[project] Remove dead Lottery app code, optimize node/... on what staticcheck showed (#2688)

pull/2693/head
Edgar Aroutiounian 5 years ago committed by GitHub
parent 780ecf4034
commit 9fa85b586b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 28
      node/contract.go
  2. 10
      node/errors.go
  3. 110
      node/node.go
  4. 10
      node/node_error.go
  5. 10
      node/node_explorer.go
  6. 31
      node/node_genesis.go
  7. 47
      node/node_handler.go
  8. 6
      node/node_newblock.go
  9. 139
      node/node_resharding.go
  10. 15
      node/node_syncing.go
  11. 26
      node/node_test.go
  12. 30
      node/rpc.go
  13. 52
      node/worker/worker.go

@ -1,7 +1,6 @@
package node
import (
"crypto/ecdsa"
"math/big"
"strings"
"sync/atomic"
@ -24,14 +23,6 @@ const (
FaucetContractFund = 80000000
)
// BuiltInSC is the type of built-in smart contract in blockchain
type builtInSC uint
// List of smart contract type built-in
const (
scFaucet builtInSC = iota
)
// GetNonceOfAddress returns nonce of an address.
func (node *Node) GetNonceOfAddress(address common.Address) uint64 {
state, err := node.Blockchain().State()
@ -87,11 +78,6 @@ func (node *Node) CallFaucetContract(address common.Address) common.Hash {
return node.callGetFreeTokenWithNonce(address, nonce-1)
}
func (node *Node) callGetFreeToken(address common.Address) common.Hash {
nonce := atomic.AddUint64(&node.ContractDeployerCurrentNonce, 1)
return node.callGetFreeTokenWithNonce(address, nonce-1)
}
func (node *Node) callGetFreeTokenWithNonce(address common.Address, nonce uint64) common.Hash {
abi, err := abi.JSON(strings.NewReader(contracts.FaucetABI))
if err != nil {
@ -113,17 +99,3 @@ func (node *Node) callGetFreeTokenWithNonce(address common.Address, nonce uint64
node.addPendingTransactions(types.Transactions{tx})
return tx.Hash()
}
// AddContractKeyAndAddress is used to add smart contract related information when node restart and resume with previous state
// It supports three kinds of on-chain smart contracts for now.
func (node *Node) AddContractKeyAndAddress(t builtInSC) {
switch t {
case scFaucet:
// faucet contract
contractDeployerKey, _ := ecdsa.GenerateKey(crypto.S256(), strings.NewReader("Test contract key string stream that is fixed so that generated test key are deterministic every time"))
node.ContractDeployerKey = contractDeployerKey
node.ContractAddresses = append(node.ContractAddresses, crypto.CreateAddress(crypto.PubkeyToAddress(contractDeployerKey.PublicKey), uint64(0)))
default:
utils.Logger().Error().Interface("unknown SC", t).Msg("AddContractKeyAndAddress")
}
}

@ -1,10 +0,0 @@
package node
import "errors"
var (
// ErrLotteryAppFailed is the error when a transaction failed to process lottery app.
ErrLotteryAppFailed = errors.New("Failed to process lottery app transaction")
// ErrPuzzleInsufficientFund is the error when a user does not have sufficient fund to enter.
ErrPuzzleInsufficientFund = errors.New("You do not have sufficient fund to play")
)

@ -12,7 +12,6 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/accounts"
"github.com/harmony-one/harmony/api/client"
clientService "github.com/harmony-one/harmony/api/client/service"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
proto_node "github.com/harmony-one/harmony/api/proto/node"
"github.com/harmony-one/harmony/api/service"
@ -135,17 +134,14 @@ type Node struct {
CxPool *core.CxPool // pool for missing cross shard receipts resend
Worker *worker.Worker
BeaconWorker *worker.Worker // worker for beacon chain
// Client server (for wallet requests)
clientServer *clientService.Server
Worker, BeaconWorker *worker.Worker
downloaderServer *downloader.Server
// Syncing component.
syncID [SyncIDLength]byte // a unique ID for the node during the state syncing process with peers
downloaderServer *downloader.Server
stateSync *syncing.StateSync
beaconSync *syncing.StateSync
syncID [SyncIDLength]byte // a unique ID for the node during the state syncing process with peers
stateSync, beaconSync *syncing.StateSync
peerRegistrationRecord map[string]*syncConfig // record registration time (unixtime) of peers begin in syncing
SyncingPeerProvider SyncingPeerProvider
@ -157,31 +153,15 @@ type Node struct {
host p2p.Host
// Incoming messages to process.
clientRxQueue *msgq.Queue
shardRxQueue *msgq.Queue
globalRxQueue *msgq.Queue
clientRxQueue, shardRxQueue, globalRxQueue *msgq.Queue
// Service manager.
serviceManager *service.Manager
// Demo account.
DemoContractAddress common.Address
LotteryManagerPrivateKey *ecdsa.PrivateKey
// Puzzle account.
PuzzleContractAddress common.Address
PuzzleManagerPrivateKey *ecdsa.PrivateKey
// For test only; TODO ek – remove this
TestBankKeys []*ecdsa.PrivateKey
ContractDeployerKey *ecdsa.PrivateKey
ContractDeployerCurrentNonce uint64 // The nonce of the deployer contract at current block
ContractAddresses []common.Address
// For puzzle contracts
AddressNonce sync.Map
// Shard group Message Receiver
shardGroupReceiver p2p.GroupReceiver
@ -206,15 +186,10 @@ type Node struct {
// map of service type to its message channel.
serviceMessageChan map[service.Type]chan *msg_pb.Message
accountManager *accounts.Manager
isFirstTime bool // the node was started with a fresh database
accountManager *accounts.Manager
isFirstTime bool // the node was started with a fresh database
// How long in second the leader needs to wait to propose a new block.
BlockPeriod time.Duration
// last time consensus reached for metrics
lastConsensusTime int64
// Last 1024 staking transaction error, only in memory
errorSink struct {
sync.Mutex
@ -436,16 +411,6 @@ func (node *Node) StartServer() {
select {}
}
// Count the total number of transactions in the blockchain
// Currently used for stats reporting purpose
func (node *Node) countNumTransactionsInBlockchain() int {
count := 0
for block := node.Blockchain().CurrentBlock(); block != nil; block = node.Blockchain().GetBlockByHash(block.Header().ParentHash()) {
count += len(block.Transactions())
}
return count
}
// GetSyncID returns the syncID of this node
func (node *Node) GetSyncID() [SyncIDLength]byte {
return node.syncID
@ -561,14 +526,6 @@ func New(
if node.isFirstTime {
// Setup one time smart contracts
node.AddFaucetContractToPendingTransactions()
} else {
node.AddContractKeyAndAddress(scFaucet)
}
// Create test keys. Genesis will later need this.
var err error
node.TestBankKeys, err = CreateTestBankKeys(TestAccountNumber)
if err != nil {
utils.Logger().Error().Err(err).Msg("Error while creating test keys")
}
}
}
@ -588,33 +545,30 @@ func New(
// Broadcast double-signers reported by consensus
if node.Consensus != nil {
go func() {
for {
select {
case doubleSign := <-node.Consensus.SlashChan:
utils.Logger().Info().
RawJSON("double-sign-candidate", []byte(doubleSign.String())).
Msg("double sign notified by consensus leader")
// no point to broadcast the slash if we aren't even in the right epoch yet
if !node.Blockchain().Config().IsStaking(
node.Blockchain().CurrentHeader().Epoch(),
) {
return
}
if hooks := node.NodeConfig.WebHooks.Hooks; hooks != nil {
if s := hooks.Slashing; s != nil {
url := s.OnNoticeDoubleSign
go func() { webhooks.DoPost(url, &doubleSign) }()
}
for doubleSign := range node.Consensus.SlashChan {
utils.Logger().Info().
RawJSON("double-sign-candidate", []byte(doubleSign.String())).
Msg("double sign notified by consensus leader")
// no point to broadcast the slash if we aren't even in the right epoch yet
if !node.Blockchain().Config().IsStaking(
node.Blockchain().CurrentHeader().Epoch(),
) {
return
}
if hooks := node.NodeConfig.WebHooks.Hooks; hooks != nil {
if s := hooks.Slashing; s != nil {
url := s.OnNoticeDoubleSign
go func() { webhooks.DoPost(url, &doubleSign) }()
}
if node.NodeConfig.ShardID != shard.BeaconChainShardID {
go node.BroadcastSlash(&doubleSign)
} else {
records := slash.Records{doubleSign}
if err := node.Blockchain().AddPendingSlashingCandidates(
records,
); err != nil {
utils.Logger().Err(err).Msg("could not add new slash to ending slashes")
}
}
if node.NodeConfig.ShardID != shard.BeaconChainShardID {
go node.BroadcastSlash(&doubleSign)
} else {
records := slash.Records{doubleSign}
if err := node.Blockchain().AddPendingSlashingCandidates(
records,
); err != nil {
utils.Logger().Err(err).Msg("could not add new slash to ending slashes")
}
}
}

@ -1,10 +0,0 @@
package node
import (
"errors"
)
var (
// ErrCrosslinkVerificationFail ...
ErrCrosslinkVerificationFail = errors.New("Crosslink Verification Failed")
)

@ -83,10 +83,11 @@ func (node *Node) ExplorerMessageHandler(payload []byte) {
utils.Logger().Error().Err(err).Msg("[Explorer] Unable to parse Prepared msg")
return
}
block := recvMsg.Block
blockObj := &types.Block{}
err = rlp.DecodeBytes(block, blockObj)
block, blockObj := recvMsg.Block, &types.Block{}
if err := rlp.DecodeBytes(block, blockObj); err != nil {
utils.Logger().Error().Err(err).Msg("explorer could not rlp decode block")
return
}
// Add the block into FBFT log.
node.Consensus.FBFTLog.AddBlock(blockObj)
// Try to search for MessageType_COMMITTED message from pbft log.
@ -101,7 +102,6 @@ func (node *Node) ExplorerMessageHandler(payload []byte) {
node.commitBlockForExplorer(blockObj)
}
}
return
}
// AddNewBlockForExplorer add new block for explorer.

@ -4,7 +4,6 @@ import (
"crypto/ecdsa"
"errors"
"math/big"
"math/rand"
"strings"
"github.com/ethereum/go-ethereum/common"
@ -97,7 +96,6 @@ func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardSt
// All non-mainnet chains get test accounts
if netType != nodeconfig.Mainnet {
node.AddTestingAddresses(genesisAlloc, TestAccountNumber)
gasLimit = params.TestGenesisGasLimit
// Smart contract deployer account used to deploy initial smart contract
contractDeployerKey, _ := ecdsa.GenerateKey(
@ -129,35 +127,6 @@ func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardSt
gspec.MustCommit(db)
}
// CreateTestBankKeys deterministically generates testing addresses.
func CreateTestBankKeys(numAddresses int) (keys []*ecdsa.PrivateKey, err error) {
rand.Seed(0)
bytes := make([]byte, 1000000)
for i := range bytes {
bytes[i] = byte(rand.Intn(100))
}
reader := strings.NewReader(string(bytes))
for i := 0; i < numAddresses; i++ {
key, err := ecdsa.GenerateKey(crypto.S256(), reader)
if err != nil {
return nil, err
}
keys = append(keys, key)
}
return keys, nil
}
// AddTestingAddresses create the genesis block allocation that contains deterministically
// generated testing addresses with tokens.
func (node *Node) AddTestingAddresses(gAlloc core.GenesisAlloc, numAddress int) {
for _, testBankKey := range node.TestBankKeys {
testBankAddress := crypto.PubkeyToAddress(testBankKey.PublicKey)
testBankFunds := big.NewInt(InitFreeFund)
testBankFunds = testBankFunds.Mul(testBankFunds, big.NewInt(denominations.One))
gAlloc[testBankAddress] = core.GenesisAccount{Balance: testBankFunds}
}
}
// AddNodeAddressesToGenesisAlloc adds to the genesis block allocation the accounts used for network validators/nodes,
// including the account used by the nodes of the initial beacon chain and later new nodes.
func AddNodeAddressesToGenesisAlloc(genesisAlloc core.GenesisAlloc) {

@ -51,11 +51,13 @@ func (node *Node) receiveGroupMessage(
}
//utils.Logger().Info("[PUBSUB]", "received group msg", len(msg), "sender", sender)
// skip the first 5 bytes, 1 byte is p2p type, 4 bytes are message size
// TODO sanity check that message isn't too big, have access to core txn constants
if len(msg) < p2pMsgPrefixSize {
utils.Logger().Warn().Err(err).Int("msg size", len(msg)).
Msg("invalid p2p message size")
continue
}
// NOTE non-blocking dispatches the message as fast as possiblee
if err := rxQueue.AddMessage(msg[p2pMsgPrefixSize:], sender); err != nil {
utils.Logger().Warn().Err(err).
Str("sender", sender.Pretty()).
@ -447,7 +449,6 @@ func (node *Node) PostConsensusProcessing(
// Update last consensus time for metrics
// TODO: randomly selected a few validators to broadcast messages instead of only leader broadcast
// TODO: refactor the asynchronous calls to separate go routine.
node.lastConsensusTime = time.Now().Unix()
if node.Consensus.IsLeader() {
if node.NodeConfig.ShardID == shard.BeaconChainShardID {
node.BroadcastNewBlock(newBlock)
@ -577,30 +578,26 @@ func (node *Node) bootstrapConsensus() {
tick := time.NewTicker(5 * time.Second)
defer tick.Stop()
lastPeerNum := node.numPeers
for {
select {
case <-tick.C:
numPeersNow := node.numPeers
// no peers, wait for another tick
if numPeersNow == 0 {
utils.Logger().Info().
Int("numPeersNow", numPeersNow).
Msg("No peers, continue")
continue
} else if numPeersNow > lastPeerNum {
utils.Logger().Info().
Int("previousNumPeers", lastPeerNum).
Int("numPeersNow", numPeersNow).
Int("targetNumPeers", node.Consensus.MinPeers).
Msg("New peers increased")
lastPeerNum = numPeersNow
}
if numPeersNow >= node.Consensus.MinPeers {
utils.Logger().Info().Msg("[bootstrap] StartConsensus")
node.startConsensus <- struct{}{}
return
}
for range tick.C {
numPeersNow := node.numPeers
// no peers, wait for another tick
if numPeersNow == 0 {
utils.Logger().Info().
Int("numPeersNow", numPeersNow).
Msg("No peers, continue")
continue
} else if numPeersNow > lastPeerNum {
utils.Logger().Info().
Int("previousNumPeers", lastPeerNum).
Int("numPeersNow", numPeersNow).
Int("targetNumPeers", node.Consensus.MinPeers).
Msg("New peers increased")
lastPeerNum = numPeersNow
}
if numPeersNow >= node.Consensus.MinPeers {
utils.Logger().Info().Msg("[bootstrap] StartConsensus")
node.startConsensus <- struct{}{}
return
}
}
}

@ -222,7 +222,7 @@ func (node *Node) proposeNewBlock() (*types.Block, error) {
}
// Prepare shard state
shardState := new(shard.State)
var shardState *shard.State
if shardState, err = node.Blockchain().SuperCommitteeForNextEpoch(
node.Beaconchain(), node.Worker.GetCurrentHeader(), false,
); err != nil {
@ -269,7 +269,7 @@ func (node *Node) proposeReceiptsProof() []*types.CXReceiptsProof {
return shardCMP || (shardEQ && blockCMP)
})
m := make(map[common.Hash]bool)
m := map[common.Hash]struct{}{}
Loop:
for _, cxp := range node.pendingCXReceipts {
@ -287,7 +287,7 @@ Loop:
if _, ok := m[hash]; ok {
continue
} else {
m[hash] = true
m[hash] = struct{}{}
}
for _, item := range cxp.Receipts {

@ -1,139 +0,0 @@
package node
import (
"bytes"
"math"
"os"
"os/exec"
"strconv"
"syscall"
"github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
/*
func (node *Node) transitionIntoNextEpoch(shardState types.State) {
logger = logger.New(
"blsPubKey", hex.EncodeToString(node.Consensus.PubKey.Serialize()),
"curShard", node.Blockchain().ShardID(),
"curLeader", node.Consensus.IsLeader())
for _, c := range shardState {
utils.Logger().Debug().
Uint32("shardID", c.ShardID).
Str("nodeList", c.Slots).
Msg("new shard information")
}
myShardID, isNextLeader := findRoleInShardState(
node.Consensus.PubKey, shardState)
logger = logger.New(
"nextShard", myShardID,
"nextLeader", isNextLeader)
if myShardID == math.MaxUint32 {
getLogger().Info("Somehow I got kicked out. Exiting")
os.Exit(8) // 8 represents it's a loop and the program restart itself
}
myShardState := shardState[myShardID]
// Update public keys
var publicKeys []*bls.PublicKey
for idx, nodeID := range myShardState.Slots {
key := &bls.PublicKey{}
err := key.Deserialize(nodeID.BLSPublicKey[:])
if err != nil {
getLogger().Error("Failed to deserialize BLS public key in shard state",
"idx", idx,
"error", err)
}
publicKeys = append(publicKeys, key)
}
node.Consensus.UpdatePublicKeys(publicKeys)
// node.DRand.UpdatePublicKeys(publicKeys)
if node.Blockchain().ShardID() == myShardID {
getLogger().Info("staying in the same shard")
} else {
getLogger().Info("moving to another shard")
if err := node.shardChains.Close(); err != nil {
getLogger().Error("cannot close shard chains", "error", err)
}
restartProcess(getRestartArguments(myShardID))
}
}
*/
func findRoleInShardState(
key *bls.PublicKey, state shard.State,
) (shardID uint32, isLeader bool) {
keyBytes := key.Serialize()
for idx, shard := range state.Shards {
for nodeIdx, nodeID := range shard.Slots {
if bytes.Compare(nodeID.BLSPublicKey[:], keyBytes) == 0 {
return uint32(idx), nodeIdx == 0
}
}
}
return math.MaxUint32, false
}
func restartProcess(args []string) {
execFile, err := getBinaryPath()
if err != nil {
utils.Logger().Error().
Err(err).
Str("file", execFile).
Msg("Failed to get program path when restarting program")
}
utils.Logger().Info().
Strs("args", args).
Strs("env", os.Environ()).
Msg("Restarting program")
err = syscall.Exec(execFile, args, os.Environ())
if err != nil {
utils.Logger().Error().
Err(err).
Msg("Failed to restart program after resharding")
}
panic("syscall.Exec() is not supposed to return")
}
func getRestartArguments(myShardID uint32) []string {
args := os.Args
hasShardID := false
shardIDFlag := "-shard_id"
// newNodeFlag := "-is_newnode"
for i, arg := range args {
if arg == shardIDFlag {
if i+1 < len(args) {
args[i+1] = strconv.Itoa(int(myShardID))
} else {
args = append(args, strconv.Itoa(int(myShardID)))
}
hasShardID = true
}
// TODO: enable this
//if arg == newNodeFlag {
// args[i] = "" // remove new node flag
//}
}
if !hasShardID {
args = append(args, shardIDFlag)
args = append(args, strconv.Itoa(int(myShardID)))
}
return args
}
// Gets the path of this currently running binary program.
func getBinaryPath() (argv0 string, err error) {
argv0, err = exec.LookPath(os.Args[0])
if nil != err {
return
}
if _, err = os.Stat(argv0); nil != err {
return
}
return
}

@ -162,14 +162,13 @@ func (p *LocalSyncingPeerProvider) SyncingPeers(shardID uint32) (peers []p2p.Pee
func (node *Node) DoBeaconSyncing() {
go func(node *Node) {
// TODO ek – infinite loop; add shutdown/cleanup logic
for {
select {
case beaconBlock := <-node.BeaconBlockChannel:
if node.beaconSync != nil {
err := node.beaconSync.UpdateBlockAndStatus(beaconBlock, node.Beaconchain(), node.BeaconWorker, true)
if err != nil {
node.beaconSync.AddLastMileBlock(beaconBlock)
}
for beaconBlock := range node.BeaconBlockChannel {
if node.beaconSync != nil {
err := node.beaconSync.UpdateBlockAndStatus(
beaconBlock, node.Beaconchain(), node.BeaconWorker, true,
)
if err != nil {
node.beaconSync.AddLastMileBlock(beaconBlock)
}
}
}

@ -2,13 +2,9 @@ package node
import (
"errors"
"fmt"
"os"
"sync"
"testing"
"time"
proto_discovery "github.com/harmony-one/harmony/api/proto/discovery"
"github.com/harmony-one/harmony/consensus"
"github.com/harmony-one/harmony/consensus/quorum"
bls2 "github.com/harmony-one/harmony/crypto/bls"
@ -281,25 +277,3 @@ func TestAddBeaconPeer(t *testing.T) {
}
}
}
func sendPingMessage(node *Node, leader p2p.Peer) {
pubKey1 := pki.GetBLSPrivateKeyFromInt(333).GetPublicKey()
p1 := p2p.Peer{
IP: "127.0.0.1",
Port: "9999",
ConsensusPubKey: pubKey1,
}
ping1 := proto_discovery.NewPingMessage(p1, true)
ping2 := proto_discovery.NewPingMessage(p1, false)
_ = ping1.ConstructPingMessage()
_ = ping2.ConstructPingMessage()
}
func exitServer() {
fmt.Println("wait 5 seconds to terminate the process ...")
time.Sleep(5 * time.Second)
os.Exit(0)
}

@ -26,11 +26,8 @@ const (
var (
// HTTP RPC
rpcAPIs []rpc.API
httpListener net.Listener
httpHandler *rpc.Server
wsListener net.Listener
wsHandler *rpc.Server
httpEndpoint = ""
wsEndpoint = ""
httpModules = []string{"hmy", "hmyv2", "net", "netv2", "explorer"}
@ -114,7 +111,6 @@ func (node *Node) StartRPC(nodePort string) error {
return err
}
rpcAPIs = apis
return nil
}
@ -155,35 +151,23 @@ func (node *Node) stopHTTP() {
}
// startWS initializes and starts the websocket RPC endpoint.
func (node *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error {
func (node *Node) startWS(
endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool,
) error {
// Short circuit if the WS endpoint isn't being exposed
if endpoint == "" {
return nil
}
listener, handler, err := rpc.StartWSEndpoint(endpoint, apis, modules, wsOrigins, exposeAll)
listener, _, err := rpc.StartWSEndpoint(endpoint, apis, modules, wsOrigins, exposeAll)
if err != nil {
return err
}
utils.Logger().Info().Str("url", fmt.Sprintf("ws://%s", listener.Addr())).Msg("WebSocket endpoint opened")
// All listeners booted successfully
wsListener = listener
wsHandler = handler
utils.Logger().Info().
Str("url", fmt.Sprintf("ws://%s", listener.Addr())).
Msg("WebSocket endpoint opened")
return nil
}
// stopWS terminates the websocket RPC endpoint.
func (node *Node) stopWS() {
if wsListener != nil {
wsListener.Close()
wsListener = nil
utils.Logger().Info().Str("url", fmt.Sprintf("ws://%s", wsEndpoint)).Msg("WebSocket endpoint closed")
}
if wsHandler != nil {
wsHandler.Stop()
wsHandler = nil
}
}
// APIs return the collection of RPC services the ethereum package offers.
// NOTE, some of these services probably need to be moved to somewhere else.
func (node *Node) APIs() []rpc.API {

@ -7,8 +7,6 @@ import (
"sort"
"time"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/harmony/block"
@ -18,12 +16,14 @@ import (
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/core/vm"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
"github.com/harmony-one/harmony/staking/slash"
staking "github.com/harmony-one/harmony/staking/types"
"github.com/pkg/errors"
)
// environment is the worker's current environment and holds all of the current state information.
@ -63,7 +63,6 @@ func (w *Worker) CommitTransactions(
}
txs := types.NewTransactionsByPriceAndNonce(w.current.signer, pendingNormal)
coalescedLogs := []*types.Log{}
// NORMAL
for {
// If we don't have enough gas for any further transactions then we're done
@ -95,7 +94,7 @@ func (w *Worker) CommitTransactions(
continue
}
logs, err := w.commitTransaction(tx, coinbase)
_, err := w.commitTransaction(tx, coinbase)
sender, _ := common2.AddressToBech32(from)
switch err {
@ -116,7 +115,6 @@ func (w *Worker) CommitTransactions(
case nil:
// Everything ok, collect the logs and shift in the next transaction from the same account
coalescedLogs = append(coalescedLogs, logs...)
txs.Shift()
default:
@ -148,16 +146,13 @@ func (w *Worker) CommitTransactions(
// Start executing the transaction
w.current.state.Prepare(tx.Hash(), common.Hash{}, len(w.current.txs))
// THESE CODE ARE DUPLICATED AS ABOVE>>
logs, err := w.commitStakingTransaction(tx, coinbase)
if err != nil {
if _, err := w.commitStakingTransaction(tx, coinbase); err != nil {
txID := tx.Hash().Hex()
utils.Logger().Error().Err(err).
Str("stakingTxID", txID).
Interface("stakingTx", tx).
Msg("Failed committing staking transaction")
} else {
coalescedLogs = append(coalescedLogs, logs...)
utils.Logger().Info().Str("stakingTxId", tx.Hash().Hex()).
Uint64("txGasLimit", tx.Gas()).
Msg("Successfully committed staking transaction")
@ -197,20 +192,37 @@ func (w *Worker) commitStakingTransaction(
return receipt.Logs, nil
}
func (w *Worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
snap := w.current.state.Snapshot()
var (
errNilReceipt = errors.New("nil receipt")
)
func (w *Worker) commitTransaction(
tx *types.Transaction, coinbase common.Address,
) ([]*types.Log, error) {
snap := w.current.state.Snapshot()
gasUsed := w.current.header.GasUsed()
receipt, cx, _, err := core.ApplyTransaction(w.config, w.chain, &coinbase, w.current.gasPool, w.current.state, w.current.header, tx, &gasUsed, vm.Config{})
receipt, cx, _, err := core.ApplyTransaction(
w.config,
w.chain,
&coinbase,
w.current.gasPool,
w.current.state,
w.current.header,
tx,
&gasUsed,
vm.Config{},
)
w.current.header.SetGasUsed(gasUsed)
if err != nil {
w.current.state.RevertToSnapshot(snap)
utils.Logger().Error().Err(err).Str("stakingTxId", tx.Hash().Hex()).Msg("Offchain ValidatorMap Read/Write Error")
return nil, err
utils.Logger().Error().
Err(err).Str("stakingTxId", tx.Hash().Hex()).
Msg("Offchain ValidatorMap Read/Write Error")
return nil, errNilReceipt
}
if receipt == nil {
utils.Logger().Warn().Interface("tx", tx).Interface("cx", cx).Msg("Receipt is Nil!")
return nil, fmt.Errorf("Receipt is Nil")
return nil, errNilReceipt
}
w.current.txs = append(w.current.txs, tx)
w.current.receipts = append(w.current.receipts, receipt)
@ -236,15 +248,13 @@ func (w *Worker) CommitReceipts(receiptsList []*types.CXReceiptsProof) error {
}
for _, cx := range receiptsList {
err := core.ApplyIncomingReceipt(w.config, w.current.state, w.current.header, cx)
if err != nil {
if err := core.ApplyIncomingReceipt(
w.config, w.current.state, w.current.header, cx,
); err != nil {
return ctxerror.New("Failed applying cross-shard receipts").WithCause(err)
}
}
for _, cx := range receiptsList {
w.current.incxs = append(w.current.incxs, cx)
}
w.current.incxs = append(w.current.incxs, receiptsList...)
return nil
}

Loading…
Cancel
Save