Ejemplo n.º 1
0
def _generateAddressBInternal(addressA,
                              addressC,
                              sendAmount,
                              dappData,
                              gasPrice,
                              gasLimit,
                              nonce=0,
                              V=27):
    '''
    Main function

    Generates the Reveal Transaction, commit and generates addressB

    :param addressA: Sender's Address
    :param addressC: Smart Contracts Address
    :param sendAmount: Send Amount (in Wei)
    :param data: Data for smart contract C
    :param gasPrice: Gas Price
    :param gasLimit: Gas Limit
    :param nonce: default 0
    :param V: default 27 --> no replay protection.
    :return:

    tx obj, addressB, commit, randw

    tx object --> reveal transaction (addressB to addressC), includes commit in data
    addressB : Commit transaction receiver
    commit : commit message
    randw: w (witness) random number
    '''

    commit, randw, R, S = _generateRS(addressA, addressC, sendAmount, dappData,
                                      gasPrice, gasLimit)

    submarineData = unlockFunctionSelector + commit
    # assert(len(commit) == 36)
    tx = Transaction(nonce,
                     gasPrice,
                     gasLimit,
                     addressC,
                     sendAmount,
                     data=submarineData,
                     v=V,
                     r=R,
                     s=S)

    try:
        addressB = tx.to_dict().get("sender")
        log.info("Unlock TX Dict: {}".format(tx.to_dict()))
        return tx, addressB, commit, randw

    except (ValueError, InvalidTransaction) as e:
        if isinstance(e, ValueError) and "VRS" not in str(e):
            raise
        log.info("Address no good (%s), retrying" % e)
        return _generateAddressBInternal(addressA, addressC, sendAmount,
                                         dappData, gasPrice, gasLimit, nonce,
                                         V)
Ejemplo n.º 2
0
    def send_transaction(self,
                         sender: address,
                         to: address,
                         value: int = 0,
                         data: bytes = b'',
                         startgas: int = None,
                         nonce: int = None):
        """ Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
        """

        if not self.privkey and not sender:
            raise ValueError('Either privkey or sender needs to be supplied.')

        if self.privkey:
            privkey_address = privatekey_to_address(self.privkey)
            sender = sender or privkey_address

            if sender != privkey_address:
                raise ValueError('sender for a different privkey.')

            if nonce is None:
                nonce = self.nonce(sender)
        else:
            if nonce is None:
                nonce = 0

        startgas = self.check_startgas(startgas)

        tx = Transaction(nonce,
                         self.gasprice(),
                         startgas,
                         to=to,
                         value=value,
                         data=data)

        if self.privkey:
            tx.sign(self.privkey)
            result = self.call(
                'eth_sendRawTransaction',
                data_encoder(rlp.encode(tx)),
            )
            return result[2 if result.startswith('0x') else 0:]

        else:

            # rename the fields to match the eth_sendTransaction signature
            tx_dict = tx.to_dict()
            tx_dict.pop('hash')
            tx_dict['sender'] = sender
            tx_dict['gasPrice'] = tx_dict.pop('gasprice')
            tx_dict['gas'] = tx_dict.pop('startgas')

            res = self.eth_sendTransaction(**tx_dict)

        assert len(res) in (20, 32)
        return hexlify(res)
Ejemplo n.º 3
0
def signed_tx_example():
    from ethereum.transactions import Transaction
    from pyethapp.accounts import mk_privkey, privtoaddr
    secret_seed = 'wow'
    privkey = mk_privkey(secret_seed)
    sender = privtoaddr(privkey)
    # fetch nonce
    nonce = quantity_decoder(JSONRPCClient().call('eth_getTransactionCount',
                                                  address_encoder(sender),
                                                  'pending'))
    # create transaction
    tx = Transaction(nonce,
                     default_gasprice,
                     default_startgas,
                     to=z_address,
                     value=100,
                     data='')
    tx.sign(privkey)
    tx_dict = tx.to_dict()
    tx_dict.pop('hash')
    res = JSONRPCClient().eth_sendTransaction(**tx_dict)
    if len(res) == 20:
        print 'contract created @', res.encode('hex')
    else:
        assert len(res) == 32
        print 'tx hash', res.encode('hex')
Ejemplo n.º 4
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')
Ejemplo n.º 5
0
    def send_transaction(self,
                         sender,
                         to,
                         value=0,
                         data='',
                         startgas=0,
                         gasprice=10 * denoms.szabo,
                         nonce=None):
        """ Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
        """

        if not self.privkey and not sender:
            raise ValueError('Either privkey or sender needs to be supplied.')

        if self.privkey and not sender:
            sender = privtoaddr(self.privkey)

            if nonce is None:
                nonce = self.nonce(sender)
        elif self.privkey:
            if sender != privtoaddr(self.privkey):
                raise ValueError('sender for a different privkey.')

            if nonce is None:
                nonce = self.nonce(sender)
        else:
            if nonce is None:
                nonce = 0

        if not startgas:
            startgas = self.gaslimit() - 1

        tx = Transaction(nonce,
                         gasprice,
                         startgas,
                         to=to,
                         value=value,
                         data=data)

        if self.privkey:
            # add the fields v, r and s
            tx.sign(self.privkey)

        tx_dict = tx.to_dict()

        # rename the fields to match the eth_sendTransaction signature
        tx_dict.pop('hash')
        tx_dict['sender'] = sender
        tx_dict['gasPrice'] = tx_dict.pop('gasprice')
        tx_dict['gas'] = tx_dict.pop('startgas')

        res = self.eth_sendTransaction(**tx_dict)
        assert len(res) in (20, 32)
        return res.encode('hex')
Ejemplo n.º 6
0
    def send_transaction(
            self,
            sender: address,
            to: address,
            value: int = 0,
            data: bytes = b'',
            startgas: int = 0,
            gasprice: int = GAS_PRICE,
            nonce: Optional[int] = None):
        """ Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
        """

        if not self.privkey and not sender:
            raise ValueError('Either privkey or sender needs to be supplied.')

        if self.privkey:
            privkey_address = privatekey_to_address(self.privkey)
            sender = sender or privkey_address

            if sender != privkey_address:
                raise ValueError('sender for a different privkey.')

            if nonce is None:
                nonce = self.nonce(sender)
        else:
            if nonce is None:
                nonce = 0

        if not startgas:
            startgas = self.gaslimit() - 1

        tx = Transaction(nonce, gasprice, startgas, to=to, value=value, data=data)

        if self.privkey:
            tx.sign(self.privkey)
            result = self.call(
                'eth_sendRawTransaction',
                data_encoder(rlp.encode(tx)),
            )
            return result[2 if result.startswith('0x') else 0:]

        else:

            # rename the fields to match the eth_sendTransaction signature
            tx_dict = tx.to_dict()
            tx_dict.pop('hash')
            tx_dict['sender'] = sender
            tx_dict['gasPrice'] = tx_dict.pop('gasprice')
            tx_dict['gas'] = tx_dict.pop('startgas')

            res = self.eth_sendTransaction(**tx_dict)

        assert len(res) in (20, 32)
        return hexlify(res)
Ejemplo n.º 7
0
 def txsign(self, tx_in, key, from_addr, chain_id=None):
     tx = Transaction(**tx_in)
     if chain_id is None:
         chain_id = int(g.rpch.parity_chainId(), 16)
     tx.sign(key, chain_id)
     hex_tx = rlp.encode(tx).encode('hex')
     coin_txid = CoinTxID(tx.hash.encode('hex'))
     if tx.sender.encode('hex') != from_addr:
         m = "Sender address '{}' does not match address of key '{}'!"
         die(3, m.format(from_addr, tx.sender.encode('hex')))
     if g.debug:
         msg('{}'.format('\n  '.join(parse_abi(data))))
         pmsg(tx.to_dict())
     return hex_tx, coin_txid
Ejemplo n.º 8
0
    def sendTransaction(self, data):
        """
        extend spec to support v,r,s signed transactions
        """
        if not isinstance(data, dict):
            raise BadRequestError('Transaction must be an object')

        def get_data_default(key, decoder, default=None):
            if key in data:
                return decoder(data[key])
            return default

        to = get_data_default('to', address_decoder, b'')
        startgas = get_data_default('gas', quantity_decoder, default_startgas)
        gasprice = get_data_default('gasPrice', quantity_decoder,
                                    default_gasprice)
        value = get_data_default('value', quantity_decoder, 0)
        data_ = get_data_default('data', data_decoder, b'')
        v = signed = get_data_default('v', quantity_decoder, 0)
        r = get_data_default('r', quantity_decoder, 0)
        s = get_data_default('s', quantity_decoder, 0)
        nonce = get_data_default('nonce', quantity_decoder, None)
        sender = get_data_default('from', address_decoder,
                                  self.app.services.accounts.coinbase)

        # create transaction
        if signed:
            assert nonce is not None, 'signed but no nonce provided'
            assert v and r and s
        else:
            nonce = self.app.services.chain.chain.head_candidate.get_nonce(
                sender)

        tx = Transaction(nonce, gasprice, startgas, to, value, data_, v, r, s)
        if not signed:
            assert sender in self.app.services.accounts, 'no account for sender'
            self.app.services.accounts.sign_tx(sender, tx)
        self.app.services.chain.add_transaction(tx, origin=None)

        log.debug('decoded tx', tx=tx.to_dict())

        if to == b'':  # create
            return address_encoder(
                processblock.mk_contract_address(tx.sender, nonce))
        else:
            return data_encoder(tx.hash)
Ejemplo n.º 9
0
    def sendTransaction(self, data):
        """
        extend spec to support v,r,s signed transactions
        """
        if not isinstance(data, dict):
            raise BadRequestError('Transaction must be an object')

        def get_data_default(key, decoder, default=None):
            if key in data:
                return decoder(data[key])
            return default

        to = get_data_default('to', address_decoder, b'')
        startgas = get_data_default('gas', quantity_decoder, default_startgas)
        gasprice = get_data_default('gasPrice', quantity_decoder, default_gasprice)
        value = get_data_default('value', quantity_decoder, 0)
        data_ = get_data_default('data', data_decoder, b'')
        v = signed = get_data_default('v', quantity_decoder, 0)
        r = get_data_default('r', quantity_decoder, 0)
        s = get_data_default('s', quantity_decoder, 0)
        nonce = get_data_default('nonce', quantity_decoder, None)
        sender = get_data_default('from', address_decoder, self.app.services.accounts.coinbase)

        # create transaction
        if signed:
            assert nonce is not None, 'signed but no nonce provided'
            assert v and r and s
        else:
            nonce = self.app.services.chain.chain.head_candidate.get_nonce(sender)

        tx = Transaction(nonce, gasprice, startgas, to, value, data_, v, r, s)
        if not signed:
            assert sender in self.app.services.accounts, 'no account for sender'
            self.app.services.accounts.sign_tx(sender, tx)
        self.app.services.chain.add_transaction(tx, origin=None)

        log.debug('decoded tx', tx=tx.to_dict())

        if to == b'':  # create
            return address_encoder(processblock.mk_contract_address(tx.sender, nonce))
        else:
            return data_encoder(tx.hash)
Ejemplo n.º 10
0
def signed_tx_example():
    from ethereum.transactions import Transaction
    from pyethapp.accounts import mk_privkey, privtoaddr

    secret_seed = "wow"
    privkey = mk_privkey(secret_seed)
    sender = privtoaddr(privkey)
    # fetch nonce
    nonce = quantity_decoder(JSONRPCClient().call("eth_getTransactionCount", address_encoder(sender), "pending"))
    # create transaction
    tx = Transaction(nonce, default_gasprice, default_startgas, to=z_address, value=100, data="")
    tx.sign(privkey)
    tx_dict = tx.to_dict()
    tx_dict.pop("hash")
    res = JSONRPCClient().eth_sendTransaction(**tx_dict)
    if len(res) == 20:
        print "contract created @", res.encode("hex")
    else:
        assert len(res) == 32
        print "tx hash", res.encode("hex")
Ejemplo n.º 11
0
def signed_tx_example(to=z_address, value=100):
    from ethereum.transactions import Transaction
    from pyethapp.accounts import mk_privkey, privtoaddr
    secret_seed = 'wow'
    privkey = mk_privkey(secret_seed)
    sender = privtoaddr(privkey)
    # fetch nonce
    nonce = quantity_decoder(
        JSONRPCClient().call('eth_getTransactionCount', address_encoder(sender), 'pending'))
    # create transaction
    tx = Transaction(nonce, default_gasprice, default_startgas, to=z_address, value=value, data='')
    tx.sign(privkey)
    tx_dict = tx.to_dict()
    tx_dict.pop('hash')
    res = JSONRPCClient().eth_sendTransaction(**tx_dict)
    if len(res) == 20:
        print 'contract created @', res.encode('hex')
    else:
        assert len(res) == 32
        print 'tx hash', res.encode('hex')
Ejemplo n.º 12
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')
Ejemplo n.º 13
0
def create_transaction(nonce, gasprice, gaslimit, to, value, data):
    tx = Transaction(nonce, gasprice, gaslimit, to, value, data)
    logging.debug("Created transaction: {0}".format(tx.to_dict()))
    return tx