Skip to content

Commit

Permalink
[project] Remove dead Lottery app code, optimize node/... on what sta…
Browse files Browse the repository at this point in the history
…ticcheck showed (harmony-one#2688)
  • Loading branch information
fxfactorial authored Apr 2, 2020
1 parent 780ecf4 commit 9fa85b5
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 407 deletions.
28 changes: 0 additions & 28 deletions node/contract.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package node

import (
"crypto/ecdsa"
"math/big"
"strings"
"sync/atomic"
Expand All @@ -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()
Expand Down Expand Up @@ -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 {
Expand All @@ -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")
}
}
10 changes: 0 additions & 10 deletions node/errors.go

This file was deleted.

110 changes: 32 additions & 78 deletions node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
}
}
}
Expand All @@ -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")
}
}
}
Expand Down
10 changes: 0 additions & 10 deletions node/node_error.go

This file was deleted.

10 changes: 5 additions & 5 deletions node/node_explorer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -101,7 +102,6 @@ func (node *Node) ExplorerMessageHandler(payload []byte) {
node.commitBlockForExplorer(blockObj)
}
}
return
}

// AddNewBlockForExplorer add new block for explorer.
Expand Down
31 changes: 0 additions & 31 deletions node/node_genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"crypto/ecdsa"
"errors"
"math/big"
"math/rand"
"strings"

"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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) {
Expand Down
47 changes: 22 additions & 25 deletions node/node_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()).
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
}
}
Expand Down
Loading

0 comments on commit 9fa85b5

Please sign in to comment.