本文整理汇总了Python中ethereum.transactions.Transaction类的典型用法代码示例。如果您正苦于以下问题:Python Transaction类的具体用法?Python Transaction怎么用?Python Transaction使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transaction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_call
def test_call(block, sender, to, data='', gasprice=0, value=0):
state_root_before = block.state_root
assert block.has_parent()
# rebuild block state before finalization
parent = block.get_parent()
test_block = block.init_from_parent(parent, block.coinbase,
timestamp=block.timestamp)
for _tx in block.get_transactions():
success, output = processblock.apply_transaction(test_block, _tx)
assert success
# apply transaction
startgas = block.gas_limit - block.gas_used
gasprice = 0
nonce = test_block.get_nonce(sender)
tx = Transaction(nonce, gasprice, startgas, to, value, data)
tx.sender = sender
try:
success, output = processblock.apply_transaction(test_block, tx)
except processblock.InvalidTransaction as e:
success = False
assert block.state_root == state_root_before
if success:
return output
else:
log.debug('test_call failed', error=e)
return None
示例2: send_transaction
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')
示例3: sendout
def sendout(self):
log.debug("Sendout ping")
if not self.__awaiting:
return
payments = self.__awaiting # FIXME: Should this list be synchronized?
self.__awaiting = []
addr = keys.privtoaddr(self.__privkey) # TODO: Should be done once?
nonce = self.__client.get_transaction_count(addr.encode('hex'))
p, value = _encode_payments(payments)
data = bank_contract.encode('transfer', [p])
gas = 21000 + len(p) * 30000
tx = Transaction(nonce, self.GAS_PRICE, gas, to=self.BANK_ADDR,
value=value, data=data)
tx.sign(self.__privkey)
h = tx.hash
log.info("Batch payments: {}".format(h.encode('hex')))
# Firstly write transaction hash to database. We need the hash to be
# remembered before sending the transaction to the Ethereum node in
# case communication with the node is interrupted and it will be not
# known if the transaction has been sent or not.
with Payment._meta.database.transaction():
for payment in payments:
assert payment.status == PaymentStatus.awaiting
payment.status = PaymentStatus.sent
payment.details['tx'] = h.encode('hex')
payment.save()
tx_hash = self.__client.send(tx)
assert tx_hash[2:].decode('hex') == h # FIXME: Improve Client.
self.__inprogress[h] = payments
示例4: deliver
def deliver(self, enc_num, to):
# nonce = number of transactions already sent by that account
head = self.app.services.chain.chain.head
nonce = head.get_nonce(self.my_addr)
# Took from buterin example:
# https://blog.ethereum.org/2014/04/10/pyethereum-and-serpent-programming-guide/
gasprice = 10**12
# Took from buterin example:
# https://blog.ethereum.org/2014/04/10/pyethereum-and-serpent-programming-guide/
startgas = 10000
value = 0 # It's just a message, don't need to send any value (TODO: confirm that info)
# data is a json formatted message but has to be 'binary'
unix_now = int(round(time()))
payload = {}
payload['when'] = unix_now
payload['number'] = enc_num
payload['publish_on'] = unix_now + 86400 # in 24 hours
payload['published_at'] = 'http://www.example.com/foo'
data = json.dumps(payload)
deliver_tx = Transaction(nonce, gasprice, startgas, to, value, data)
signed_deliver_tx = deliver_tx.sign(self.privkey_hex)
success, output = apply_transaction(head, signed_deliver_tx)
示例5: call
def call(this, to, value=0, data='', sender=None,
startgas=25000, gasprice=10*denoms.szabo):
sender = address20(sender or this.coinbase)
to = address20(to)
block = this.head_candidate
state_root_before = block.state_root
assert block.has_parent()
# rebuild block state before finalization
parent = block.get_parent()
test_block = block.init_from_parent(parent, block.coinbase,
timestamp=block.timestamp)
for tx in block.get_transactions():
success, output = processblock.apply_transaction(test_block, tx)
assert success
# apply transaction
nonce = test_block.get_nonce(sender)
tx = Transaction(nonce, gasprice, startgas, to, value, data)
tx.sender = sender
try:
success, output = processblock.apply_transaction(test_block, tx)
except processblock.InvalidTransaction as e:
success = False
assert block.state_root == state_root_before
if success:
return output
else:
return False
示例6: sign_transaction
def sign_transaction(tx: Transaction, privkey: str, network_id: int):
# Implementing EIP 155.
tx.v = network_id
sig = sign(privkey, keccak256(rlp.encode(tx)), v=35 + 2 * network_id)
v, r, s = sig[-1], sig[0:32], sig[32:-1]
tx.v = v
tx.r = int.from_bytes(r, byteorder='big')
tx.s = int.from_bytes(s, byteorder='big')
示例7: call
def call(self, data, block_id=None):
block = self.json_rpc_server.get_block(block_id)
state_root_before = block.state_root
# rebuild block state before finalization
if block.has_parent():
parent = block.get_parent()
test_block = block.init_from_parent(parent, block.coinbase,
timestamp=block.timestamp)
for tx in block.get_transactions():
success, output = processblock.apply_transaction(test_block, tx)
assert success
else:
original = block.snapshot()
original['journal'] = deepcopy(original['journal']) # do not alter original journal
test_block = ethereum.blocks.genesis(block.db)
test_block.revert(original)
# validate transaction
if not isinstance(data, dict):
raise BadRequestError('Transaction must be an object')
to = address_decoder(data['to'])
try:
startgas = quantity_decoder(data['gas'])
except KeyError:
startgas = block.gas_limit - block.gas_used
try:
gasprice = quantity_decoder(data['gasPrice'])
except KeyError:
gasprice = 0
try:
value = quantity_decoder(data['value'])
except KeyError:
value = 0
try:
data_ = data_decoder(data['data'])
except KeyError:
data_ = b''
try:
sender = address_decoder(data['from'])
except KeyError:
sender = '\x00' * 20
# apply transaction
nonce = test_block.get_nonce(sender)
tx = Transaction(nonce, gasprice, startgas, to, value, data_)
tx.sender = sender
try:
success, output = processblock.apply_transaction(test_block, tx)
except processblock.InvalidTransaction as e:
success = False
assert block.state_root == state_root_before
if success:
return output
else:
return False
示例8: send_transaction
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)
示例9: test_eth_sendRawTransaction
def test_eth_sendRawTransaction(accounts, rpc_client):
tx = Transaction(0, tester.gas_price, tester.gas_limit, accounts[1], 1234, '')
tx.sign(tester.keys[0])
raw_tx = rlp.encode(tx)
raw_tx_hex = encode_data(raw_tx)
result = rpc_client('eth_sendRawTransaction', params=[raw_tx_hex])
assert len(result) == 66
示例10: direct
def direct(o, recipient, value):
nonce = o.eth.get_transaction_count(o.me.address.encode('hex'))
print "NONCE", nonce
print "VALUE", value
tx = Transaction(nonce, 1, 21000, to=recipient, value=value,
data='')
tx.sign(o.me.priv)
print o.eth.send(tx)
gevent.sleep(1) # FIXME: Wait for confirmed transaction receipt.
示例11: faucet_send
def faucet_send(o, to, value):
value = int(value * denoms.ether)
nonce = o.eth.get_transaction_count(Faucet.ADDR.encode('hex'))
to = normalize_address(to)
tx = Transaction(nonce, 1, 21000, to, value, '')
tx.sign(Faucet.PRIVKEY)
r = o.eth.send(tx)
print "Transaction sent:", r
gevent.sleep(10)
示例12: faucet
def faucet(o):
nonce = o.eth.get_transaction_count(Faucet.ADDR.encode('hex'))
print "NONCE", nonce
if nonce == 0: # Deploy Bank of Deposit contract
tx = Transaction(nonce, 1, 3141592, to='', value=0,
data=BankOfDeposit.INIT_HEX.decode('hex'))
tx.sign(Faucet.PRIVKEY)
o.eth.send(tx)
addr = tx.creates
assert addr == "cfdc7367e9ece2588afe4f530a9adaa69d5eaedb".decode('hex')
print "ADDR", addr.encode('hex')
示例13: gimme_money
def gimme_money(ethnode, addr, value):
nonce = ethnode.get_transaction_count(Faucet.ADDR.encode('hex'))
addr = normalize_address(addr)
tx = Transaction(nonce, 1, 21000, addr, value, '')
tx.sign(Faucet.PRIVKEY)
h = ethnode.send(tx)
log.info("Faucet --({} ETH)--> {} ({})".format(float(value) / 10**18,
addr.encode('hex'), h))
h = h[2:].decode('hex')
assert h == tx.hash
return h
示例14: test_eth_sendRawTransaction
def test_eth_sendRawTransaction(hex_accounts, client):
tx = Transaction(0, tester.gas_price, tester.gas_limit, tester.accounts[1], 1234, '')
tx.sign(tester.keys[0])
raw_tx = rlp.encode(tx)
raw_tx_hex = encode_data(raw_tx)
tx_hash = client.send_raw_transaction(raw_tx_hex)
assert tx_hash
tx_data = client.get_transaction_by_hash(tx_hash)
assert tx_data['hash'] == tx_hash
assert tx_data['from'] == hex_accounts[0]
assert tx_data['to'] == hex_accounts[1]
示例15: create_transaction
def create_transaction(
web3: Web3,
from_: str,
to: str,
data: bytes = b'',
nonce_offset: int = 0,
value: int = 0,
gas_price: Union[int, None] = None,
gas_limit: int = NETWORK_CFG.POT_GAS_LIMIT
) -> Transaction:
if gas_price is None:
gas_price = NETWORK_CFG.GAS_PRICE
nonce = web3.eth.getTransactionCount(from_, 'pending') + nonce_offset
tx = Transaction(nonce, gas_price, gas_limit, to, value, data)
tx.sender = decode_hex(from_)
return tx