以太坊入门(一)账户和nonce的关系

什么是nonce?

在以太坊的交易数据中,大家都可以看到一个数字,nonce,从0开始,一直向上递增,这个代表什么意思呢?

以太坊所有的交易都是基于account的,不同于基于utxo的比特币,因此需要对每次交易都按顺序记录,nonce值就是这个顺序,主要用来防止重放攻击。

发起一笔交易,nonce就会加一。对于发起的解释:

1.外部账户每发送一笔交易;

2.合约账户每创建一个合约

而转入交易、合约调用其他合约等属于内部调用,因此nonce值不变。

如何使用nonce

发起转账或者创建合约的时候,通过web3从以太坊网络查询当前的nonce(ethGetTransactionCount)值,使用此值作为当前交易的nonce值,发送到以太坊网络即可。

nonce使用的几条规则

1. 当nonce太小(小于当前的nonce值),交易会被直接拒绝,Transactions with too low a nonce get immediately rejected;

2. 当nonce太大,大于当前nonce,交易会一直处于队列之中,Transactions with too high a nonce get placed in the transaction pool queue;

3.当发送一个比较大的nonce值,然后补齐开始nonce到那个值之间的nonce,那么交易依旧可以被执行,If transactions with nonces that fill the gap between the last valid nonce and the too high nonce are sent and the nonce sequence is complete, all the transactions in the sequence will get processed and mined.

4. 交易队列只保存最多64个从同一个账户发出的交易,The transaction pool queue will only hold a maximum of 64 transactions with the same From:address with nonces out of sequence. 也就是说,如果要批量转账,同一节点不要发出超过64笔交易。

5.当某节点queue中还有交易,但此时停止geth客户端,queue中的交易会被清除掉,When the geth instances are shut down and restarted, transactions in the transaction pool queue disappear.

6.当前nonce合适,但是账户余额不足时,会被以太坊拒绝;

7.如果发起一笔交易,但是因为gwei比较低或者网络比较忙的时候,该交易还没矿工挖出,可以通过使用相同的nonce和较高的gas费用,从而“覆盖”前一笔交易;