Merge branch 'master' of github.com:harmony-one/harmony into rj_fork

pull/951/head
Rongjian Lan 6 years ago
commit 9deadb1fb0
  1. 63
      api/service/clientsupport/service.go
  2. 3
      api/service/manager.go
  3. 2
      api/service/staking/service.go
  4. 2
      cmd/client/txgen/main.go
  5. 14
      cmd/client/wallet/main.go
  6. 8
      common/denominations/denominations.go
  7. 2
      consensus/consensus.go
  8. 4
      consensus/consensus_service.go
  9. 15
      consensus/consensus_v2.go
  10. 2
      consensus/view_change.go
  11. 32
      core/denominations/denominations.go
  12. 2
      core/genesis.go
  13. 4
      core/genesis_block_test.json
  14. 2
      core/genesis_util.go
  15. 2
      core/tx_pool_test.go
  16. 7
      hmy/api_backend.go
  17. 7
      hmy/backend.go
  18. 2
      internal/hmyapi/backend.go
  19. 2
      internal/hmyapi/blockchain.go
  20. 14
      internal/hmyapi/net.go
  21. 4
      internal/utils/contract/constants.go
  22. 2
      node/contract.go
  23. 18
      node/node.go
  24. 2
      node/node_genesis.go
  25. 7
      node/node_handler.go
  26. 76
      node/node_newblock.go
  27. 8
      node/rpc.go
  28. 10
      node/service_setup.go
  29. 2
      node/worker/worker_test.go

@ -0,0 +1,63 @@
package clientsupport
import (
"strconv"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rpc"
clientService "github.com/harmony-one/harmony/api/client/service"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/core/state"
"google.golang.org/grpc"
)
const (
// ClientServicePortDiff is the positive port diff for client service
ClientServicePortDiff = 5555
)
// Service is the client support service.
type Service struct {
server *clientService.Server
grpcServer *grpc.Server
ip string
port string
messageChan chan *msg_pb.Message
}
// New returns new client support service.
func New(stateReader func() (*state.DB, error),
callFaucetContract func(common.Address) common.Hash,
getDeployedStakingContract func() common.Address,
ip, nodePort string) *Service {
port, _ := strconv.Atoi(nodePort)
return &Service{
server: clientService.NewServer(stateReader, callFaucetContract, getDeployedStakingContract),
ip: ip,
port: strconv.Itoa(port + ClientServicePortDiff)}
}
// StartService starts client support service.
func (s *Service) StartService() {
s.grpcServer, _ = s.server.Start(s.ip, s.port)
}
// StopService stops client support service.
func (s *Service) StopService() {
s.grpcServer.Stop()
}
// SetMessageChan sets up message channel to service.
func (s *Service) SetMessageChan(messageChan chan *msg_pb.Message) {
s.messageChan = messageChan
}
// NotifyService notify service
func (s *Service) NotifyService(params map[string]interface{}) {
return
}
// APIs for the services.
func (s *Service) APIs() []rpc.API {
return nil
}

@ -24,6 +24,7 @@ type Type byte
// Constants for Type.
const (
SupportSyncing Type = iota
ClientSupport
SupportExplorer
Consensus
Randomness
@ -42,6 +43,8 @@ func (t Type) String() string {
return "SyncingSupport"
case SupportExplorer:
return "SupportExplorer"
case ClientSupport:
return "ClientSupport"
case Consensus:
return "Consensus"
case Randomness:

@ -19,9 +19,9 @@ import (
proto_common "github.com/harmony-one/harmony/api/proto"
"github.com/harmony-one/harmony/api/proto/message"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/contracts"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/core/types"
hmykey "github.com/harmony-one/harmony/internal/keystore"
"github.com/harmony-one/harmony/internal/utils"

@ -22,7 +22,7 @@ import (
"github.com/harmony-one/harmony/api/client"
proto_node "github.com/harmony-one/harmony/api/proto/node"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/crypto/bls"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"

@ -14,11 +14,11 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/api/client"
clientService "github.com/harmony-one/harmony/api/client/service"
proto_node "github.com/harmony-one/harmony/api/proto/node"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
@ -432,14 +432,14 @@ func processTransferCommand() {
}
balance := state.balance
balance = balance.Div(balance, big.NewInt(params.GWei))
if amount > float64(balance.Uint64())/params.GWei {
fmt.Printf("Balance is not enough for the transfer, current balance is %.6f\n", float64(balance.Uint64())/params.GWei)
balance = balance.Div(balance, big.NewInt(denominations.Nano))
if amount > float64(balance.Uint64())/denominations.Nano {
fmt.Printf("Balance is not enough for the transfer, current balance is %.6f\n", float64(balance.Uint64())/denominations.Nano)
return
}
amountBigInt := big.NewInt(int64(amount * params.GWei))
amountBigInt = amountBigInt.Mul(amountBigInt, big.NewInt(params.GWei))
amountBigInt := big.NewInt(int64(amount * denominations.Nano))
amountBigInt = amountBigInt.Mul(amountBigInt, big.NewInt(denominations.Nano))
gas, err := core.IntrinsicGas(inputData, false, true)
if err != nil {
fmt.Printf("cannot calculate required gas: %v\n", err)
@ -474,7 +474,7 @@ func processTransferCommand() {
}
func convertBalanceIntoReadableFormat(balance *big.Int) string {
balance = balance.Div(balance, big.NewInt(params.GWei))
balance = balance.Div(balance, big.NewInt(denominations.Nano))
strBalance := fmt.Sprintf("%d", balance.Uint64())
bytes := []byte(strBalance)

@ -0,0 +1,8 @@
package denominations
//ONE Units
const (
Atto = 1
Nano = 1e9
One = 1e18
)

@ -9,9 +9,9 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/log"
"github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/common/denominations"
consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
bls_cosi "github.com/harmony-one/harmony/crypto/bls"

@ -45,6 +45,10 @@ func (consensus *Consensus) GetNextRnd() ([32]byte, [32]byte, error) {
return [32]byte{}, [32]byte{}, errors.New("No available randomness")
}
vdfOutput := consensus.pendingRnds[0]
//pop the first vdfOutput from the list
consensus.pendingRnds = consensus.pendingRnds[1:]
rnd := [32]byte{}
blockHash := [32]byte{}
copy(rnd[:], vdfOutput[:32])

@ -520,8 +520,13 @@ func (consensus *Consensus) finalizeCommits() {
consensus.viewID++
consensus.blockNum++
if consensus.consensusTimeout[timeoutBootstrap].IsActive() {
consensus.consensusTimeout[timeoutBootstrap].Stop()
utils.GetLogger().Debug("start consensus timeout; stop bootstrap timeout only once", "viewID", consensus.viewID, "block", consensus.blockNum)
} else {
utils.GetLogger().Debug("start consensus timeout", "viewID", consensus.viewID, "block", consensus.blockNum)
}
consensus.consensusTimeout[timeoutConsensus].Start()
consensus.consensusTimeout[timeoutBootstrap].Stop()
consensus.OnConsensusDone(&blockObj)
utils.GetLogInstance().Debug("HOORAY!!!!!!! CONSENSUS REACHED!!!!!!!", "viewID", consensus.viewID, "numOfSignatures", len(consensus.commitSigs))
@ -600,8 +605,13 @@ func (consensus *Consensus) onCommitted(msg *msg_pb.Message) {
consensus.commitBitmap = mask
consensus.tryCatchup()
if consensus.consensusTimeout[timeoutBootstrap].IsActive() {
consensus.consensusTimeout[timeoutBootstrap].Stop()
utils.GetLogger().Debug("start consensus timeout; stop bootstrap timeout only once", "viewID", consensus.viewID, "block", consensus.blockNum)
} else {
utils.GetLogger().Debug("start consensus timeout", "viewID", consensus.viewID, "block", consensus.blockNum)
}
consensus.consensusTimeout[timeoutConsensus].Start()
consensus.consensusTimeout[timeoutBootstrap].Stop()
return
}
@ -704,6 +714,7 @@ func (consensus *Consensus) Start(blockChannel chan *types.Block, stopChan chan
defer close(stoppedChan)
ticker := time.NewTicker(3 * time.Second)
consensus.consensusTimeout[timeoutBootstrap].Start()
utils.GetLogger().Debug("start bootstrap timeout only once", "viewID", consensus.viewID, "block", consensus.blockNum)
for {
select {
case <-ticker.C:

@ -155,6 +155,7 @@ func (consensus *Consensus) startViewChange(viewID uint32) {
consensus.consensusTimeout[timeoutViewChange].SetDuration(duration)
consensus.consensusTimeout[timeoutViewChange].Start()
utils.GetLogger().Debug("start view change timeout", "viewID", consensus.viewID, "block", consensus.blockNum, "viewChangingID", consensus.mode.ViewID())
}
// new leader send new view message
@ -330,6 +331,7 @@ func (consensus *Consensus) onViewChange(msg *msg_pb.Message) {
consensus.ResetViewChangeState()
consensus.consensusTimeout[timeoutViewChange].Stop()
consensus.consensusTimeout[timeoutConsensus].Start()
utils.GetLogger().Debug("start consensus timeout and stop view change timeout", "viewID", consensus.viewID, "block", consensus.blockNum, "viewChangingID", consensus.mode.ViewID())
}
utils.GetLogInstance().Debug("onViewChange", "numSigs", len(consensus.viewIDSigs), "needed", consensus.Quorum())
}

@ -1,32 +0,0 @@
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package denominations
// These are the multipliers for ether denominations.
// Example: To get the wei value of an amount in 'gwei', use
//
// new(big.Int).Mul(value, big.NewInt(params.GWei))
// These are the multipliers for ether denominations.
// Example: To get the wei value of an amount in 'gwei', use
//
// new(big.Int).Mul(value, big.NewInt(params.GWei))
//
const (
Wei = 1
GWei = 1e9
One = 1e18
)

@ -299,7 +299,7 @@ func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
return block
}
// GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
// GenesisBlockForTesting creates and writes a block in which addr has the given Nano balance.
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
return g.MustCommit(db)

@ -1,8 +1,8 @@
{
"b7a2c103728b7305b5ae6e961c94ee99c9fe8e2b": {
"wei": "50000000000000000000000"
"nano": "50000000000000000000000"
},
"b498bb0f520005b6216a4425b75aa9adc52d622b": {
"wei": "4000000000000000000000"
"nano": "4000000000000000000000"
}
}

@ -54,7 +54,7 @@ func StringToBigInt(s string, base int) *big.Int {
func convertToGenesisItems(gc genesisConfig) []GenesisItem {
gi := []GenesisItem{}
for k, v := range gc {
gi = append(gi, GenesisItem{StringToBigInt(k, 16), StringToBigInt(v["wei"], 10)})
gi = append(gi, GenesisItem{StringToBigInt(k, 16), StringToBigInt(v["nano"], 10)})
}
sort.Slice(gi, func(i, j int) bool {
return gi[i].Addr.Cmp(gi[j].Addr) == -1

@ -31,7 +31,7 @@ import (
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
)

@ -18,7 +18,7 @@ import (
"github.com/harmony-one/harmony/core/types"
)
// APIBackend An implementation of Backend. Full client.
// APIBackend An implementation of internal/hmyapi/Backend. Full client.
type APIBackend struct {
hmy *Harmony
}
@ -201,3 +201,8 @@ func (b *APIBackend) GetBalance(address common.Address) (*hexutil.Big, error) {
balance, err := b.hmy.nodeAPI.GetBalanceOfAddress(address)
return (*hexutil.Big)(balance), err
}
// NetVersion returns net version
func (b *APIBackend) NetVersion() uint64 {
return b.hmy.NetVersion()
}

@ -30,6 +30,9 @@ type Harmony struct {
APIBackend *APIBackend
nodeAPI NodeAPI
// aka network version, which is used to identify which network we are using
networkID uint64
}
// NodeAPI is the list of functions from node used to call rpc apis.
@ -55,6 +58,7 @@ func New(nodeAPI NodeAPI, txPool *core.TxPool, eventMux *event.TypeMux) (*Harmon
chainDb: chainDb,
bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms),
nodeAPI: nodeAPI,
networkID: 1, // TODO(ricl): this should be from config
}
hmy.APIBackend = &APIBackend{hmy}
@ -67,3 +71,6 @@ func (s *Harmony) TxPool() *core.TxPool { return s.txPool }
// BlockChain ...
func (s *Harmony) BlockChain() *core.BlockChain { return s.blockchain }
// NetVersion returns the network version, i.e. network ID identifying which network we are using
func (s *Harmony) NetVersion() uint64 { return s.networkID }

@ -20,6 +20,8 @@ import (
// implementations:
// * hmy/api_backend.go
type Backend interface {
// NOTE(ricl): this is not in ETH Backend inteface. They put it directly in eth object.
NetVersion() uint64
// General Ethereum API
// Downloader() *downloader.Downloader
ProtocolVersion() int

@ -68,7 +68,7 @@ func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.A
return res[:], state.Error()
}
// GetBalance returns the amount of wei for the given address in the state of the
// GetBalance returns the amount of Nano for the given address in the state of the
// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
// block numbers are also allowed.
func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {

@ -9,13 +9,13 @@ import (
// PublicNetAPI offers network related RPC methods
type PublicNetAPI struct {
net p2p.Host
networkID uint64
net p2p.Host
networkVersion uint64
}
// NewPublicNetAPI creates a new net API instance.
func NewPublicNetAPI(net p2p.Host, networkID uint64) *PublicNetAPI {
return &PublicNetAPI{net, networkID}
func NewPublicNetAPI(net p2p.Host, networkVersion uint64) *PublicNetAPI {
return &PublicNetAPI{net, networkVersion}
}
// PeerCount returns the number of connected peers
@ -23,7 +23,7 @@ func (s *PublicNetAPI) PeerCount() hexutil.Uint {
return hexutil.Uint(s.net.GetPeerCount())
}
// NetworkID ...
func (s *PublicNetAPI) NetworkID() string {
return fmt.Sprintf("%d", 1) // TODO(ricl): we should add support for network id (https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version)
// Version returns the network version, i.e. network ID identifying which network we are using
func (s *PublicNetAPI) Version() string {
return fmt.Sprintf("%d", s.networkVersion) // TODO(ricl): we should add support for network id (https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version)
}

@ -263,7 +263,7 @@ var GenesisAccounts = [...]DeployAccount{
{Address: "0x7F58C0cD5c255020Ec94425873F666F1D68FBaA6", Private: "", Public: "0x7F58C0cD5c255020Ec94425873F666F1D68FBaA6"},
{Address: "0x7F686454f91A68cC3248a642F59aDb2970e84D8e", Private: "", Public: "0x7F686454f91A68cC3248a642F59aDb2970e84D8e"},
{Address: "0x9c23fE8cdcA1a8E529deeE8eD8492575cc3F9129", Private: "", Public: "0x9c23fE8cdcA1a8E529deeE8eD8492575cc3F9129"},
{Address: "0x324c741430F5B970b61E398434B4F3957a6BC6E0", Private: "", Public: "0x324c741430F5B970b61E398434B4F3957a6BC6E0"},
{Address: "0x5a22c7ec1579C0d87760F4C8ec32fBE24d40E1Dc", Private: "", Public: "0x5a22c7ec1579C0d87760F4C8ec32fBE24d40E1Dc"},
{Address: "0x7bBf40bD603B2434A964CdF979020B1E0E68E13D", Private: "", Public: "0x7bBf40bD603B2434A964CdF979020B1E0E68E13D"},
{Address: "0x22117D26611161b1b1f4EBB06C441aeeA102261c", Private: "", Public: "0x22117D26611161b1b1f4EBB06C441aeeA102261c"},
{Address: "0x7cc507b9345a58B5232e16B49b02F365bEB7d91e", Private: "", Public: "0x7cc507b9345a58B5232e16B49b02F365bEB7d91e"},
@ -277,7 +277,7 @@ var GenesisAccounts = [...]DeployAccount{
{Address: "0xeaD1fAa7E5Fdb6136057d4BfCa1f05D220D1441f", Private: "", Public: "0xeaD1fAa7E5Fdb6136057d4BfCa1f05D220D1441f"},
{Address: "0xa3B34f4E21C6c44A603E3c53abbF8b10C7BdaF59", Private: "", Public: "0xa3B34f4E21C6c44A603E3c53abbF8b10C7BdaF59"},
{Address: "0x82375BA85Dc7F301f6609a39E2C3FFccB1433d5e", Private: "", Public: "0x82375BA85Dc7F301f6609a39E2C3FFccB1433d5e"},
{Address: "0x8244c534557d3d40caD3771EdeA45d394bbc3f60", Private: "", Public: "0x8244c534557d3d40caD3771EdeA45d394bbc3f60"},
{Address: "0x144B2Fd168147311f749B0f9573664676C333e2A", Private: "", Public: "0x144B2Fd168147311f749B0f9573664676C333e2A"},
{Address: "0x689a35324d6B8DDDfa3bF5E7b26A23E704dD0100", Private: "", Public: "0x689a35324d6B8DDDfa3bF5E7b26A23E704dD0100"},
// 200-209

@ -12,9 +12,9 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/contracts"
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils"
contract_constants "github.com/harmony-one/harmony/internal/utils/contract"

@ -12,9 +12,9 @@ import (
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/bls/ffi/go/bls"
"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"
"github.com/harmony-one/harmony/api/service"
"github.com/harmony-one/harmony/api/service/syncing"
@ -48,6 +48,11 @@ const (
NodeLeader // Node is the leader of some shard.
)
const (
// TxPoolLimit is the limit of transaction pool.
TxPoolLimit = 20000
)
func (state State) String() string {
switch state {
case NodeInit:
@ -113,6 +118,9 @@ type Node struct {
Worker *worker.Worker
BeaconWorker *worker.Worker // worker for beacon chain
// Client server (for wallet requests)
clientServer *clientService.Server
// Syncing component.
syncID [SyncIDLength]byte // a unique ID for the node during the state syncing process with peers
downloaderServer *downloader.Server
@ -220,8 +228,14 @@ func (node *Node) Beaconchain() *core.BlockChain {
func (node *Node) addPendingTransactions(newTxs types.Transactions) {
node.pendingTxMutex.Lock()
node.pendingTransactions = append(node.pendingTransactions, newTxs...)
// If length of pendingTransactions is greater than TxPoolLimit then by greedy take the TxPoolLimit recent transactions.
if len(node.pendingTransactions) > TxPoolLimit {
utils.GetLogInstance().Warn("Got more transactions than expected and this could caused OOM", "num", len(newTxs), "totalPending", len(node.pendingTransactions))
curLen := len(node.pendingTransactions)
node.pendingTransactions = node.pendingTransactions[curLen-TxPoolLimit:]
}
node.pendingTxMutex.Unlock()
utils.GetLogInstance().Debug("Got more transactions", "num", len(newTxs), "totalPending", len(node.pendingTransactions))
utils.GetLogInstance().Info("Got more transactions", "num", len(newTxs), "totalPending", len(node.pendingTransactions))
}
// AddPendingTransaction adds one new transaction to the pending transaction list.

@ -12,8 +12,8 @@ import (
"github.com/ethereum/go-ethereum/params"
"github.com/pkg/errors"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/core/rawdb"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/ctxerror"

@ -413,13 +413,6 @@ func (node *Node) PostConsensusProcessing(newBlock *types.Block) {
}()
}
// ConfirmedBlockChannel which is listened by drand leader who will initiate DRG if its a epoch block (first block of a epoch)
if node.DRand != nil {
go func() {
node.ConfirmedBlockChannel <- newBlock
}()
}
// TODO: update staking information once per epoch.
node.UpdateStakingList(node.QueryStakeInfo())
node.printStakingList()

@ -22,82 +22,6 @@ const (
BlockPeriod = 10 * time.Second
)
// WaitForConsensusReady listen for the readiness signal from consensus and generate new block for consensus.
func (node *Node) WaitForConsensusReady(readySignal chan struct{}, stopChan chan struct{}, stoppedChan chan struct{}) {
go func() {
// Setup stoppedChan
defer close(stoppedChan)
utils.GetLogInstance().Debug("Waiting for Consensus ready")
time.Sleep(30 * time.Second) // Wait for other nodes to be ready (test-only)
firstTime := true
var newBlock *types.Block
timeoutCount := 0
deadline := time.Now().Add(BlockPeriod)
for {
// keep waiting for Consensus ready
select {
case <-readySignal:
time.Sleep(1000 * time.Millisecond) // Delay a bit so validator is catched up (test-only).
case <-time.After(ConsensusTimeOut * time.Second):
node.Consensus.ResetState()
timeoutCount++
utils.GetLogInstance().Debug("Consensus timeout, retry!", "count", timeoutCount)
// FIXME: retry is not working, there is no retry logic here. It will only wait for new transaction.
case <-stopChan:
utils.GetLogInstance().Debug("Consensus propose new block: STOPPED!")
return
}
for {
// threshold and firstTime are for the test-only built-in smart contract tx.
// TODO: remove in production
threshold := DefaultThreshold
if firstTime {
threshold = FirstTimeThreshold
firstTime = false
}
if len(node.pendingTransactions) >= threshold || !time.Now().Before(deadline) {
deadline = time.Now().Add(BlockPeriod)
utils.GetLogInstance().Debug("PROPOSING NEW BLOCK ------------------------------------------------", "blockNum", node.Blockchain().CurrentBlock().NumberU64()+1, "threshold", threshold, "pendingTransactions", len(node.pendingTransactions))
// Normal tx block consensus
selectedTxs := node.getTransactionsForNewBlock(MaxNumberOfTransactionsPerBlock)
if err := node.Worker.CommitTransactions(selectedTxs); err != nil {
ctxerror.Log15(utils.GetLogger().Error,
ctxerror.New("cannot commit transacttions").
WithCause(err))
}
block, err := node.Worker.Commit()
if err != nil {
ctxerror.Log15(utils.GetLogInstance().Error,
ctxerror.New("Failed committing new block").
WithCause(err))
} else if err := node.proposeShardState(block); err != nil {
ctxerror.Log15(utils.GetLogger().Error,
ctxerror.New("cannot add shard state").
WithCause(err))
} else {
newBlock = block
utils.GetLogInstance().Debug("Successfully proposed new block", "blockNum", block.NumberU64(), "numTxs", block.Transactions().Len())
threshold = DefaultThreshold
break
}
}
// If not enough transactions to run Consensus,
// periodically check whether we have enough transactions to package into block.
time.Sleep(PeriodicBlock)
}
// Send the new block to Consensus so it can be confirmed.
if newBlock != nil {
utils.GetLogInstance().Debug("Consensus sending new block to block channel")
node.BlockChannel <- newBlock
utils.GetLogInstance().Debug("Consensus sent new block to block channel")
}
}
}()
}
// WaitForConsensusReadyv2 listen for the readiness signal from consensus and generate new block for consensus.
// only leader will receive the ready signal
// TODO: clean pending transactions for validators; or validators not prepare pending transactions

@ -31,7 +31,7 @@ var (
httpEndpoint = ""
wsEndpoint = ""
httpModules = []string{"hmy"}
httpModules = []string{"hmy", "net"}
httpVirtualHosts = []string{"*"}
httpTimeouts = rpc.DefaultHTTPTimeouts
@ -149,5 +149,11 @@ func (node *Node) APIs() []rpc.API {
Service: filters.NewPublicFilterAPI(harmony.APIBackend, false),
Public: true,
},
{
Namespace: "net",
Version: "1.0",
Service: hmyapi.NewPublicNetAPI(node.host, harmony.APIBackend.NetVersion()),
Public: true,
},
}...)
}

@ -4,6 +4,7 @@ import (
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/api/service"
"github.com/harmony-one/harmony/api/service/blockproposal"
"github.com/harmony-one/harmony/api/service/clientsupport"
"github.com/harmony-one/harmony/api/service/consensus"
"github.com/harmony-one/harmony/api/service/discovery"
"github.com/harmony-one/harmony/api/service/explorer"
@ -28,11 +29,15 @@ func (node *Node) setupForShardLeader() {
node.serviceManager.RegisterService(service.Consensus, consensus.New(node.BlockChannel, node.Consensus, node.startConsensus))
// Register new block service.
node.serviceManager.RegisterService(service.BlockProposal, blockproposal.New(node.Consensus.ReadySignal, node.WaitForConsensusReadyv2))
// Register client support service.
node.serviceManager.RegisterService(service.ClientSupport, clientsupport.New(node.Blockchain().State, node.CallFaucetContract, node.getDeployedStakingContract, node.SelfPeer.IP, node.SelfPeer.Port))
}
func (node *Node) setupForShardValidator() {
nodeConfig, chanPeer := node.initNodeConfiguration()
// Register client support service.
node.serviceManager.RegisterService(service.ClientSupport, clientsupport.New(node.Blockchain().State, node.CallFaucetContract, node.getDeployedStakingContract, node.SelfPeer.IP, node.SelfPeer.Port))
// Register peer discovery service. "0" is the beacon shard ID. No need to do staking for beacon chain node.
node.serviceManager.RegisterService(service.PeerDiscovery, discovery.New(node.host, nodeConfig, chanPeer, node.AddBeaconPeer))
// Register networkinfo service. "0" is the beacon shard ID
@ -51,7 +56,8 @@ func (node *Node) setupForBeaconLeader() {
node.serviceManager.RegisterService(service.PeerDiscovery, discovery.New(node.host, nodeConfig, chanPeer, nil))
// Register networkinfo service.
node.serviceManager.RegisterService(service.NetworkInfo, networkinfo.New(node.host, node.NodeConfig.GetShardGroupID(), chanPeer, nil))
// Register client support service.
node.serviceManager.RegisterService(service.ClientSupport, clientsupport.New(node.Blockchain().State, node.CallFaucetContract, node.getDeployedStakingContract, node.SelfPeer.IP, node.SelfPeer.Port))
// Register consensus service.
node.serviceManager.RegisterService(service.Consensus, consensus.New(node.BlockChannel, node.Consensus, node.startConsensus))
// Register new block service.
@ -74,7 +80,7 @@ func (node *Node) setupForBeaconValidator() {
// Register new block service.
node.serviceManager.RegisterService(service.BlockProposal, blockproposal.New(node.Consensus.ReadySignal, node.WaitForConsensusReadyv2))
// Register client support service.
node.serviceManager.RegisterService(service.ClientSupport, clientsupport.New(node.Blockchain().State, node.CallFaucetContract, node.getDeployedStakingContract, node.SelfPeer.IP, node.SelfPeer.Port))
}
func (node *Node) setupForNewNode() {

@ -8,9 +8,9 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/consensus"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/denominations"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/core/vm"
)

Loading…
Cancel
Save