github.com/gzuhlwang/notes-on-go-ethereum@v0.0.0-20190711012035-9f9c66e21d92/core/tx_noncer.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"github.com/ethereum/go-ethereum/common"
    21  	"github.com/ethereum/go-ethereum/core/state"
    22  )
    23  
    24  // txNoncer is a tiny virtual state database to manage the executable nonces of
    25  // accounts in the pool, falling back to reading from a real state database if
    26  // an account is unknown.
    27  type txNoncer struct {
    28  	fallback *state.StateDB
    29  	nonces   map[common.Address]uint64
    30  }
    31  
    32  // newTxNoncer creates a new virtual state database to track the pool nonces.
    33  func newTxNoncer(statedb *state.StateDB) *txNoncer {
    34  	return &txNoncer{
    35  		fallback: statedb.Copy(),
    36  		nonces:   make(map[common.Address]uint64),
    37  	}
    38  }
    39  
    40  // get returns the current nonce of an account, falling back to a real state
    41  // database if the account is unknown.
    42  func (txn *txNoncer) get(addr common.Address) uint64 {
    43  	if _, ok := txn.nonces[addr]; !ok {
    44  		txn.nonces[addr] = txn.fallback.GetNonce(addr)
    45  	}
    46  	return txn.nonces[addr]
    47  }
    48  
    49  // set inserts a new virtual nonce into the virtual state database to be returned
    50  // whenever the pool requests it instead of reaching into the real state database.
    51  func (txn *txNoncer) set(addr common.Address, nonce uint64) {
    52  	txn.nonces[addr] = nonce
    53  }