本文整理匯總了Python中ethereum.transactions.Transaction方法的典型用法代碼示例。如果您正苦於以下問題:Python transactions.Transaction方法的具體用法?Python transactions.Transaction怎麽用?Python transactions.Transaction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ethereum.transactions
的用法示例。
在下文中一共展示了transactions.Transaction方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_raw_transaction
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def get_raw_transaction(transaction: Transaction) -> str:
'''
Get raw_transaction by encoding Transaction object
Args:
transaction (`ethereum.transactions.Transaction`): Ethereum transaction object
Returns:
str: raw transaction hex string
Example:
>>> from clove.network import EthereumTestnet
>>> network = EthereumTestnet()
>>> transaction = network.deserialize_raw_transaction('0xf8f28201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a9092000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000808080') # noqa: E501
>>> network.get_raw_transaction(transaction)
'0xf8f28201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a9092000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000808080' # noqa: E501
'''
return Web3.toHex(rlp.encode(transaction))
示例2: publish
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def publish(self, transaction: Union[str, Transaction]) -> Optional[str]:
'''
Method to publish transaction
Args:
transaction (str, `ethereum.transactions.Transaction`): signed transaction
Returns:
str, None: transaction hash or None if something goes wrong
Example:
>>> from clove.network import EthereumTestnet
>>> network = EthereumTestnet()
>>> signed_transaction = '0xf901318201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a90920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001ca0d1c5b984ef2629eeb7c96f48a645566b2caf4130b0f3d7060ad5225946eee9e99f9928c5dfe868b45efbb9f8ae7d64d6162591c78961439c49e836947842e178' # noqa: E501
>>> network.publish(signed_transaction)
'0x4fd41289b816f6122e59a0759bd10441ead75d550562f4b3aad2fddc56eb3274'
'''
raw_transaction = transaction if isinstance(transaction, str) else self.get_raw_transaction(transaction)
try:
published_transaction = self.web3.eth.sendRawTransaction(raw_transaction).hex()
logger.debug(f'Transaction {published_transaction} published successful')
return published_transaction
except ValueError:
logger.warning(f'Unable to publish transaction {raw_transaction}')
return
示例3: _check_transaction
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def _check_transaction(self, transaction, unsigned):
"""
Checks a single (external) transaction against its expected unsigned (local) counterpart
"""
decoded = rlp.decode(self.web3.toAscii(transaction['signedRaw']), Transaction)
decoded_tx = dict(
nonce=self.web3.toHex(decoded.nonce),
gasPrice=self.web3.toHex(decoded.gasprice),
gas=self.web3.toHex(decoded.startgas),
to=self.web3.toHex(decoded.to),
value=self.web3.toHex(decoded.value),
data=self.web3.toHex(decoded.data)
)
unsigned['tx'].pop('from')
if unsigned['tx'] != decoded_tx:
logging.error("mismatch! signed tx: {}, local tx: {}".format(decoded_tx, unsigned['tx']))
raise AirdropException("transaction mismatch for {}".format(unsigned['tx']['nonce']))
示例4: make_transaction
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
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: tx_hash_decoder
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def tx_hash_decoder(data):
"""Decode a transaction hash."""
decoded = data_decoder(data)
if len(decoded) != 32:
raise BadRequestError('Transaction hashes must be 32 bytes long')
return decoded
示例6: _get_trace
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def _get_trace(self, txhash):
try: # index
test_blk, tx, i = self._get_block_before_tx(txhash)
except (KeyError, TypeError):
raise Exception('Unknown Transaction %s' % txhash)
# collect debug output FIXME set loglevel trace???
recorder = LogRecorder()
# apply tx (thread? we don't want logs from other invocations)
self.app.services.chain.add_transaction_lock.acquire()
processblock.apply_transaction(test_blk, tx) # FIXME deactivate tx context switch or lock
self.app.services.chain.add_transaction_lock.release()
return dict(tx=txhash, trace=recorder.pop_records())
示例7: signed_tx_example
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
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')
示例8: broadcast_transaction
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def broadcast_transaction(self, tx, origin=None):
assert isinstance(tx, Transaction)
if self.broadcast_filter.known(tx.hash):
log.debug('already broadcasted tx')
else:
log.debug('broadcasting tx', origin=origin)
bcast = self.app.services.peermanager.broadcast
bcast(eth_protocol.ETHProtocol, 'transactions', args=(tx,),
exclude_peers=[origin.peer] if origin else [])
# wire protocol receivers ###########
示例9: set_contract
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def set_contract(self):
self.contract = self.network.web3.eth.contract(address=self.contract_address, abi=self.abi)
initiate_func = self.contract.functions.initiate(
self.locktime_unix,
self.secret_hash,
self.recipient_address,
self.token_address,
bool(self.token),
self.token_value_base_units,
)
tx_dict = {
'nonce': self.network.web3.eth.getTransactionCount(self.sender_address),
'from': self.sender_address,
'value': self.value_base_units,
}
tx_dict = initiate_func.buildTransaction(tx_dict)
self.gas_limit = initiate_func.estimateGas({
key: value for key, value in tx_dict.items() if key not in ('to', 'data')
})
self.tx = Transaction(
nonce=tx_dict['nonce'],
gasprice=tx_dict['gasPrice'],
startgas=self.gas_limit,
to=tx_dict['to'],
value=tx_dict['value'],
data=Web3.toBytes(hexstr=tx_dict['data']),
)
示例10: sign
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def sign(transaction: Transaction, private_key: str) -> Transaction:
'''
Signing the transaction.
Args:
transaction (Transaction): Ethereum unsigned transaction object
private_key (str): private key
Returns:
Transaction: Ethereum signed transaction object
'''
transaction.sign(private_key)
logger.info('Transaction signed')
return transaction
示例11: deserialize_raw_transaction
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def deserialize_raw_transaction(raw_transaction: str) -> Transaction:
'''
Deserializing raw transaction and returning Transaction object
Args:
raw_transaction (str): raw transaction hex string
Returns:
`ethereum.transactions.Transaction`: Ethereum transaction object
Raises:
ImpossibleDeserialization: if the raw transaction was not deserializable
Example:
>>> from clove.network import EthereumTestnet
>>> network = EthereumTestnet()
>>> transaction = network.deserialize_raw_transaction('0xf8f28201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a9092000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000808080') # noqa: E501
<Transaction(821b)>
'''
try:
transaction = rlp.hex_decode(raw_transaction, Transaction)
logger.debug('Deserialization succeed')
except (ValueError, RLPException):
logger.warning(f'Deserialization with {raw_transaction} failed')
raise ImpossibleDeserialization()
transaction._cached_rlp = None
transaction.make_mutable()
return transaction
示例12: redeem
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def redeem(self, secret: str) -> EthereumTokenTransaction:
'''
Creates transaction that can redeem a contract.
Args:
secret (str): transaction secret that should match the contract secret hash (after hashing)
Returns:
EthereumTokenTransaction: unsigned transaction object with redeem transaction
Raises:
ValueError: if contract balance is 0
'''
if self.balance == 0:
raise ValueError("Balance of this contract is 0.")
contract = self.contract
redeem_func = contract.functions.redeem(secret)
tx_dict = {
'nonce': self.network.web3.eth.getTransactionCount(self.recipient_address),
'value': 0,
'gas': ETH_REDEEM_GAS_LIMIT,
}
tx_dict = redeem_func.buildTransaction(tx_dict)
transaction = EthereumTokenTransaction(network=self.network)
transaction.tx = Transaction(
nonce=tx_dict['nonce'],
gasprice=tx_dict['gasPrice'],
startgas=tx_dict['gas'],
to=tx_dict['to'],
value=tx_dict['value'],
data=Web3.toBytes(hexstr=tx_dict['data']),
)
transaction.value = self.value
transaction.token = self.token
transaction.recipient_address = self.recipient_address
return transaction
示例13: compute_state_test_unit
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def compute_state_test_unit(state, txdata, konfig):
state.env.config = konfig
s = state.snapshot()
try:
# Create the transaction
tx = transactions.Transaction(
nonce=parse_int_or_hex(txdata['nonce'] or b"0"),
gasprice=parse_int_or_hex(txdata['gasPrice'] or b"0"),
startgas=parse_int_or_hex(txdata['gasLimit'] or b"0"),
to=decode_hex(remove_0x_head(txdata['to'])),
value=parse_int_or_hex(txdata['value'] or b"0"),
data=decode_hex(remove_0x_head(txdata['data'])))
if 'secretKey' in txdata:
tx.sign(decode_hex(remove_0x_head(txdata['secretKey'])))
else:
tx.v = parse_int_or_hex(txdata['v'])
# Run it
prev = state.to_dict()
print("calling apply_transaction")
success, output = apply_transaction(state, tx)
print("Applied tx")
except InvalidTransaction as e:
print("Exception: %r" % e)
success, output = False, b''
state.commit()
post = state.to_dict()
output_decl = {
"hash": '0x' + encode_hex(state.trie.root_hash),
#"indexes": indices,
#"diff": mk_state_diff(prev, post)
}
stateRoot = encode_hex(state.trie.root_hash)
print("{{\"stateRoot\": \"{}\"}}".format(stateRoot))
state.revert(s)
return output_decl
示例14: getIntrinsicGas
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def getIntrinsicGas(test_tx):
tx = transactions.Transaction(
nonce=parse_int_or_hex(test_tx['nonce'] or b"0"),
gasprice=parse_int_or_hex(test_tx['gasPrice'] or b"0"),
startgas=parse_int_or_hex(test_tx['gasLimit'] or b"0"),
to=decode_hex(remove_0x_head(test_tx['to'])),
value=parse_int_or_hex(test_tx['value'] or b"0"),
data=decode_hex(remove_0x_head(test_tx['data'])))
return tx.intrinsic_gas_used
示例15: getTxSender
# 需要導入模塊: from ethereum import transactions [as 別名]
# 或者: from ethereum.transactions import Transaction [as 別名]
def getTxSender(test_tx):
tx = transactions.Transaction(
nonce=parse_int_or_hex(test_tx['nonce'] or b"0"),
gasprice=parse_int_or_hex(test_tx['gasPrice'] or b"0"),
startgas=parse_int_or_hex(test_tx['gasLimit'] or b"0"),
to=decode_hex(remove_0x_head(test_tx['to'])),
value=parse_int_or_hex(test_tx['value'] or b"0"),
data=decode_hex(remove_0x_head(test_tx['data'])))
if 'secretKey' in test_tx:
tx.sign(decode_hex(remove_0x_head(test_tx['secretKey'])))
return encode_hex(tx.sender)