See how Ethereum transactions are generated and broadcast over the network
Transactions are at the heart of the Ethereum blockchain (or any blockchain like it). When you interact with the Ethereum blockchain, you are executing a transaction and updating its status. Have you ever wondered what happens when you execute a transaction on Ethereum? Let’s answer this question with an example of a transaction. This article includes the following contents.
-
End-to-end traversal of Ethereum transactions, i.e. entering the Ethereum network from your browser/console and then returning to your browser/control
-
Know how transactions work when you use a plugin like Metamask or Myetherwallet instead of running your own nodes
-
If you’re paranoid and don’t trust any plugins and want to execute your own transactions, what can you do?
Readers of this article will need a basic understanding of Ethereum and its components, such as accounts, gas, and contracts. A detailed explanation of these concepts can be found in this article (see hyperlink to Accounts, Transactions, Gas, and Block Gas limits in Ethereum). If you are a developer unfamiliar with Ethereum, this article may be helpful. You can also learn how to build simple distributed applications from this article. This article is even more relevant if you have experienced executing a trade. For example, it could be a transaction that sends some Ether to another person or contract. For example, in the case of interacting with distributed applications, if you buy some tokens on the site, it’s a transaction. If you vote for a candidate, that’s a deal, too.
An end-to-end overview of Ethereum transactions
Let’s take the following contract call as an example and walk through the overall flow of how the function call/transaction is executed and permanently stored on the blockchain. Click here for the full contract. At a higher level, this is a voting contract where you can pre-set a number of candidates to compete in an election and anyone can vote for them. These votes will be recorded on the blockchain.
Voting.deployed().then(function(instance) {
instance.voteForCandidate('Nick', {gas: 140000, from: web3.eth.accounts[0]}).then(function(r) {
console.log("Voted successfully!")})})Copy the code
If you run an Ethereum client (Geth or Parity) locally on your computer, and your computer is connected to an Ethereum network (test network or main network), you have access to the contract address and ABI to execute the transaction.
If you’ve ever built a distributed application, you’re probably familiar with this code. This is a contract called Voting, which is already deployed on the blockchain. Taking this contract as an example, we execute a function called voteForCandidate that enters the name of the candidate, the gas ceiling for the transaction, and the account executing the transaction. As the name suggests, this function can be used to vote for a candidate, which is recorded on the blockchain. In the following sections, we’ll try to deconstruct the call to see what happens when you execute the javascript function.
1. Construct the original transaction object
As shown in the figure below, the voteForCandidate function call is first converted into the original transaction (rawTxn). The Web3js library is used to build the original transaction object.
txnCount = web3.eth.getTransactionCount(web3.eth.accounts[0])
var rawTxn = {
nonce: web3.toHex(txnCount),
gasPrice: web3.toHex(100000000000),
gasLimit: web3.toHex(140000),
to: '0x633296baebc20f33ac2e1c1b105d7cd1f6a0718b',
value: web3.toHex(0),
data: '0xc7ed014952616d6100000000000000000000000000000000000000000000000000000000'
};
Copy the code
Let’s try to understand all the fields in the original transaction object and how they are set up.
Nonce (Random Number) : Each Ethereum account has a field called nonce that records the total number of transactions that have been performed for that account. The value of the Nonce increases with each new transaction, which tells the network what order it needs to follow to execute the transaction. Nonce is also used for replay protection. GasPrice: The price per unit of gas you are willing to pay for the transaction. If you are executing a trade on the main network, there happens to be a website on ETH Gas Station where you can set the Gas price for your trade by following its advice so that the trade can be successfully executed within a certain period of time. Gas prices are currently measured in GWei and range from 0.1->100+ GWei. Gas prices and their impact are further described below.
GasLimit: The maximum amount of gas you are willing to pay for the transaction. This cap ensures that your account doesn’t run out of money in the event of execution problems, such as getting stuck in an infinite loop. Once the transaction is completed, any remaining gas will be returned to your account.
To: The address to which the function call is sent. 0 x633296baebc20f33ac2e1c1b105d7cd1f6a0718b is the address of our case voting agreement.
Value: The total amount of Ether you intend to send. When we execute the voteForCandidate function, we don’t send ether at all, so value is zero. If you want to execute a transaction, send ether to another person or contract, you will need to set value.
Data: Let’s look at how the data field is computed.
You first get the function signature from the ABI of voteForCandidate(Bytes32 candidate) and derive its hash value.
> web3.sha3('voteForCandidate(bytes32 candidate)')
'0xc7ed014922ff9493a686391b70ca0e8bb7e80f91c98a5cd3d285778ab2e245b3'
Copy the code
Take the first four bytes of the hash value, 0xCC9AB267.
Then put the parameters’ Nick ‘into 32 bytes, get 52616 d6100000000000000000000000000000000000000000000000000000000
Combine the two to get the data payload.
2. Sign the deal
If you remember, you used web3.eth. Accounts [0] to perform the transaction. The Ethereum network needs to know that you are indeed the owner of the account to ensure that others cannot execute the transaction on your behalf. The way to prove this to the network is to sign a transaction using the corresponding private key for the account. The signed transaction is shown below:
const privateKey = Buffer.from('e331b6d69882b4ab4ea581s88e0b6s4039a3de5967d88dfdcffdd2270c0fd109'.'hex')
const txn = new EthereumTx(rawTxn)
txn.sign(privateKey)
const serializedTxn = txn.serialize()
Copy the code
3. Transactions are verified locally
The signed transaction is submitted to your local Ethereum node. Your local node then validates the signed transaction to make sure it was actually signed by the account address.
4. Transactions are broadcast to the network
Signed transactions are broadcast by your GEth/Parity nodes to their peers, who broadcast the transaction to their peers, and so on. Once the transaction is broadcast to the network, your local node will also output the transaction ID, which you can use to track the status of your transaction. The transaction ID is the hash value of the signed transaction object.
transactionId = sha3(serializedTxn)
Copy the code
If you’re performing the transaction on a public Ethereum network, the best way to track the status of your transaction is through EtherScan.io. As shown above, did you notice that there are several nodes flagged as Etherscan nodes? Etherscan’s team ran a few nodes and connected a great front-end network application to Etherscan. If your deal is selected by their node, you can view your pending deal on their website.
Also keep in mind that not all nodes will accept your transaction. Some of these nodes may be set up to accept only transactions where gas prices exceed a certain minimum. If you set the gas price below the lower limit, the node will ignore your transaction.
5. The miner node accepts transactions
As shown in the figure, the Ethereum network has both miner and non-miner nodes. As you probably know, the miner’s job is to include your transaction in the block. Miners are the maintainers of the trade pool. Your trade is first added to the pool and then evaluated by miners.
You’ll notice from the figure above that miners store all transactions in pools sorted by gas prices. The higher the gas price, the more likely it is that the transaction will be added to the next block. This is a common setup for miner nodes (optimized for higher pay). However, miners can set up their nodes to sort transactions according to their preferences (for example, they mine only for low gas prices to help the network).
Can you see how our voteForCandidate deal sinks to the bottom of the mining pool? Once all the high gas price transactions have been mined and included in the block, miners will mine our transactions.
It is also important to note that a mining pool is limited in the number of trades it can accommodate. For example, a crowdfunding campaign is underway or a very popular distributed app (like Crypto Cat) comes along. People submitted deals with high gas prices in the hope that miners would pick their deals first. If deals with high gas prices fill up the pool, deals with low gas prices are abandoned. Our candidate Nick won’t be receiving any votes for a while. In this case, we might even have to re-broadcast our trade.
Another trick to get your trade up in the pool is to resubmit your trade, raise the gas price and keep the NONCE value unchanged. That way, when miners receive a New Deal, the New Deal with a higher gas price overrides the previous one. If the NONCE value is changed, the resubmitted transaction is considered a different transaction (and Nick ends up voting twice). You recommend a good article (editor’s note: see article at the end of the Chinese translation of the popular science | release blocked the etheric fang trading links), the author Jim McDonald, made a further explanation.
6. Miner node finds a valid block and broadcasts it to the network
The miners finally picked our deal and included it in the block along with the others. Miners can only select a certain number of transactions to add to the block, because Ethereum already has a single block gas cap. In other words, the total number of gas caps for all transactions cannot exceed the block gas cap. You can check the current gas ceiling at ethstats.net.
Once the miner chooses to include transactions in the block, those transactions are validated and included in a pending block, and proof of work begins. A miner node eventually finds a valid block (by solving the proof-of-work puzzle) and adds that block to the blockchain. Just as the original transaction broadcast by your local node is received by other nodes, the miner node will broadcast this valid block to other nodes.
7. The local node receives/synchronizes new blocks
Eventually, your local node will receive the new block and synchronize a local copy of the blockchain. Once the new block is received, the local node executes all transactions in the block.
If you use Truffle to execute your transaction, truffle will constantly test the blockchain for confirmation. Once it finds that the transaction is confirmed, it executes the code in the THEN () block and prints the console logging function (for each of our examples).
Use Metamask instead of local nodes
If you install the MetaMask browser plugin, you can manage your accounts in your browser. The key will only be stored on your browser, so you are the only one with access to your account and private key. When you execute a transaction on the browser, the plugin converts your function call into the original transaction and signs the transaction with your private key. Metamask runs its own nodes and uses them to broadcast your transactions (Metamask uses nodes run by Infura). This way, you don’t have to run your own Ethereum node.
3. Offline signature
What if you don’t like using plug-ins, or if you’re worried that your local GEth node might be corrupted (tampered with)? There is a safe solution to this problem.
If you’ve noticed, the first two steps don’t require an Internet connection at all. If you want to ensure that your transaction will never be tampered with, you can use a computer with no Internet connection to convert this function call into the original transaction and sign the transaction using your private key. You can then copy the signed transaction string and broadcast it to the network using a networked computer. You can use services like Etherscan and Infura to broadcast your signed transactions to the web.
Another security option is to use a hardware wallet such as Ledger or Trezor. The wallet stores your private key, and the key that signs the transaction is programmed into the hardware itself. The reason they need to be connected is simply to post your signed transactions.
Thanks to Jim McDonald for proofreading this article.
The original link: https://medium.com/blockchannel/life-cycle-of-an-ethereum-transaction-e5 c66bae0f6e author: Mahesh Murthy translation & editing: MinMin & Elisa articles: the etheric fang lovers (https://ethfans.org/ajian1984/articles/849)Copy the code