github.com/annchain/OG@v0.0.9/account/account.go (about)

     1  package account
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/annchain/OG/common"
     6  	"github.com/annchain/OG/common/crypto"
     7  	"go.uber.org/atomic"
     8  	"sync"
     9  )
    10  
    11  type Account struct {
    12  	Id          int
    13  	PrivateKey  crypto.PrivateKey
    14  	PublicKey   crypto.PublicKey
    15  	Address     common.Address
    16  	InitBalance uint64
    17  
    18  	nonce       atomic.Uint64
    19  	nonceInited bool
    20  	mu          sync.RWMutex
    21  }
    22  
    23  func NewAccount(privateKeyHex string) *Account {
    24  	s := &Account{}
    25  	pv, err := crypto.PrivateKeyFromString(privateKeyHex)
    26  	if err != nil {
    27  		panic(err)
    28  	}
    29  	signer := crypto.NewSigner(pv.Type)
    30  	s.PrivateKey = pv
    31  	s.PublicKey = signer.PubKey(pv)
    32  	s.Address = signer.Address(s.PublicKey)
    33  	//logrus.WithField("add", s.Address.String()).WithField("priv", privateKeyHex).Trace("Sample Account")
    34  
    35  	return s
    36  }
    37  
    38  func (s *Account) ConsumeNonce() (uint64, error) {
    39  	s.mu.Lock()
    40  	defer s.mu.Unlock()
    41  
    42  	if !s.nonceInited {
    43  		return 0, fmt.Errorf("nonce is not initialized. Query first")
    44  	}
    45  	s.nonce.Inc()
    46  	return s.nonce.Load(), nil
    47  }
    48  
    49  func (s *Account) GetNonce() (uint64, error) {
    50  	s.mu.RLock()
    51  	defer s.mu.RUnlock()
    52  	if !s.nonceInited {
    53  		return 0, fmt.Errorf("nonce is not initialized. Query first")
    54  	}
    55  	return s.nonce.Load(), nil
    56  }
    57  
    58  func (s *Account) SetNonce(lastUsedNonce uint64) {
    59  	s.mu.Lock()
    60  	defer s.mu.Unlock()
    61  	s.nonce.Store(lastUsedNonce)
    62  	s.nonceInited = true
    63  }