示例#1
0
 def __init__(self, genesis, key, network, env, time_offset=5):
     # Create a chain object
     self.chain = Chain(genesis, env=env)
     # Use the validator's time as the chain's time
     self.chain.time = lambda: self.get_timestamp()
     # My private key
     self.key = key
     # My address
     self.address = privtoaddr(key)
     # My randao
     self.randao = RandaoManager(sha3(self.key))
     # Pointer to the test p2p network
     self.network = network
     # Record of objects already received and processed
     self.received_objects = {}
     # The minimum eligible timestamp given a particular number of skips
     self.next_skip_count = 0
     self.next_skip_timestamp = 0
     # This validator's indices in the state
     self.indices = None
     # Code that verifies signatures from this validator
     self.validation_code = generate_validation_code(privtoaddr(key))
     # Parents that this validator has already built a block on
     self.used_parents = {}
     # This validator's clock offset (for testing purposes)
     self.time_offset = random.randrange(time_offset) - (time_offset // 2)
     # Give this validator a unique ID
     self.id = len(ids)
     ids.append(self.id)
     self.find_my_indices()
     self.cached_head = self.chain.head_hash
示例#2
0
def test_lock(account, password, privkey):
    assert not account.locked
    assert account.address == privtoaddr(privkey)
    assert account.privkey == privkey
    assert account.pubkey is not None
    account.unlock(password + 'fdsa')
    account.lock()
    assert account.locked
    assert account.address == privtoaddr(privkey)
    assert account.privkey is None
    assert account.pubkey is None
    with pytest.raises(ValueError):
        account.unlock(password + 'fdsa')
    account.unlock(password)
示例#3
0
def test_unlock(keystore, password, privkey, uuid):
    account = Account(keystore)
    assert account.locked
    account.unlock(password)
    assert not account.locked
    assert account.privkey == privkey
    assert account.address == privtoaddr(privkey)
def make_transaction( src_priv_key, dst_address, value, data ):
    src_address = b2h( utils.privtoaddr(src_priv_key) )
    nonce = get_num_transactions( src_address )
    gas_price = get_gas_price_in_wei()
    data_as_string = b2h(data)
    start_gas = eval_startgas( src_address, dst_address, value, data_as_string, gas_price )
    
    nonce = int( nonce, 16 )
    gas_price = int( gas_price, 16 )
    start_gas = int( start_gas, 16 ) + 100000
    
    tx = transactions.Transaction( nonce,
                                   gas_price,
                                   start_gas,
                                   dst_address,
                                   value,
                                   data ).sign(src_priv_key)
    
    
                                   
    tx_hex  = b2h(rlp.encode(tx))
    tx_hash = b2h( tx.hash )
    if use_ether_scan:
        params = [{"hex" : "0x" + tx_hex }]
    else:
        params = ["0x" + tx_hex]
    return_value = json_call( "eth_sendRawTransaction", params )                       
    if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000":
        print "Transaction failed"
        return False
    wait_for_confirmation(tx_hash)
    return return_value        
示例#5
0
def test_decode_transfer():
    encoded_data = "0500000000000000000000010bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd823110747000000000000000000000000000000000000000000000000000000000000000160d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df510000000000000000000000000000000000000000000000000000000000000000ff9636ccb66e73219fd166cd6ffbc9c6215f74ff31c1fd4131cf532b29ee096f65278c459253fba65bf019c723a68bb4a6153ea8378cd1b15d55825e1a291b6f00"
    bad_encoded_data = "0500000000000000000000010bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd823110747000000000000000000000000000000000000000000000000000000000000000160d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df510000000000000000000000000000000000000000000000000000000000000000ff9636ccb66e73219fd166cd6ffbc9c6215f74ff31c1fd4131cf532b29ee096f65278c459253fba65bf019c723a68bb4a6153ea8378cd1b15d55825e1a291b6f0001"
    data = encoded_data.decode("hex")
    bad_data = bad_encoded_data.decode("hex")
    s = tester.state()
    c = s.abi_contract(decode_code, language="solidity")
    o1 = c.decodeTransfer(data)
    assert data[0] == "\x05"  # make sure data has right cmdid
    assert len(data) == 213
    nonce = o1[0]
    assert nonce == 1
    asset = o1[1]
    assert asset == sha3("asset")[:20].encode("hex")
    recipient = o1[2]
    assert len(recipient) == 40
    assert recipient == privtoaddr("y" * 32).encode("hex")
    balance = o1[3]
    assert balance == 1
    optionalLocksroot = o1[4]
    assert optionalLocksroot == "60d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df51".decode("hex")
    optionalSecret = o1[5]
    assert optionalSecret == "0000000000000000000000000000000000000000000000000000000000000000".decode("hex")
    signature = "ff9636ccb66e73219fd166cd6ffbc9c6215f74ff31c1fd4131cf532b29ee096f65278c459253fba65bf019c723a68bb4a6153ea8378cd1b15d55825e1a291b6f00".decode(
        "hex"
    )
    r = o1[6]
    s = o1[7]
    v = o1[8]
    assert r == signature[:32]
    assert s == signature[32:64]
    assert v == int(signature[64].encode("hex"))
    with pytest.raises(TransactionFailed):
        c.decodeSecret(bad_data)
示例#6
0
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

    priv = utils.sha3('some big long brainwallet password')
    pub = bitcoin.privtopub(priv)

    msghash = utils.sha3('the quick brown fox jumps over the lazy dog')

    pk = PrivateKey(priv, raw=True)
    signature = pk.ecdsa_recoverable_serialize(
        pk.ecdsa_sign_recoverable(msghash, raw=True)
    )
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    V = utils.safe_ord(signature[64]) + 27
    R = big_endian_to_int(signature[0:32])
    S = big_endian_to_int(signature[32:64])

    assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub)

    addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])
    assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr

    result = c.test_ecrecover(utils.big_endian_to_int(msghash), V, R, S)
    assert result == addr
示例#7
0
    def send_transaction(self, sender, to, value=0, data='', startgas=0, gasprice=10 * denoms.szabo):
        "can send a locally signed transaction if privkey is given"
        assert self.privkey or sender
        if self.privkey:
            _sender = sender
            sender = privtoaddr(self.privkey)
            assert sender == _sender
        assert sender
        # fetch nonce
        nonce = self.nonce(sender)
        if not startgas:
            startgas = quantity_decoder(self.call('eth_gasLimit')) - 1

        # create transaction
        tx = Transaction(nonce, gasprice, startgas, to=to, value=value, data=data)
        if self.privkey:
            tx.sign(self.privkey)
        tx_dict = tx.to_dict()
        tx_dict.pop('hash')
        for k, v in dict(gasprice='gasPrice', startgas='gas').items():
            tx_dict[v] = tx_dict.pop(k)
        tx_dict['sender'] = sender
        res = self.eth_sendTransaction(**tx_dict)
        assert len(res) in (20, 32)
        return res.encode('hex')
示例#8
0
def test_eth_sign(web3, skip_if_testrpc):
    skip_if_testrpc(web3)

    private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a'
    private_key = decode_hex(private_key_hex)

    # This imports the private key into the running geth instance and unlocks
    # the account so that it can sign things.
    # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0`
    address = web3.personal.importRawKey(private_key, "password")
    web3.personal.unlockAccount(address, "password")

    assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address)
    assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0'

    # the data to be signed
    data = b'1234567890abcdefghijklmnopqrstuvwxyz'
    # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3`
    data_hash = web3.sha3(data, encoding=None)
    data_hash_bytes = decode_hex(data_hash)

    assert force_bytes(data_hash) == sha3(data)

    priv_key = PrivateKey(flags=ALL_FLAGS)
    priv_key.set_raw_privkey(private_key)

    # sanit check the extract_ecdsa_signer function works as expected.
    vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256)
    vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig)
    vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id))
    vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full))

    assert vector_address == address

    # Now have geth sign some data.
    signature_hex = web3.eth.sign(address, data)
    signature_bytes = decode_hex(signature_hex)

    actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes)

    assert actual_signer == address

    # Verify the signature against the public key derived from the
    # original private key.  It fails.
    rec_id = signature_bytes[64]
    if is_string(rec_id):
        rec_id = ord(rec_id)
    recoverable_signature = priv_key.ecdsa_recoverable_deserialize(
        signature_bytes[:64],
        rec_id,
    )
    signature = priv_key.ecdsa_recoverable_convert(recoverable_signature)
    is_valid = priv_key.pubkey.ecdsa_verify(
        msg=data,
        raw_sig=signature,
        digest=sha3_256,
    )

    assert is_valid
示例#9
0
def test_decode_mediated_transfer():
    encoded_data = "070000000000000000000001000000000000001f0bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd8231107473e20ab25eb721dd4b691516238df14f0f5d3f7a3ea0c0d77f61162072c606eff3d4ee1368ef600e960d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df515601c4475f2f6aa73d6a70a56f9c756f24d211a914cc7aff3fb80d2d8741c8680000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001d000000000000000000000000000000000000000000000000000000000000000079d1479c11af904096d7e179c4184b84fd5765f0a0ab1cf44578ef7a545e1b7157c73df9c3ee2797ee379eb05b1b239cea0eec47f9e03adc546a4c0ff7dcc3a601"

    data = encoded_data.decode("hex")
    s = tester.state()
    c = s.abi_contract(decode_code, language="solidity")

    assert data[0] == "\x07"  # make sure data has right cmdid
    assert len(data) == 325
    o1 = c.decodeMediatedTransfer1(data)
    o2 = c.decodeMediatedTransfer2(data)
    nonce = o1[0]
    assert nonce == 1
    expiration = o1[1]
    assert expiration == int("000000000000001f", 16)
    asset = o1[2]
    assert len(asset) == 40
    assert asset == sha3("asset")[:20].encode("hex")
    recipient = o1[3]
    assert len(recipient) == 40
    assert recipient == privtoaddr("y" * 32).encode("hex")
    target = o1[4]
    assert len(target) == 40
    assert target == privtoaddr("z" * 32).encode("hex")
    initiator = o1[5]
    assert len(initiator) == 40
    assert initiator == privtoaddr("x" * 32).encode("hex")
    locksroot = o1[6]
    assert locksroot == "60d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df51".decode("hex")
    hashlock = o2[0]
    assert hashlock == sha3("x" * 32)
    balance = o2[1]
    assert balance == 1
    amount = o2[2]
    assert amount == 29  # int('000000000000000000000000000000000000000000000000000000000000001d', 16)
    fee = o2[3]
    assert fee == 0
    signature = "79d1479c11af904096d7e179c4184b84fd5765f0a0ab1cf44578ef7a545e1b7157c73df9c3ee2797ee379eb05b1b239cea0eec47f9e03adc546a4c0ff7dcc3a601".decode(
        "hex"
    )
    r = o2[4]
    s = o2[5]
    v = o2[6]
    assert r == signature[:32]
    assert s == signature[32:64]
    assert v == int(signature[64].encode("hex"))
示例#10
0
 def __init__(self, app):
     self.config = app.config
     self.db = app.services.db
     assert self.db is not None
     super(ChainService, self).__init__(app)
     log.info('initializing chain')
     self.chain = Chain(self.db, new_head_cb=self._on_new_head)
     self.synchronizer = Synchronizer(self.chain)
     self.chain.coinbase = privtoaddr(self.config['eth']['privkey_hex'].decode('hex'))
示例#11
0
 def __init__(self, app):
     super(RNOService, self).__init__(app)
     log.info('Initializing RNO')
     self.config = app.config
     self.interrupt = Event()
     self.tx_queue = Queue()  # thread safe
     self.privkey_hex = self.config['eth']['privkey_hex'].decode('hex')
     self.my_addr = privtoaddr(self.privkey_hex)
     self.eccx = ECCx(None, self.privkey_hex)
示例#12
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))
        self.v, self.r, self.s = ecdsa_raw_sign(rawhash, key)
        self.sender = utils.privtoaddr(key)
        return self
示例#13
0
def test_epoch_with_validator_logs(casper, new_epoch, get_logs, casper_chain,
                                   deposit_validator, funded_privkey,
                                   deposit_amount, mk_suggested_vote):
    validator_index = casper.next_validator_index()
    deposit_validator(funded_privkey, deposit_amount)
    # Validator is registered in Casper
    assert validator_index == casper.validator_indexes(
        utils.privtoaddr(funded_privkey))

    for _ in range(3):
        new_epoch()
    last_block_number = casper_chain.block.number
    # Allowed to vote now
    assert casper.validators__start_dynasty(
        validator_index) == casper.dynasty()

    casper.vote(mk_suggested_vote(validator_index, funded_privkey))
    receipt = casper_chain.head_state.receipts[-1]
    logs = get_logs(receipt, casper)
    assert len(logs) == 3  # Vote + Last Epoch + Prev Epoch
    last_epoch_hash = casper_chain.chain.get_blockhash_by_number(
        last_block_number - 1)
    last_epoch_log = [
        log for log in logs if log['_event_type'] == b'Epoch'
        and log['_checkpoint_hash'] == last_epoch_hash
    ][0]
    assert last_epoch_log['_is_justified'] is True
    assert last_epoch_log['_is_finalized'] is False

    new_epoch()
    last_block_number = casper_chain.block.number
    casper.vote(mk_suggested_vote(validator_index, funded_privkey))

    receipt = casper_chain.head_state.receipts[-1]
    logs = get_logs(receipt, casper)
    assert len(logs) == 3  # Vote + Last Epoch + Prev Epoch
    last_epoch_hash = casper_chain.chain.get_blockhash_by_number(
        last_block_number - 1)
    last_epoch_log = [
        log for log in logs if log['_event_type'] == b'Epoch'
        and log['_checkpoint_hash'] == last_epoch_hash
    ][0]
    prev_epoch_hash = casper_chain.chain.get_blockhash_by_number(
        last_block_number - casper.EPOCH_LENGTH() - 1)
    prev_epoch_log = [
        log for log in logs if log['_event_type'] == b'Epoch'
        and log['_checkpoint_hash'] == prev_epoch_hash
    ][0]

    assert prev_epoch_log['_is_justified'] is True
    assert prev_epoch_log['_is_finalized'] is True

    assert last_epoch_log['_is_justified'] is True
    assert last_epoch_log['_is_finalized'] is False
示例#14
0
def test_deposit_log(casper, funded_privkey, new_epoch, deposit_validator,
              deposit_amount, get_last_log, casper_chain):
    new_epoch()
    assert casper.current_epoch() == 1
    assert casper.next_validator_index() == 1

    validator_index = casper.next_validator_index()
    deposit_validator(funded_privkey, deposit_amount)
    # Validator is registered in Casper
    assert validator_index == casper.validator_indexes(utils.privtoaddr(funded_privkey))

    # Deposit log
    log = get_last_log(casper_chain, casper)
    assert {'_event_type', '_from', '_validation_address', '_validator_index', '_start_dyn', '_amount'} == log.keys()
    assert log['_event_type'] == b'Deposit'
    assert log['_from'] == '0x' + utils.encode_hex(utils.privtoaddr(funded_privkey))
    assert log['_validation_address'] == casper.validators__addr(validator_index)
    assert log['_validator_index'] == validator_index
    assert log['_start_dyn'] == casper.validators__start_dynasty(validator_index)
    assert log['_amount'] == deposit_amount
示例#15
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if key in (0, '', '\x00' * 32):
            raise InvalidTransaction("Zero privkey cannot sign")
        rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))
        self.v, self.r, self.s = ecdsa_raw_sign(rawhash, key)
        self.sender = utils.privtoaddr(key)
        return self
示例#16
0
 def __init__(self, num_nodes=2, simenv=None):
     if simenv:
         self.simenv = simpy.Environment()
     else:
         self.simenv = None
     privkeys = mk_privkeys(num_nodes)
     validators = [privtoaddr(p) for p in privkeys]
     self.nodes = []
     for i in range(num_nodes):
         app = AppMock(privkeys[i], validators, self.simenv)
         self.nodes.append(app)
示例#17
0
 def __init__(self, num_nodes=2, simenv=None):
     if simenv:
         self.simenv = simpy.Environment()
     else:
         self.simenv = None
     privkeys = mk_privkeys(num_nodes)
     validators = [privtoaddr(p) for p in privkeys]
     self.nodes = []
     for i in range(num_nodes):
         app = AppMock(privkeys[i], validators, self.simenv)
         self.nodes.append(app)
示例#18
0
 def deposit(self):
     if len(self.inp) != 3:
         raise Exception("Wrong number of inputs for deposit")
     amount1 = int(self.inp[1])
     key = utils.normalize_key(self.inp[2])
     newOwner1 = utils.privtoaddr(key)
     newOwner2, amount2 = utils.normalize_address(b'\x00' * 20), 0
     tx = Transaction(0, 0, 0, 0, 0, 0, newOwner1, amount1, newOwner2,
                      amount2, 0)
     self.client.deposit(tx)
     print("Succesfully deposited %s to %s" % (amount1, newOwner1))
示例#19
0
 def __init__(self, roles=list()):
     self.player_roles = roles
     self.contract_player = dict([(player.contract.address, player)
                                  for player in roles])
     self.private_key = roles[0].sk
     self.public_address = utils.privtoaddr(self.private_key)
     self.wants_rebalance = True  # TODO This should be set as a preference at some point.
     self.frozen_channels = set()
     self.rebalance_transactions = None
     self.rebalance_participants = None
     self.rebalance_signatures = None
示例#20
0
def test_decode_mediated_transfer():
    encoded_data = '070000000000000000000001000000000000001f0bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd8231107473e20ab25eb721dd4b691516238df14f0f5d3f7a3ea0c0d77f61162072c606eff3d4ee1368ef600e960d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df515601c4475f2f6aa73d6a70a56f9c756f24d211a914cc7aff3fb80d2d8741c8680000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001d000000000000000000000000000000000000000000000000000000000000000079d1479c11af904096d7e179c4184b84fd5765f0a0ab1cf44578ef7a545e1b7157c73df9c3ee2797ee379eb05b1b239cea0eec47f9e03adc546a4c0ff7dcc3a601'

    data = encoded_data.decode('hex')
    s = tester.state()
    c = s.abi_contract(decode_code, language="solidity")

    assert data[0] == '\x07'  # make sure data has right cmdid
    assert len(data) == 325
    o1 = c.decodeMediatedTransfer1(data)
    o2 = c.decodeMediatedTransfer2(data)
    nonce = o1[0]
    assert nonce == 1
    expiration = o1[1]
    assert expiration == int('000000000000001f', 16)
    asset = o1[2]
    assert len(asset) == 40
    assert asset == sha3('asset')[:20].encode('hex')
    recipient = o1[3]
    assert len(recipient) == 40
    assert recipient == privtoaddr('y' * 32).encode('hex')
    target = o1[4]
    assert len(target) == 40
    assert target == privtoaddr('z' * 32).encode('hex')
    initiator = o2[0]
    assert len(initiator) == 40
    assert initiator == privtoaddr('x' * 32).encode('hex')
    locksroot = o2[1]
    assert locksroot == '60d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df51'.decode(
        'hex')
    hashlock = o2[2]
    assert hashlock == sha3('x' * 32)
    balance = o2[3]
    assert balance == 1
    amount = o2[4]
    assert amount == 29  #int('000000000000000000000000000000000000000000000000000000000000001d', 16)
    fee = o2[5]
    assert fee == 0
    signature = o2[6]
    assert signature == '79d1479c11af904096d7e179c4184b84fd5765f0a0ab1cf44578ef7a545e1b7157c73df9c3ee2797ee379eb05b1b239cea0eec47f9e03adc546a4c0ff7dcc3a601'.decode(
        'hex')
def get_account_balance( key ):
    url = "https://testnet.etherscan.io/api"
    payload = {"module" : "account",
               "action" : "balance",
               "tag" : "latest",
               "address" : "0x" + b2h( utils.privtoaddr(key) ), 
               "apikey" : ether_scan_api_key }
    response = requests.post( url, params=payload )
    balance = response.json()[ 'result' ]
    if balance is None:
        return 0
    return int(balance)
示例#22
0
 def direct_tx(self, transaction):
     self.last_tx = transaction
     if self.last_sender is not None and privtoaddr(
             self.last_sender) != transaction.sender:
         self.last_sender = None
     success, output = apply_transaction(self.head_state, transaction)
     self.block = self.block.copy(
         transactions=self.block.transactions + (transaction,)
     )
     if not success:
         raise TransactionFailed()
     return output
示例#23
0
def create_wallet():
    # TODO is urandom secure??? maybe need to use something else
    private_key = utils.sha3(os.urandom(4096))

    # TODO encrypt and store these keys somewhere for user?!?!
    raw_address = utils.privtoaddr(private_key)
    account_address = utils.checksum_encode(raw_address)

    print("DO NOT LOSS PRIVATE KEY OR PUBLIC KEY NO WAY TO RECOVER")
    print("PRIVATE KEY", private_key.hex(), "PUBLIC KEY", account_address)

    return private_key, account_address
示例#24
0
def create_private_key(output_file):
    password = ''
    password2 = ' '
    while password != password2:
        password = getpass.getpass('Type the password: '******'Retype the password: '******'Private key succesfully generated.')
    addr = eth.privtoaddr(priv)
    logging.info("The generated address is '{}'".format('0x' +
                                                        eth.encode_hex(addr)))
    store_private_key(priv, password, output_file)
示例#25
0
    def __init__(self, contract_address, contract_abi_string,
                 ethereum_chain_id, http_provider, websocket_provider,
                 gas_price_gwei, gas_limit, contract_owner_private_key):

        super(MintableERC20Processor,
              self).__init__(contract_address, contract_abi_string,
                             ethereum_chain_id, http_provider,
                             websocket_provider, gas_price_gwei, gas_limit)

        self.master_wallet_private_key = contract_owner_private_key
        self.master_wallet_address = Web3.toChecksumAddress(
            utils.privtoaddr(self.master_wallet_private_key))
示例#26
0
def setup(host, port, contract, gas, gas_price, private_key):
    gas = int(gas)
    gas_price = int(gas_price)
    json_rpc = EthJsonRpc(host, port)
    coinbase = json_rpc.eth_coinbase()["result"]
    if private_key:
        print "Your address for your private key: {}".format(
            privtoaddr(private_key.decode('hex')).encode('hex'))
    else:
        print "Your coinbase: {}".format(coinbase)
    contract_abi = json.loads(
        '[{"inputs": [], "constant": true, "type": "function", "name": "startDate", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "CROWDFUNDING_PERIOD", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "emergencyCall", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [{"type": "address", "name": "singularDTVFundAddress"}, {"type": "address", "name": "singularDTVTokenAddress"}], "constant": false, "type": "function", "name": "setup", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "withdrawFunding", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "fundBalance", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "singularDTVFund", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "baseValue", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "TOKEN_TARGET", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "singularDTVToken", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "owner", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [{"type": "uint256", "name": "valueInWei"}], "constant": false, "type": "function", "name": "changeBaseValue", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [{"type": "address", "name": ""}], "constant": true, "type": "function", "name": "investments", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "fund", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "stage", "outputs": [{"type": "uint8", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "updateStage", "outputs": [{"type": "uint8", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "valuePerShare", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "TOKEN_LOCKING_PERIOD", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "campaignEndedSuccessfully", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "workshopWaited2Years", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "CAP", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "withdrawForWorkshop", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "type": "constructor"}]'
    )
    translator = ContractTranslator(contract_abi)
    data = translator.encode("emergencyCall", ()).encode("hex")
    bc_return_val = json_rpc.eth_call(to_address=contract, data=data)["result"]
    result_decoded = translator.decode("emergencyCall",
                                       bc_return_val[2:].decode("hex"))[0]
    if result_decoded:
        if private_key:
            address = privtoaddr(private_key.decode('hex'))
            nonce = int(
                json_rpc.eth_getTransactionCount('0x' + address.encode('hex'))
                ["result"][2:], 16)
            tx = Transaction(nonce, gas_price, gas, contract, 0,
                             data.decode('hex'))
            tx.sign(private_key.decode('hex'))
            raw_tx = rlp.encode(tx).encode('hex')
            transaction_hash = json_rpc.eth_sendRawTransaction(
                "0x" + raw_tx)["result"]
        else:
            transaction_hash = json_rpc.eth_sendTransaction(
                coinbase,
                to_address=contract,
                data=data,
                gas=gas,
                gas_price=gas_price)["result"]
        wait_for_transaction_receipt(json_rpc, transaction_hash)
        print 'Transaction {} for contract {} completed.'.format(
            "emergencyCall", contract)
示例#27
0
def test_withdraw_after_majority_slash(casper, casper_chain,
                                       funded_privkeys, deposit_amount, new_epoch,
                                       induct_validators, mk_suggested_vote, mk_slash_votes):
    validator_indexes = induct_validators(funded_privkeys, [deposit_amount] * len(funded_privkeys))

    # 0th gets slashed
    slashed_indexes = validator_indexes[:-1]
    slashed_privkeys = funded_privkeys[:-1]
    slashed_public_keys = [
        utils.privtoaddr(slashed_privkey) for slashed_privkey in slashed_privkeys
    ]
    # the rest remain
    logged_in_index = validator_indexes[-1]
    logged_in_privkey = funded_privkeys[-1]

    assert len(slashed_indexes) / float(len(funded_privkeys)) >= 1 / 3.0

    for slashed_index, slashed_privkey in zip(slashed_indexes, slashed_privkeys):
        vote_1, vote_2 = mk_slash_votes(slashed_index, slashed_privkey)
        casper.slash(vote_1, vote_2)

    current_epoch = casper.current_epoch()
    assert casper.total_slashed(current_epoch) == deposit_amount * len(slashed_indexes)
    assert casper.total_slashed(current_epoch + 1) == 0

    # artificially simulate the slashed validators voting
    # normally if this occured, the validators would likely stop
    # voting and their deposits would have to bleed out.
    for i, validator_index in enumerate(validator_indexes):
        casper.vote(mk_suggested_vote(validator_index, funded_privkeys[i]))
    new_epoch()

    # slashed validators can withdraw after end_dynasty plus delay
    for i in range(casper.WITHDRAWAL_DELAY() + 1):
        casper.vote(mk_suggested_vote(logged_in_index, logged_in_privkey))
        new_epoch()

    assert casper.dynasty() > casper.validators__end_dynasty(slashed_indexes[0])

    prev_balances = [
        casper_chain.head_state.get_balance(slashed_public_key)
        for slashed_public_key in slashed_public_keys
    ]
    for slashed_index in slashed_indexes:
        casper.withdraw(slashed_index)

    for slashed_public_key, prev_balance in zip(slashed_public_keys, prev_balances):
        balance = casper_chain.head_state.get_balance(slashed_public_key)
        assert balance == prev_balance

    for slashed_index in slashed_indexes:
        assert_validator_empty(casper, slashed_index)
def ethereum():
    form = EthForm()
    if form.submit2.data and form.validate():
        api = Savoir(current_app.config['CHAIN_RPC_USER'],
                     current_app.config['CHAIN_RPC_PASSWORD'],
                     current_app.config['CHAIN_RPC_HOST'],
                     current_app.config['CHAIN_RPC_PORT'],
                     current_app.config['CHAIN_NAME'])

        url = form.url.data
        if not url:
            url = current_app.config['GETH_URL']
        w3 = Web3(HTTPProvider(url))
        if current_app.config['GETH_MODE'] == 'dev':
            w3.middleware_stack.inject(geth_poa_middleware, layer=0)
            gasPrice = 2000000000
        else:
            gasPrice = w3.eth.gasPrice
            # gasPrice = w3.eth.generateGasPrice()
        privkey = current_app.config['ETH_KEY']
        account = w3.toChecksumAddress(utils.privtoaddr(privkey))
        block_hash = api.getblockchaininfo().get('bestblockhash')

        nonce = w3.eth.getTransactionCount(account)
        startgas = round(w3.eth.estimateGas({'data': block_hash}))
        to = account
        value = 0

        balance = w3.eth.getBalance(account)
        cost = startgas * gasPrice
        if cost > balance:
            flash('Your account has insufficient funds!')
            return redirect(url_for('main.ethereum'))

        tx = transactions.Transaction(nonce, gasPrice, startgas, to, value,
                                      block_hash)
        tx.sign(privkey)
        rlp_tx = rlp.encode(tx)
        hex_tx = w3.toHex(rlp_tx)

        response = w3.eth.sendRawTransaction(hex_tx)
        trans = EthTx(address=account,
                      txid=response,
                      mchash=block_hash[2:],
                      sent=datetime.now())
        db.session.add(trans)
        db.session.commit()
        flash('Congratulations, you validated the Multichain on Ethereum!')
        return redirect(url_for('main.index'))
    return render_template('main/admin.html',
                           title='Validate TrialChain',
                           form=form)
示例#29
0
def generate_genesis(path=None, num_participants=1):
    privkeys = [
        utils.sha3(utils.to_string(i)) for i in range(num_participants)
    ]
    addrs = [utils.privtoaddr(k) for k in privkeys]
    deposit_sizes = [i * 500 + 500 for i in range(num_participants)]
    randaos = [RandaoManager(utils.sha3(k)) for k in privkeys]

    validators = [(generate_validation_code(a), ds * 10**18, r.get(9999), a)
                  for a, ds, r in zip(addrs, deposit_sizes, randaos)]
    s = make_casper_genesis(validators=validators,
                            alloc={a: {
                                'balance': 10**18
                            }
                                   for a in addrs},
                            timestamp=int(time.time()),
                            epoch_length=100)
    genesis_hash = apply_const_message(
        s,
        sender=casper_config['METROPOLIS_ENTRY_POINT'],
        to=casper_config['METROPOLIS_BLOCKHASH_STORE'],
        data=utils.encode_int32(0))
    genesis_number = call_casper(s, 'getBlockNumber')
    print('genesis block hash: %s' % utils.encode_hex(genesis_hash))
    print('genesis block number: %d' % genesis_number)
    print('%d validators: %r' %
          (num_participants, [utils.encode_hex(a) for a in addrs]))

    snapshot = s.to_snapshot()
    header = s.prev_headers[0]
    genesis = {
        "nonce": "0x" + utils.encode_hex(header.nonce),
        "difficulty": utils.int_to_hex(header.difficulty),
        "mixhash": "0x" + utils.encode_hex(header.mixhash),
        "coinbase": "0x" + utils.encode_hex(header.coinbase),
        "timestamp": utils.int_to_hex(header.timestamp),
        "parentHash": "0x" + utils.encode_hex(header.prevhash),
        "extraData": "0x" + utils.encode_hex(header.extra_data),
        "gasLimit": utils.int_to_hex(header.gas_limit),
        "alloc": snapshot["alloc"]
    }

    if path:
        with open(path, 'w') as f:
            json.dump(genesis,
                      f,
                      sort_keys=False,
                      indent=4,
                      separators=(',', ': '))
        print('casper genesis generated')
    else:
        return genesis
示例#30
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
示例#31
0
    def get_priv_pub_addr(self, root_seed, n, change=0):
        mk = bip32_master_key(root_seed)

        hasha = bip32_ckd(
            bip32_ckd(
                bip32_ckd(
                    bip32_ckd(bip32_ckd(mk, 44 + 2**31),
                              self.coin_index + 2**31), 2**31), change), n)
        pub = u.privtopub(hasha)
        priv = bip32_extract_key(hasha)
        addr = u.checksum_encode("0x" + u.encode_hex(u.privtoaddr(priv[:-2])))

        return priv[:-2], pub, addr
示例#32
0
 def __init__(self, genesis, key, network, env, time_offset=5):
     # Create a chain object
     self.chain = Chain(genesis, env=env)
     # Create a transaction queue
     self.txqueue = TransactionQueue()
     # Use the validator's time as the chain's time
     self.chain.time = lambda: self.get_timestamp()
     # My private key
     self.key = key
     # My address
     self.address = privtoaddr(key)
     # My randao
     self.randao = RandaoManager(sha3(self.key))
     # Pointer to the test p2p network
     self.network = network
     # Record of objects already received and processed
     self.received_objects = {}
     # The minimum eligible timestamp given a particular number of skips
     self.next_skip_count = 0
     self.next_skip_timestamp = 0
     # Is this validator active?
     self.active = False
     # Code that verifies signatures from this validator
     self.validation_code = generate_validation_code(privtoaddr(key))
     # Validation code hash
     self.vchash = sha3(self.validation_code)
     # Parents that this validator has already built a block on
     self.used_parents = {}
     # This validator's clock offset (for testing purposes)
     self.time_offset = random.randrange(time_offset) - (time_offset // 2)
     # Determine the epoch length
     self.epoch_length = self.call_casper('getEpochLength')
     # My minimum gas price
     self.mingasprice = 20 * 10**9
     # Give this validator a unique ID
     self.id = len(ids)
     ids.append(self.id)
     self.update_activity_status()
     self.cached_head = self.chain.head_hash
示例#33
0
文件: casper.py 项目: yep/research
 def __init__(self, genesis, key, network, env, time_offset=5):
     # Create a chain object
     self.chain = Chain(genesis, env=env)
     # Create a transaction queue
     self.txqueue = TransactionQueue()
     # Use the validator's time as the chain's time
     self.chain.time = lambda: self.get_timestamp()
     # My private key
     self.key = key
     # My address
     self.address = privtoaddr(key)
     # My randao
     self.randao = RandaoManager(sha3(self.key))
     # Pointer to the test p2p network
     self.network = network
     # Record of objects already received and processed
     self.received_objects = {}
     # The minimum eligible timestamp given a particular number of skips
     self.next_skip_count = 0
     self.next_skip_timestamp = 0
     # Is this validator active?
     self.active = False
     # Code that verifies signatures from this validator
     self.validation_code = generate_validation_code(privtoaddr(key))
     # Validation code hash
     self.vchash = sha3(self.validation_code)
     # Parents that this validator has already built a block on
     self.used_parents = {}
     # This validator's clock offset (for testing purposes)
     self.time_offset = random.randrange(time_offset) - (time_offset // 2)
     # Determine the epoch length
     self.epoch_length = self.call_casper('getEpochLength')
     # My minimum gas price
     self.mingasprice = 20 * 10**9
     # Give this validator a unique ID
     self.id = len(ids)
     ids.append(self.id)
     self.update_activity_status()
     self.cached_head = self.chain.head_hash
示例#34
0
    def test_ecrecover(self):
        priv = b.sha256('some big long brainwallet password')
        pub = b.privtopub(priv)

        msghash = b.sha256('the quick brown fox jumps over the lazy dog')
        V, R, S = b.ecdsa_raw_sign(msghash, priv)
        assert b.ecdsa_raw_verify(msghash, (V, R, S), pub)

        addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:]
        assert utils.privtoaddr(priv) == addr

        result = self.c.test_ecrecover(utils.big_endian_to_int(msghash.decode('hex')), V, R, S)
        assert result == utils.big_endian_to_int(addr)
示例#35
0
def normal_case():
    print "=================================NORMAL CASE===================================="
    s = tester.state()
    alice = tester.k0
    bob = tester.k1
    silverToken = s.abi_contract(tokenCode, sender=alice)
    goldToken = s.abi_contract(tokenCode, sender=bob)
    start = s.block.gas_used
    exchangeAlicePart = s.abi_contract(exchangeCode, sender=alice)
    exchangeBobPart = s.abi_contract(exchangeCode, sender=bob)
    
    print "Before exchange happens" 
    print "Alice has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(alice)))
    print "Bob has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(bob)))
    
    print "Alice has {token} gold token".format(token=goldToken.get_balance(utils.privtoaddr(alice)))
    print "Bob has {} gold token".format(goldToken.get_balance(utils.privtoaddr(bob)))
    pre_image = "10"
    block_timeout = 50
    exchangeAlicePart.initialize(utils.sha3(pre_image), block_timeout, utils.privtoaddr(bob), exchangeBobPart.address, goldToken.address, sender=alice)
    exchangeBobPart.initialize(exchangeAlicePart.get_secret(), block_timeout, utils.privtoaddr(alice), 0, silverToken.address, sender=bob)

    print "Alice first sends silver token to Bob part of the exchange contract"
    silverToken.send_token(exchangeBobPart.address, 500, sender=alice)
    print "Bob then sends gold token to Alice part of the exchange contract"
    goldToken.send_token(exchangeAlicePart.address, 500, sender=bob)
    print "Alice unlocks both contracts simutanously"
    exchangeAlicePart.transfer(pre_image, sender=alice)
    print "" 
    print ""
    print "After exchange happens" 
    print "Alice has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(alice)))
    print "Bob has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(bob)))
    
    print "Alice has {token} gold token".format(token=goldToken.get_balance(utils.privtoaddr(alice)))
    print "Bob has {} gold token".format(goldToken.get_balance(utils.privtoaddr(bob)))
    end = s.block.gas_used
    print "Gas used is {}".format(end - start)
 def test(self):
     # Create 50 accounts
     accounts = []
     keys = []
     account_count = 50
     for i in range(account_count):
         keys.append(sha3(to_string(i)))
         accounts.append(privtoaddr(keys[-1]))
         self.s.block.set_balance(accounts[-1], 10**18)
     # Create wallet
     required_accounts = 2
     constructor_parameters = (accounts, required_accounts)
     self.multisig_wallet = self.s.abi_contract(
         open('solidity/MultiSigWallet.sol').read(),
         language='solidity',
         constructor_parameters=constructor_parameters)
     # Create ABIs
     multisig_abi = self.multisig_wallet.translator
     # Should not be able to breach the maximum number of owners
     key_51 = sha3(to_string(51))
     account_51 = privtoaddr(key_51)
     add_owner_data = multisig_abi.encode("addOwner", [account_51])
     self.assertFalse(self.multisig_wallet.isOwner(account_51))
     add_owner_tx = self.multisig_wallet.submitTransaction(
         self.multisig_wallet.address, 0, add_owner_data, sender=keys[0])
     include_pending = True
     exclude_executed = False
     self.assertEqual(
         self.multisig_wallet.getTransactionIds(0, 1, include_pending,
                                                exclude_executed),
         [add_owner_tx])
     # Transaction is confirmed but cannot be executed due to too many owners.
     self.multisig_wallet.confirmTransaction(add_owner_tx, sender=keys[1])
     # Transaction remains pending
     self.assertEqual(
         self.multisig_wallet.getTransactionIds(0, 1, include_pending,
                                                exclude_executed),
         [add_owner_tx])
示例#37
0
def call_tx(state,
            ct,
            func,
            args,
            sender,
            to,
            value=0,
            startgas=STARTGAS,
            gasprice=GASPRICE):
    # Transaction(nonce, gasprice, startgas, to, value, data, v=0, r=0, s=0)
    tx = Transaction(state.get_nonce(utils.privtoaddr(sender)),
                     gasprice, startgas, to, value,
                     ct.encode_function_call(func, args)).sign(sender)
    return tx
示例#38
0
def test_vote_log(casper, funded_privkey, new_epoch, deposit_validator,
                     deposit_amount, get_last_log, casper_chain, mk_suggested_vote):
    new_epoch()
    validator_index = casper.next_validator_index()
    deposit_validator(funded_privkey, deposit_amount)
    # Validator is registered in Casper
    assert validator_index == casper.validator_indexes(utils.privtoaddr(funded_privkey))

    new_epoch()
    new_epoch()
    # Allowed to vote now
    assert casper.validators__start_dynasty(validator_index) == casper.dynasty()

    casper.vote(mk_suggested_vote(validator_index, funded_privkey))
    # Vote log
    log = get_last_log(casper_chain, casper)
    assert {'_event_type', '_from', '_validator_index', '_target_hash', '_target_epoch', '_source_epoch'} == log.keys()
    assert log['_event_type'] == b'Vote'
    assert log['_from'] == '0x' + utils.encode_hex(utils.privtoaddr(funded_privkey))
    assert log['_validator_index'] == validator_index
    assert log['_target_hash'] == casper.recommended_target_hash()
    assert log['_target_epoch'] == casper.recommended_source_epoch() + 1
    assert log['_source_epoch'] == casper.recommended_source_epoch()
示例#39
0
def test_logout_log(casper, funded_privkey, new_epoch, deposit_validator, logout_validator,
                  deposit_amount, get_last_log, casper_chain, mk_suggested_vote):
    new_epoch()
    validator_index = casper.next_validator_index()
    deposit_validator(funded_privkey, deposit_amount)
    # Validator is registered in Casper
    assert validator_index == casper.validator_indexes(utils.privtoaddr(funded_privkey))

    new_epoch()
    new_epoch()
    # Allowed to vote now
    assert casper.validators__start_dynasty(validator_index) == casper.dynasty()

    casper.vote(mk_suggested_vote(validator_index, funded_privkey))

    logout_validator(validator_index, funded_privkey)
    # Logout log
    log = get_last_log(casper_chain, casper)
    assert {'_event_type', '_from', '_validator_index', '_end_dyn'} == log.keys()
    assert log['_event_type'] == b'Logout'
    assert log['_from'] == '0x' + utils.encode_hex(utils.privtoaddr(funded_privkey))
    assert log['_validator_index'] == validator_index
    assert log['_end_dyn'] == casper.dynasty() + casper.DYNASTY_LOGOUT_DELAY()
示例#40
0
    def setup_and_deploy_urs_contracts(self, sender_privkey, shard_id):
        """Deploy urs contract and its dependency
        """
        state = self.shard_head_state[shard_id]

        if used_receipt_store_utils.is_urs_setup(state, shard_id):
            return
        txs = used_receipt_store_utils.mk_initiating_txs_for_urs(
            sender_privkey, state.get_nonce(utils.privtoaddr(sender_privkey)),
            shard_id)
        for tx in txs:
            self.direct_tx(tx, shard_id=shard_id)
        self.shard_last_tx[shard_id], self.shard_last_sender[shard_id] = txs[
            -1], None
示例#41
0
def get_eth_address_with_key() -> (str, bytes):

    # import secp256k1
    # private_key = secp256k1.PrivateKey().private_key

    private_key = utils.sha3(os.urandom(4096))

    public_key = utils.checksum_encode(utils.privtoaddr(private_key))

    # If you want to use secp256k1 to calculate public_key
    # utils.checksum_encode(utils.sha3(p.pubkey.serialize(compressed=False)[1:])[-20:])

    return (public_key,
            private_key)
示例#42
0
def get_account_balance(key):
    url = "https://testnet.etherscan.io/api"
    payload = {
        "module": "account",
        "action": "balance",
        "tag": "latest",
        "address": "0x" + b2h(utils.privtoaddr(key)),
        "apikey": ether_scan_api_key
    }
    response = requests.post(url, params=payload)
    balance = response.json()['result']
    if balance is None:
        return 0
    return int(balance)
示例#43
0
    def test_self_payment(self):
        privkey = os.urandom(32)
        addr = privtoaddr(privkey)

        ecc = ECCx(privkey)
        ecc.verify = mock.Mock()
        msg = mock.Mock()
        msg.task_to_compute.provider_ethereum_address = encode_hex(addr)

        res = helpers.process_report_computed_task_no_time_check(
            msg,
            ecc,
        )
        self.assertIsInstance(res, message.tasks.RejectReportComputedTask)
示例#44
0
 def tx(self,
        sender=k0,
        to=b'\x00' * 20,
        value=0,
        data=b'',
        startgas=STARTGAS,
        gasprice=GASPRICE):
     sender_addr = privtoaddr(sender)
     self.last_sender = sender
     transaction = Transaction(self.head_state.get_nonce(sender_addr),
                               gasprice, startgas, to, value,
                               data).sign(sender)
     output = self.direct_tx(transaction)
     return output
示例#45
0
    def __init__(self, app):
        self.config = app.config
        self.db = app.services.db
        assert self.db is not None
        super(ChainService, self).__init__(app)
        log.info('initializing chain')
        self.chain = Chain(self.db, new_head_cb=self._on_new_head)
        self.synchronizer = Synchronizer(self, force_sync=None)
        self.chain.coinbase = privtoaddr(self.config['eth']['privkey_hex'].decode('hex'))

        self.block_queue = Queue(maxsize=self.block_queue_size)
        self.transaction_queue = Queue(maxsize=self.transaction_queue_size)
        self.add_blocks_lock = False
        self.broadcast_filter = DuplicatesFilter()
示例#46
0
    def test_ecrecover(self):
        priv = b.sha256('some big long brainwallet password')
        pub = b.privtopub(priv)

        msghash = b.sha256('the quick brown fox jumps over the lazy dog')
        V, R, S = b.ecdsa_raw_sign(msghash, priv)
        assert b.ecdsa_raw_verify(msghash, (V, R, S), pub)

        addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:]
        assert utils.privtoaddr(priv) == addr

        result = self.c.test_ecrecover(
            utils.big_endian_to_int(msghash.decode('hex')), V, R, S)
        assert result == utils.big_endian_to_int(addr)
示例#47
0
 def tx(self,
        sender=k0,
        to=b'\x00' * 20,
        value=0,
        data=b'',
        startgas=STARTGAS,
        gasprice=GASPRICE):
     sender_addr = privtoaddr(sender)
     transaction = Transaction(self.state.get_nonce(sender_addr), gasprice,
                               startgas, to, value, data).sign(sender)
     success, output = apply_transaction(self.state, transaction)
     if not success:
         raise TransactionFailed()
     return output
示例#48
0
def test_slash_log(casper, funded_privkey, deposit_amount, get_last_log, base_sender_privkey,
                              induct_validator, mk_vote, fake_hash, casper_chain):
    validator_index = induct_validator(funded_privkey, deposit_amount)
    assert casper.total_curdyn_deposits_in_wei() == deposit_amount

    vote_1 = mk_vote(
        validator_index,
        casper.recommended_target_hash(),
        casper.current_epoch(),
        casper.recommended_source_epoch(),
        funded_privkey
    )
    vote_2 = mk_vote(
        validator_index,
        fake_hash,
        casper.current_epoch(),
        casper.recommended_source_epoch(),
        funded_privkey
    )

    assert casper.dynasty_wei_delta(casper.dynasty() + 1) == 0
    # Save deposit before slashing
    validator_deposit = casper.deposit_size(validator_index)

    casper.slash(vote_1, vote_2)
    # Slashed!
    assert casper.deposit_size(validator_index) == 0

    # Slash log
    log = get_last_log(casper_chain, casper)
    assert {'_event_type', '_from', '_offender', '_offender_index', '_bounty', '_destroyed'} == log.keys()
    assert log['_event_type'] == b'Slash'
    assert log['_from'] == '0x' + utils.encode_hex(utils.privtoaddr(base_sender_privkey))
    assert log['_offender'] == '0x' + utils.encode_hex(utils.privtoaddr(funded_privkey))
    assert log['_offender_index'] == validator_index
    assert log['_bounty'] == math.floor(validator_deposit / 25)
    assert log['_destroyed'] == validator_deposit - log['_bounty']
示例#49
0
    def evm(self, code, sender=DEFAULT_KEY, endowment=0, gas=None):
        sendnonce = self.block.get_nonce(privtoaddr(sender))

        transaction = transactions.contract(sendnonce, gas_price, gas_limit, endowment, code)
        transaction.sign(sender)

        if gas is not None:
            transaction.startgas = gas

        (success, output) = processblock.apply_transaction(self.block, transaction)

        if not success:
            raise ContractCreationFailed()

        return output
示例#50
0
def mk_privkeys(num):
    "make privkeys that support coloring, see utils.cstr"
    privkeys = []
    assert num <= num_colors
    for i in range(num):
        j = 0
        while True:
            k = sha3(str(j))
            a = privtoaddr(k)
            an = big_endian_to_int(a)
            if an % num_colors == i:
                break
            j += 1
        privkeys.append(k)
    return privkeys
示例#51
0
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

    priv = encode_hex(utils.sha3('some big long brainwallet password'))
    pub = bitcoin.privtopub(priv)

    msghash = encode_hex(utils.sha3('the quick brown fox jumps over the lazy dog'))
    V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv)
    assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub)

    addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])
    assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr

    result = c.test_ecrecover(utils.big_endian_to_int(decode_hex(msghash)), V, R, S)
    assert result == addr
示例#52
0
def test_vote():
    h, r = 2, 3
    bh = "0" * 32
    privkey = "x" * 32
    sender = utils.privtoaddr(privkey)

    v = Vote(h, r)
    v2 = Vote(h, r, blockhash=bh)

    assert isinstance(v, Vote)
    assert isinstance(v2, Vote)

    assert isinstance(v, VoteNil)
    assert isinstance(v, rlp.Serializable)

    assert isinstance(v2, VoteBlock)

    v.sign(privkey)
    s = v.sender
    assert s == sender

    v2.sign(privkey)
    assert v2.sender == sender

    # encode
    assert len(v.get_sedes()) == len(v.fields) == 6

    vs = rlp.encode(v)
    assert isinstance(vs, bytes)
    print rlp.decode(vs)
    vd = rlp.decode(vs, Vote)
    assert isinstance(vd, VoteNil)
    assert vd.blockhash == ""
    assert vd == v

    v2s = rlp.encode(v2)
    v2d = rlp.decode(v2s, Vote)
    assert isinstance(v2d, VoteBlock)
    assert v2d.blockhash == bh
    assert v2d == v2

    assert v != v2
    assert vd != v2d

    assert len(set((v, vd))) == 1
    assert len(set((v2, v2d))) == 1
    assert len(set((v, vd, v2, v2d))) == 2
示例#53
0
def test_create_gnt(chain):
    owner_addr, receiver_addr, gnt, gntb, cdep = mysetup(chain)
    faucet, _ = chain.provider.get_or_deploy_contract('Faucet',
                                                      deploy_args=[gnt.address])

    assert gnt.call().balanceOf(faucet.address) == 0
    chain.wait.for_receipt(gnt.transact({'from': encode_hex(ethereum.tester.a0)}).transfer(
        faucet.address, 1000 * utils.denoms.ether ))
    assert gnt.call().balanceOf(faucet.address) == 1000 * utils.denoms.ether
    key = sha3(to_string(11))
    account = privtoaddr(key)

    ethereum.tester.accounts.append(account)
    ethereum.tester.keys.append(key)

    assert chain.web3.eth.getBalance(encode_hex(account)) == 0
    previousA0 = chain.web3.eth.getBalance(encode_hex(ethereum.tester.a0))
    assert previousA0 > utils.denoms.ether

    tx = Transaction(
        nonce=chain.web3.eth.getTransactionCount(ethereum.tester.a0),
        gasprice=chain.web3.eth.gasPrice,
        startgas=100000,
        to=encode_hex(account),
        value=utils.denoms.ether,
        data=b'',
    )

    tx.sign(ethereum.tester.k0)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = chain.web3.toHex(raw_tx)
    chain.web3.eth.sendRawTransaction(raw_tx_hex)

    assert gnt.call().balanceOf(faucet.address) == 1000 * utils.denoms.ether

    assert chain.web3.eth.getBalance(encode_hex(account)) == utils.denoms.ether

    assert gnt.call().decimals() == 18
    assert gnt.call().balanceOf(encode_hex(account)) == 0
    tx = chain.wait.for_receipt(
        faucet.transact({'from': encode_hex(account)}).create())
    assert gnt.call().balanceOf(encode_hex(account)) == 1000 * utils.denoms.ether
    assert gnt.call().balanceOf(faucet.address) == 0
示例#54
0
    def sign(self, key, network_id=None):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if network_id is None:
            rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))
        else:
            assert 1 <= network_id < 2**63 - 18
            rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
                                 :-3] + [network_id, b'', b''])
            rawhash = utils.sha3(rlpdata)

        key = normalize_key(key)

        self.v, self.r, self.s = ecsign(rawhash, key)
        if network_id is not None:
            self.v += 8 + network_id * 2

        self._sender = utils.privtoaddr(key)
        return self
def test_eth_sendRawTransaction(web3, wait_for_transaction, extra_accounts):
    private_key = mk_random_privkey()
    address = encode_address(privtoaddr(private_key))

    funding_txn_hash = web3.eth.sendTransaction({
        "from": web3.eth.coinbase,
        "to": address,
        "value": 10000000000000000,
    })
    wait_for_transaction(web3, funding_txn_hash)

    if isinstance(web3.currentProvider, TestRPCProvider):
        # ethereum-tester-client doesn't quite implement the
        # `sendRawTransaction` correctly because of how the underlying tester
        # evm works.  It needs to know about the address for this to work.
        web3.personal.importRawKey(private_key, "password")
        web3.personal.unlockAccount(address, "password")

    initial_balance = web3.eth.getBalance(extra_accounts[1])

    tx = Transaction(
        web3.eth.getTransactionCount(address),
        web3.eth.gasPrice,
        100000,
        extra_accounts[1],
        1234,
        '',
    )
    tx.sign(private_key)

    raw_tx = rlp.encode(tx)
    raw_tx_hex = encode_data(raw_tx)

    txn_hash = web3.eth.sendRawTransaction(raw_tx_hex)
    wait_for_transaction(web3, txn_hash)
    txn_receipt = web3.eth.getTransactionReceipt(txn_hash)

    after_balance = web3.eth.getBalance(extra_accounts[1])

    assert after_balance - initial_balance == 1234
def call_const_function( priv_key, value, contract_hash, contract_abi, function_name, args ):
    src_address = b2h( utils.privtoaddr(priv_key) )    
    translator = ContractTranslator(contract_abi)
    call = translator.encode_function_call(function_name, args)  
    nonce = get_num_transactions( src_address )
    gas_price = get_gas_price_in_wei()
    
    start_gas = eval_startgas( src_address, contract_hash, value, b2h(call), gas_price )    
    nonce = int( nonce, 16 )
    gas_price = int( gas_price, 16 )
    start_gas = int( start_gas, 16 ) + 100000
    
    params = { "from" : "0x" + src_address,
               "to"   : "0x" + contract_hash,
               "gas"  : "0x" + str(start_gas),
               "gasPrice" : "0x" + str(gas_price),
               "value" : str(value),
               "data" : "0x" + b2h(call) }
    
    return_value = json_call( "eth_call", [params])
    return_value = h2b(return_value[2:]) # remove 0x
    return translator.decode(function_name, return_value)
示例#57
0
def test_decode_cancel_transfer():
    encoded_data = "080000000000000000000001000000000000001f0bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd82311074760d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df510000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001d5601c4475f2f6aa73d6a70a56f9c756f24d211a914cc7aff3fb80d2d8741c868f4966fe93b467d28f15befd438b7aa0e7b8fbf5f00ce1abe0cc4a0ddf9bcc7c45c9863b784f474dee3c0682a5aa4c982712b98fcd60f5e5d94038008a97e251300"

    data = encoded_data.decode("hex")
    s = tester.state()
    c = s.abi_contract(decode_code, language="solidity")

    assert data[0] == "\x08"  # make sure data has right cmdid
    assert len(data) == 253
    o1 = c.decodeCancelTransfer1(data)
    o2 = c.decodeCancelTransfer2(data)
    nonce = o1[0]
    assert nonce == 1
    expiration = o1[1]
    assert expiration == int("000000000000001f", 16)
    asset = o1[2]
    assert len(asset) == 40
    assert asset == sha3("asset")[:20].encode("hex")
    recipient = o1[3]
    assert len(recipient) == 40
    assert recipient == privtoaddr("y" * 32).encode("hex")
    locksroot = o2[0]
    assert locksroot == "60d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df51".decode("hex")
    balance = o2[1]
    assert balance == 1
    amount = o2[2]
    assert amount == 29  # int('000000000000000000000000000000000000000000000000000000000000001d', 16)
    hashlock = o2[3]
    assert hashlock == sha3("x" * 32)
    signature = "f4966fe93b467d28f15befd438b7aa0e7b8fbf5f00ce1abe0cc4a0ddf9bcc7c45c9863b784f474dee3c0682a5aa4c982712b98fcd60f5e5d94038008a97e251300".decode(
        "hex"
    )
    r = o2[4]
    s = o2[5]
    v = o2[6]
    assert r == signature[:32]
    assert s == signature[32:64]
    assert v == int(signature[64].encode("hex"))
示例#58
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if key in (0, '', b'\x00' * 32, '0' * 64):
            raise InvalidTransaction("Zero privkey cannot sign")
        rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))

        if len(key) == 64:
            # we need a binary key
            key = encode_privkey(key, 'bin')

        pk = PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
        self.v = utils.safe_ord(signature[64]) + 27
        self.r = big_endian_to_int(signature[0:32])
        self.s = big_endian_to_int(signature[32:64])

        self.sender = utils.privtoaddr(key)
        return self
示例#59
0
    v2s = rlp.encode(v2)
    v2d = rlp.decode(v2s, Vote)
    assert isinstance(v2d, VoteBlock)
    assert v2d.blockhash == bh
    assert v2d == v2

    assert v != v2
    assert vd != v2d

    assert len(set((v, vd))) == 1
    assert len(set((v2, v2d))) == 1
    assert len(set((v, vd, v2, v2d))) == 2


privkeys = [chr(i) * 32 for i in range(1, 11)]
validators = [utils.privtoaddr(p) for p in privkeys]


def test_LockSet():
    ls = LockSet(num_eligible_votes=len(privkeys))
    assert not ls
    assert len(ls) == 0

    bh = "0" * 32
    r, h = 2, 3
    v1 = VoteBlock(h, r, bh)

    # add not signed
    with pytest.raises(InvalidVoteError):
        ls.add(v1)
    assert not ls
示例#60
0
deposit_sizes = [128] * 15 + [256] * 5

print 'Creating genesis state'
s = mk_basic_state({}, None, env=Env(config=casper_config))
s.gas_limit = 10**9
s.prev_headers[0].timestamp = 2
s.timestamp = 2
s.prev_headers[0].difficulty = 1
s.block_difficulty = 1
s.set_code(casper_config['CASPER_ADDR'], get_casper_code())
s.set_code(casper_config['RLP_DECODER_ADDR'], get_rlp_decoder_code())
s.set_code(casper_config['HASH_WITHOUT_BLOOM_ADDR'], get_hash_without_ed_code())
ct = get_casper_ct()
# Add all validators
for k, r, ds in zip(keys, randaos, deposit_sizes):
    a = privtoaddr(k)
    # Leave 1 eth to pay txfees
    s.set_balance(a, (ds + 1) * 10**18)
    t = Transaction(0, 0, 10**8, casper_config['CASPER_ADDR'], ds * 10**18, ct.encode('deposit', [generate_validation_code(a), r.get(9999)])).sign(k)
    success, gas, logs = apply_transaction(s, t)
s.commit()
g = s.to_snapshot()
print 'Genesis state created'

validators = [Validator(g, k, n, Env(config=casper_config), time_offset=4) for k in keys]
n.agents = validators
n.generate_peers()

for i in range(100000):
    # print 'ticking'
    n.tick()