From e308e77b755a7e8e92795636ff61e388a186d08c Mon Sep 17 00:00:00 2001 From: xiaobo Date: Wed, 26 Oct 2022 16:16:03 +0800 Subject: [PATCH] feat(nft): refactoring settings and config Signed-off-by: xiaobo --- .gitignore | 1 + Makefile | 2 +- benchmark/common/tx/fixamontassigner.go | 5 +- benchmark/common/tx/transferasset.go | 7 +- benchmark/sync/synctobestheight_test.go | 119 +- benchmark/tools/generator/chain/datagen.go | 16 +- .../tools/generator/chain/txrepository.go | 2 +- .../generator/chain/txrepository_test.go | 2 +- benchmark/tools/generator/chain/utils.go | 37 +- .../calculator/multiinputsofoneaccount.go | 2 +- blockchain/blockchain.go | 135 +- blockchain/blockindex.go | 6 +- blockchain/blockvalidator.go | 18 +- blockchain/chainio.go | 5 +- blockchain/chainstore.go | 4 +- blockchain/chainstoreffldb.go | 4 +- blockchain/confirmvalidator.go | 1 + blockchain/difficulty.go | 14 +- blockchain/difficulty_test.go | 2 +- blockchain/indexers/manager.go | 2 +- blockchain/indexers/returndepositindex.go | 1 + blockchain/indexers/txcache.go | 15 +- blockchain/indexers/txindex.go | 1 + blockchain/indexers/unspentindex.go | 10 +- blockchain/indexers/utxoindex.go | 1 + blockchain/ledger.go | 26 +- blockchain/txvalidator.go | 29 +- blockchain/utxocache.go | 4 +- cmd/common/common.go | 5 - cmd/common/flags.go | 416 +----- cmd/ela-cli.go | 2 +- cmd/rollback/rollback.go | 13 +- cmd/script/api/api.go | 13 +- cmd/script/api/attribute.go | 1 + cmd/script/api/block.go | 4 +- cmd/script/api/clienttype.go | 1 + cmd/script/api/header.go | 4 +- cmd/script/api/illegalvotes.go | 2 +- cmd/script/api/inputtype.go | 2 +- cmd/script/api/mock/peer.go | 5 +- cmd/script/api/outputtype.go | 2 +- cmd/script/api/payloadtype.go | 3 +- common/config/config.go | 929 +++++++++--- common/config/config_test.go | 120 ++ common/config/params.go | 972 ------------ common/config/params_test.go | 43 - common/config/settings/settings.go | 1318 +---------------- core/checkpoint/channels.go | 17 +- core/checkpoint/channels_test.go | 9 +- core/checkpoint/manager.go | 40 +- core/checkpoint/manager_test.go | 64 +- core/contract/contract_test.go | 2 +- core/contract/crosschain.go | 2 +- core/manager.go | 99 ++ .../activateproducertransaction.go | 4 +- core/transaction/coinbasetransaction.go | 16 +- core/transaction/common.go | 2 +- .../transaction/crassetsrectifytransaction.go | 15 +- .../crcappropriationtransaction.go | 17 +- .../crcouncilmemberclaimnodetransaction.go | 2 +- .../crcproposalrealwithdrawtransaction.go | 13 +- .../crcproposalreviewtransaction.go | 6 +- .../crcproposaltrackingtransaction.go | 10 +- core/transaction/crcproposaltransaction.go | 8 +- core/transaction/crcproposalwithdraw.go | 16 +- ...posv2claimrewardrealwithdrawtransaction.go | 8 +- .../dposv2claimrewardtransaction.go | 4 +- core/transaction/exchangevotes.go | 9 +- .../inactivearbitratorstransaction.go | 4 +- .../nexttrundposinfotransaction.go | 2 +- core/transaction/registercrtransaction.go | 6 +- .../registerproducertransaction.go | 10 +- .../returncrdepositcointransaction.go | 2 +- .../returndepositcointransaction.go | 2 +- .../returnsidechaindepositcointransaction.go | 5 +- core/transaction/returnvotes.go | 2 +- core/transaction/reverttodpostransaction.go | 2 +- core/transaction/reverttopowtransaction.go | 6 +- core/transaction/sidechainpowtransaction.go | 5 +- core/transaction/transactionCheckParameter.go | 2 +- core/transaction/transactionchecker.go | 21 +- core/transaction/transferassettransaction.go | 7 +- .../transfercrosschainassettransaction.go | 7 +- core/transaction/txdeserialize_test.go | 2 +- core/transaction/unregistercrtransaction.go | 2 +- core/transaction/updatecrtransaction.go | 2 +- core/transaction/updateproducertransaction.go | 4 +- core/transaction/votesrealwithdrawtx.go | 8 +- core/transaction/voting.go | 6 +- .../withdrawfromsidechaintransaction.go | 26 +- core/types/dposheader.go | 2 +- core/types/functions/function.go | 2 +- core/types/interfaces/initpayload.go | 1 + core/types/outputpayload/exchangevotes.go | 2 +- core/types/outputpayload/vote_test.go | 2 +- .../payload/returnsidechaindepositcoin.go | 3 +- cr/state/checkpoint.go | 2 +- cr/state/committee.go | 135 +- cr/state/committeeaction.go | 13 +- cr/state/keyframe.go | 2 +- cr/state/proposalmanager.go | 23 +- cr/state/state.go | 11 +- crypto/common.go | 1 + dpos/account/account.go | 2 +- dpos/arbitrator.go | 8 +- dpos/log/eventmonitor.go | 2 +- dpos/manager/dposmanager.go | 4 +- dpos/manager/proposaldispatcher.go | 2 +- dpos/network.go | 8 +- dpos/p2p/msg/getblocks.go | 3 +- dpos/p2p/msg/responseblocks.go | 3 +- dpos/p2p/peer/peer_test.go | 2 +- dpos/p2p/server_test.go | 2 +- dpos/state/arbitrators.go | 194 +-- dpos/state/arbitratorsmock.go | 2 +- dpos/state/checkpoint.go | 2 +- dpos/state/dposarbiter_test.go | 5 +- dpos/state/heightversion.go | 13 +- dpos/state/originarbiter.go | 2 +- dpos/state/state.go | 64 +- dpos/state/state_test.go | 6 +- elanet/bloom/filter.go | 2 +- elanet/bloom/merkleblock.go | 2 +- elanet/bloom/merklebranch.go | 2 +- elanet/bloom/merklebranch_test.go | 2 +- elanet/dns/main/main.go | 7 +- elanet/interface.go | 6 +- elanet/netsync/interface.go | 2 +- elanet/netsync/manager.go | 2 +- elanet/server.go | 12 +- go.mod | 10 +- log.go | 29 +- main.go | 219 ++- mempool/blockpool.go | 11 +- mempool/conflictmanager.go | 28 +- mempool/conflictmanager_test.go | 7 +- mempool/conflictslot.go | 3 +- mempool/txfeeorderedlist_bench_test.go | 5 +- mempool/txpool.go | 25 +- mempool/txpool_test.go | 19 +- mempool/txpoolcheckpoint.go | 2 +- p2p/header.go | 2 +- p2p/peer/peer.go | 2 +- pow/revertlistener.go | 4 +- pow/service.go | 49 +- pow/service_test.go | 21 +- servers/interfaces.go | 59 +- test/unit/arbitrators_test.go | 9 +- test/unit/arbitratorsrollback_test.go | 30 +- test/unit/blockvalidator_test.go | 15 +- test/unit/candidate_test.go | 2 +- test/unit/chainstore_test.go | 32 +- test/unit/committee_test.go | 130 +- test/unit/committeerollback_test.go | 266 ++-- test/unit/crkeyframe_test.go | 2 +- test/unit/dposkeyframe_test.go | 4 +- test/unit/dposstate_test.go | 34 +- test/unit/heightversion_test.go | 36 +- test/unit/returndepositindex_test.go | 2 +- test/unit/reward_test.go | 24 +- test/unit/server_test.go | 2 +- test/unit/state_test.go | 30 +- test/unit/transaction_test.go | 2 +- test/unit/txvalidator_specailtx_test.go | 7 +- test/unit/txvalidator_test.go | 304 ++-- test/unit/unspentindex_test.go | 74 +- test/unit/utxocache_test.go | 12 +- test/unit/utxoindex_test.go | 77 +- test/unit/validation_test.go | 22 +- utils/common.go | 27 +- wallet/coin.go | 2 +- wallet/coin_test.go | 2 +- wallet/coincheckpoint.go | 2 +- wallet/coincheckpoint_test.go | 2 +- wallet/common.go | 2 +- wallet/wallet.go | 19 +- wallet/wallet_test.go | 2 +- 177 files changed, 2683 insertions(+), 4368 deletions(-) create mode 100644 common/config/config_test.go delete mode 100644 common/config/params.go delete mode 100644 common/config/params_test.go create mode 100644 core/manager.go diff --git a/.gitignore b/.gitignore index a5a732f46..9bade99bf 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ elastos*/ /tmp /go.sum keystore +goheader *.out *.test benchmark/process/run-to-height diff --git a/Makefile b/Makefile index ce0385ca0..e36eb95a3 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ GOVER := $(shell go version) VERSION := $(shell git describe --abbrev=4 --dirty --always --tags) -BUILD = go build -ldflags "-X main.Version=$(VERSION) -X 'main.GoVersion=$(GOVER)'" #-race +BUILD = go build -ldflags "-X main.Version=$(VERSION) -X 'main.GoVersion=$(GOVER)'" DEV_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) DEV_VERSION := $(shell git rev-list HEAD -n 1 | cut -c 1-8) diff --git a/benchmark/common/tx/fixamontassigner.go b/benchmark/common/tx/fixamontassigner.go index 90ea6c826..c23fb098d 100644 --- a/benchmark/common/tx/fixamontassigner.go +++ b/benchmark/common/tx/fixamontassigner.go @@ -9,7 +9,7 @@ import ( "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/benchmark/common/utils" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/outputpayload" @@ -38,8 +38,9 @@ func (a *fixAmountAssigner) SignAndChange(tx interfaces.Transaction) error { for _, o := range tx.Outputs() { o.Value = defaultAmount } + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) tx.SetOutputs(append(tx.Outputs(), &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: a.utxo.Value - defaultAmount*common.Fixed64(len(tx.Outputs())) - defaultFee, OutputLock: 0, diff --git a/benchmark/common/tx/transferasset.go b/benchmark/common/tx/transferasset.go index 992685468..cdb597293 100644 --- a/benchmark/common/tx/transferasset.go +++ b/benchmark/common/tx/transferasset.go @@ -8,7 +8,8 @@ package tx import ( "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/benchmark/common/utils" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" @@ -41,9 +42,11 @@ func (g *transferAssetGenerator) Generate() interfaces.Transaction { 0, nil, ) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, v := range g.account { + txn.SetOutputs(append(txn.Outputs(), &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 0, // assign later OutputLock: 0, ProgramHash: v.ProgramHash, diff --git a/benchmark/sync/synctobestheight_test.go b/benchmark/sync/synctobestheight_test.go index ddbcf5a68..1bd13d517 100644 --- a/benchmark/sync/synctobestheight_test.go +++ b/benchmark/sync/synctobestheight_test.go @@ -7,7 +7,6 @@ package sync import ( "bytes" - "flag" "fmt" "os" "os/exec" @@ -19,10 +18,11 @@ import ( "time" "github.com/elastos/Elastos.ELA/blockchain" - cmdcom "github.com/elastos/Elastos.ELA/cmd/common" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/config/settings" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/types" crstate "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/dpos/state" @@ -76,25 +76,26 @@ func Benchmark_Sync_ToBestHeight(b *testing.B) { func startDstNode() { // Enable profiling server if requested. - if dstSettings.Config().ProfilePort != 0 { - go utils.StartPProf(dstSettings.Config().ProfilePort, - dstSettings.Config().ProfileHost) + if dstSettings.ProfilePort != 0 { + go utils.StartPProf(dstSettings.ProfilePort, + dstSettings.ProfileHost) } flagDataDir := dstContext.String("datadir") dataDir := filepath.Join(flagDataDir, dataPath) - dstSettings.Params().CkpManager.SetDataPath( - filepath.Join(dataDir, checkpointPath)) - dstSettings.Params().CkpManager.SetNeedSave(true) + + ckpManager := checkpoint.NewManager(dstSettings) + ckpManager.SetDataPath(filepath.Join(dataDir, checkpointPath)) var interrupt = signal.NewInterrupt() ledger := blockchain.Ledger{} // Initializes the foundation address - blockchain.FoundationAddress = dstSettings.Params().Foundation + FoundationAddress, _ := common.Uint168FromAddress(dstSettings.FoundationAddress) + blockchain.FoundationAddress = *FoundationAddress - chainStore, err := blockchain.NewChainStore(dataDir, dstSettings.Params()) + chainStore, err := blockchain.NewChainStore(dataDir, dstSettings) if err != nil { logger.Error(err) return @@ -102,16 +103,16 @@ func startDstNode() { defer chainStore.Close() ledger.Store = chainStore - txMemPool := mempool.NewTxPool(dstSettings.Params()) - blockMemPool := mempool.NewBlockPool(dstSettings.Params()) + txMemPool := mempool.NewTxPool(dstSettings, ckpManager) + blockMemPool := mempool.NewBlockPool(dstSettings) blockMemPool.Store = chainStore blockchain.DefaultLedger = &ledger - committee := crstate.NewCommittee(dstSettings.Params()) + committee := crstate.NewCommittee(dstSettings, ckpManager) ledger.Committee = committee - arbiters, err := state.NewArbitrators(dstSettings.Params(), committee, + arbiters, err := state.NewArbitrators(dstSettings, committee, func(programHash common.Uint168) (common.Fixed64, error) { amount := common.Fixed64(0) @@ -125,14 +126,15 @@ func startDstNode() { } return amount, nil }, nil, nil, - nil, nil, nil, nil) + nil, nil, nil, nil, + ckpManager) if err != nil { logger.Error(err) return } ledger.Arbitrators = arbiters - chain, err := blockchain.New(chainStore, dstSettings.Params(), arbiters.State, committee) + chain, err := blockchain.New(chainStore, dstSettings, arbiters.State, committee, ckpManager) if err != nil { logger.Error(err) return @@ -142,7 +144,7 @@ func startDstNode() { return } if err := chain.MigrateOldDB(interrupt.C, func(uint32) {}, - func() {}, dataDir, dstSettings.Params()); err != nil { + func() {}, dataDir, dstSettings); err != nil { logger.Error(err) return } @@ -168,8 +170,8 @@ func startDstNode() { route := routes.New(routesCfg) server, err := elanet.NewServer(dataDir, &elanet.Config{ Chain: chain, - ChainParams: dstSettings.Params(), - PermanentPeers: dstSettings.Params().PermanentPeers, + ChainParams: dstSettings, + PermanentPeers: dstSettings.PermanentPeers, TxMemPool: txMemPool, BlockMemPool: blockMemPool, Routes: route, @@ -196,14 +198,13 @@ func startDstNode() { wal := wallet.NewWallet() wallet.Store = chainStore - wallet.ChainParam = dstSettings.Params() + wallet.ChainParam = dstSettings wallet.Chain = chain - dstSettings.Params().CkpManager.Register(wal) + ckpManager.Register(wal) servers.Compile = "benchmark" - servers.Config = dstSettings.Config() - servers.ChainParams = dstSettings.Params() + servers.ChainParams = dstSettings servers.Chain = chain servers.Store = chainStore servers.TxMemPool = txMemPool @@ -211,10 +212,10 @@ func startDstNode() { servers.Arbiters = arbiters servers.Wallet = wal servers.Pow = pow.NewService(&pow.Config{ - PayToAddr: dstSettings.Config().PowConfiguration.PayToAddr, - MinerInfo: dstSettings.Config().PowConfiguration.MinerInfo, + PayToAddr: dstSettings.PowConfiguration.PayToAddr, + MinerInfo: dstSettings.PowConfiguration.MinerInfo, Chain: chain, - ChainParams: dstSettings.Params(), + ChainParams: dstSettings, TxMemPool: txMemPool, BlkMemPool: blockMemPool, BroadcastBlock: func(block *types.Block) { @@ -276,55 +277,11 @@ func getSrcRunArgs() []string { } } -func newCliContext(st *settings.Settings) *cli.Context { - ctx := cli.NewContext(nil, newFlagSet(st), nil) - ctx.Set("magic", magic) - ctx.Set("conf", configPath) - ctx.Set("datadir", dstDataDir) - ctx.Set("peers", getPeerAddr(srcNodePort)) - ctx.Set("port", dstNodePort) - ctx.Set("arbiter", "false") - ctx.Set("server", "false") - ctx.Set("automining", "false") - return ctx -} - -func initDstSettings() *settings.Settings { - st := settings.NewSettings() - dstContext = newCliContext(st) - st.SetContext(dstContext) - st.SetupConfig() - st.InitParamsValue() - setupLog(dstContext, st) - return st -} - -func newFlagSet(st *settings.Settings) *flag.FlagSet { - originFlags := []cli.StringFlag{ - cmdcom.ConfigFileFlag, - cmdcom.DataDirFlag, - cmdcom.AccountPasswordFlag, - cmdcom.TestNetFlag, - cmdcom.RegTestFlag, - cmdcom.InfoPortFlag, - cmdcom.RestPortFlag, - cmdcom.WsPortFlag, - cmdcom.InstantBlockFlag, - cmdcom.RPCPortFlag, - } - result := &flag.FlagSet{} - - for _, v := range originFlags { - result.String(v.GetName(), v.GetValue(), v.GetUsage()) - } - - for _, v := range st.Flags() { - if strFlag, ok := v.(cli.StringFlag); ok { - result.String(strFlag.GetName(), strFlag.GetValue(), - strFlag.GetUsage()) - } - } - return result +func initDstSettings() *config.Configuration { + setting := settings.NewSettings() + config := setting.SetupConfig() + setupLog(config) + return config } func waitForSyncFinish(server elanet.Server, interrupt <-chan struct{}) { @@ -345,12 +302,14 @@ out: } } -func setupLog(c *cli.Context, s *settings.Settings) { - flagDataDir := c.String("datadir") +func setupLog(s *config.Configuration) { + flagDataDir := config.DataDir + if s.DataDir != "" { + flagDataDir = s.DataDir + } path := filepath.Join(flagDataDir, dstNodeLogPath) - - logger = log.NewDefault(path, uint8(s.Config().PrintLevel), - s.Config().MaxPerLogSize, s.Config().MaxLogsSize) + logger = log.NewDefault(path, uint8(s.PrintLevel), + s.MaxPerLogSize, s.MaxLogsSize) addrmgr.UseLogger(logger) connmgr.UseLogger(logger) diff --git a/benchmark/tools/generator/chain/datagen.go b/benchmark/tools/generator/chain/datagen.go index 94a3b7602..b74dc0b89 100644 --- a/benchmark/tools/generator/chain/datagen.go +++ b/benchmark/tools/generator/chain/datagen.go @@ -19,6 +19,8 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" @@ -41,7 +43,7 @@ type TimeCounter struct { type DataGen struct { txRepo *TxRepository chain *blockchain.BlockChain - chainParams *config.Params + chainParams *config.Configuration pow *pow.Service txPool *mempool.TxPool prevBlockHash common.Uint256 @@ -272,14 +274,15 @@ func LoadDataGen(dataPath string) (*DataGen, error) { func FromTxRepository(dataDir string, interrupt <-chan struct{}, repo *TxRepository, initFoundationUTXO bool) (*DataGen, error) { - chainParams := generateChainParams(repo.GetFoundationAccount()) + chainParams := config.DefaultParams.RegNet() chain, err := newBlockChain(dataDir, chainParams, interrupt) + ckpManager := checkpoint.NewManager(chainParams) if err != nil { return nil, err } - + block := core.GenesisBlock(chainParams.FoundationAddress) if initFoundationUTXO { - fundTx := chainParams.GenesisBlock.Transactions[0] + fundTx := block.Transactions[0] repo.SetFoundationUTXO(&common2.UTXO{ TxID: fundTx.Hash(), Index: 0, @@ -292,14 +295,15 @@ func FromTxRepository(dataDir string, interrupt <-chan struct{}, return nil, err } - txPool := mempool.NewTxPool(chainParams) + txPool := mempool.NewTxPool(chainParams, + ckpManager) return &DataGen{ txRepo: repo, chainParams: chainParams, chain: chain, txPool: txPool, foundationAddr: foundationAddr, - prevBlockHash: chainParams.GenesisBlock.Hash(), + prevBlockHash: block.Hash(), dataDir: dataDir, pressure: false, pressureTxSize: 8000000, diff --git a/benchmark/tools/generator/chain/txrepository.go b/benchmark/tools/generator/chain/txrepository.go index a1be2dece..550330759 100644 --- a/benchmark/tools/generator/chain/txrepository.go +++ b/benchmark/tools/generator/chain/txrepository.go @@ -6,7 +6,6 @@ package chain import ( - "github.com/elastos/Elastos.ELA/core/types/interfaces" "io" "math/rand" @@ -14,6 +13,7 @@ import ( "github.com/elastos/Elastos.ELA/benchmark/common/tx" "github.com/elastos/Elastos.ELA/common" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/crypto" ) diff --git a/benchmark/tools/generator/chain/txrepository_test.go b/benchmark/tools/generator/chain/txrepository_test.go index 66cbed225..27036024b 100644 --- a/benchmark/tools/generator/chain/txrepository_test.go +++ b/benchmark/tools/generator/chain/txrepository_test.go @@ -7,13 +7,13 @@ package chain import ( "bytes" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "math" "math/rand" "testing" "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/stretchr/testify/assert" ) diff --git a/benchmark/tools/generator/chain/utils.go b/benchmark/tools/generator/chain/utils.go index e80b4eef9..3b560f687 100644 --- a/benchmark/tools/generator/chain/utils.go +++ b/benchmark/tools/generator/chain/utils.go @@ -6,6 +6,7 @@ package chain import ( + "path/filepath" "sort" "time" @@ -14,6 +15,8 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" @@ -28,20 +31,23 @@ import ( "github.com/elastos/Elastos.ELA/utils/test" ) -func newBlockChain(path string, params *config.Params, +var checkpointPath = "checkpoints" + +func newBlockChain(path string, params *config.Configuration, interrupt <-chan struct{}) (*blockchain.BlockChain, error) { log.NewDefault(test.NodeLogPath, 1, 0, 0) - - committee := crstate.NewCommittee(params) + ckpManager := checkpoint.NewManager(params) + ckpManager.SetDataPath(filepath.Join(params.DataDir, checkpointPath)) + committee := crstate.NewCommittee(params, ckpManager) arbiters, err := state.NewArbitrators( params, committee, nil, nil, - nil, nil, nil, nil, nil) - + nil, nil, + nil, nil, nil, ckpManager) chainStore, err := blockchain.NewChainStore(path, params) if err != nil { return nil, err } - chain, err := blockchain.New(chainStore, params, arbiters.State, committee) + chain, err := blockchain.New(chainStore, params, arbiters.State, committee, ckpManager) if err != nil { return nil, err } @@ -84,15 +90,8 @@ func initDefaultLedger(chain *blockchain.BlockChain, } } -func generateChainParams(ac *account.Account) *config.Params { - proto := config.DefaultParams.RegNet() - proto.GenesisBlock = newGenesisBlock(ac) - proto.Foundation = ac.ProgramHash - blockchain.FoundationAddress = ac.ProgramHash - return proto.InstantBlock() -} - func newGenesisBlock(ac *account.Account) *types.Block { + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) attrNonce := common2.NewAttribute(common2.Nonce, []byte{77, 101, 130, 33, 7, 252, 253, 82}) genesisTime, _ := time.Parse(time.RFC3339, "2017-12-22T10:00:00Z") @@ -114,7 +113,7 @@ func newGenesisBlock(ac *account.Account) *types.Block { }, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 3300 * 10000 * 100000000, ProgramHash: ac.ProgramHash, }, @@ -124,7 +123,7 @@ func newGenesisBlock(ac *account.Account) *types.Block { ) merkleRoot, _ := crypto.ComputeRoot([]common.Uint256{coinBase.Hash(), - config.ELAAssetID}) + *ELAAssetID}) return &types.Block{ Header: common2.Header{ @@ -161,7 +160,7 @@ func newGenesisBlock(ac *account.Account) *types.Block { } func quickGenerateBlock(pow *pow.Service, prevHash *common.Uint256, - txs []interfaces.Transaction, minerAddr string, params *config.Params, + txs []interfaces.Transaction, minerAddr string, params *config.Configuration, height uint32) (*types.Block, error) { coinBaseTx, err := pow.CreateCoinbaseTx(minerAddr, height) if err != nil { @@ -173,7 +172,7 @@ func quickGenerateBlock(pow *pow.Service, prevHash *common.Uint256, Previous: *prevHash, MerkleRoot: common.EmptyHash, Timestamp: uint32(time.Now().Unix()), - Bits: params.PowLimitBits, + Bits: params.PowConfiguration.PowLimitBits, Height: height, Nonce: 0, } @@ -221,7 +220,7 @@ func quickGenerateBlock(pow *pow.Service, prevHash *common.Uint256, txCount++ } - totalReward := totalTxFee + params.RewardPerBlock + totalReward := totalTxFee + params.PowConfiguration.RewardPerBlock pow.AssignCoinbaseTxRewards(msgBlock, totalReward) txHash := make([]common.Uint256, 0, len(msgBlock.Transactions)) diff --git a/benchmark/tools/inputcounter/calculator/multiinputsofoneaccount.go b/benchmark/tools/inputcounter/calculator/multiinputsofoneaccount.go index 0486b641a..76b5f6fc3 100644 --- a/benchmark/tools/inputcounter/calculator/multiinputsofoneaccount.go +++ b/benchmark/tools/inputcounter/calculator/multiinputsofoneaccount.go @@ -7,9 +7,9 @@ package calculator import ( "bytes" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" ) type multiInputsOfOneAccount struct { diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 1f261f606..f6c665d4c 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -10,7 +10,6 @@ import ( "container/list" "errors" "fmt" - "github.com/elastos/Elastos.ELA/dpos/p2p/peer" "math/big" "os" "path/filepath" @@ -22,6 +21,8 @@ import ( . "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract/program" . "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/common" @@ -31,6 +32,7 @@ import ( "github.com/elastos/Elastos.ELA/core/types/payload" crstate "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/database" + "github.com/elastos/Elastos.ELA/dpos/p2p/peer" "github.com/elastos/Elastos.ELA/dpos/state" "github.com/elastos/Elastos.ELA/events" "github.com/elastos/Elastos.ELA/p2p/msg" @@ -49,7 +51,8 @@ var ( ) type BlockChain struct { - chainParams *config.Params + chainParams *config.Configuration + CkpManager *checkpoint.Manager db IChainStore state *state.State crCommittee *crstate.Committee @@ -85,19 +88,20 @@ type BlockChain struct { mutex sync.RWMutex } -func New(db IChainStore, chainParams *config.Params, state *state.State, - committee *crstate.Committee) (*BlockChain, error) { +func New(db IChainStore, chainParams *config.Configuration, state *state.State, + committee *crstate.Committee, ckpManager *checkpoint.Manager) (*BlockChain, error) { - targetTimespan := int64(chainParams.TargetTimespan / time.Second) - targetTimePerBlock := int64(chainParams.TargetTimePerBlock / time.Second) - adjustmentFactor := chainParams.AdjustmentFactor + targetTimespan := int64(chainParams.PowConfiguration.TargetTimespan / time.Second) + targetTimePerBlock := int64(chainParams.PowConfiguration.TargetTimePerBlock / time.Second) + adjustmentFactor := chainParams.PowConfiguration.AdjustmentFactor chain := BlockChain{ chainParams: chainParams, db: db, state: state, + CkpManager: ckpManager, crCommittee: committee, UTXOCache: NewUTXOCache(db, chainParams), - GenesisHash: chainParams.GenesisBlock.Hash(), + GenesisHash: core.GenesisBlock(chainParams.FoundationAddress).Hash(), minRetargetTimespan: targetTimespan / adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor, blocksPerRetarget: uint32(targetTimespan / targetTimePerBlock), @@ -129,7 +133,7 @@ func (b *BlockChain) GetDB() IChainStore { return b.db } -func (b *BlockChain) GetParams() *config.Params { +func (b *BlockChain) GetParams() *config.Configuration { return b.chainParams } @@ -145,7 +149,7 @@ func (b *BlockChain) MigrateOldDB( barStart func(total uint32), increase func(), dataDir string, - params *config.Params) (err error) { + params *config.Configuration) (err error) { // No old database need migrate. if !utils.FileExisted(filepath.Join(dataDir, oldBlockDbName)) { @@ -169,7 +173,7 @@ func (b *BlockChain) MigrateOldDB( oldChainStore := &ChainStore{ fflDB: oldChainStoreFFLDB, } - oldChain, err := New(oldChainStore, params, nil, nil) + oldChain, err := New(oldChainStore, params, nil, nil, b.CkpManager) if err != nil { return err } @@ -277,17 +281,16 @@ func (b *BlockChain) InitCheckpoint(interrupt <-chan struct{}, bestHeight := b.GetHeight() log.Info("current block height ->", bestHeight) arbiters := DefaultLedger.Arbitrators - ckpManager := b.chainParams.CkpManager done := make(chan struct{}) go func() { // Notify initialize process start. startHeight := uint32(0) - if err = ckpManager.Restore(); err != nil { + if err = b.CkpManager.Restore(); err != nil { log.Warn(err) err = nil } - safeHeight := ckpManager.SafeHeight() + safeHeight := b.CkpManager.SafeHeight() if startHeight < safeHeight { startHeight = safeHeight + 1 } @@ -309,7 +312,7 @@ func (b *BlockChain) InitCheckpoint(interrupt <-chan struct{}, } if block.Height >= bestHeight-uint32( - b.chainParams.GeneralArbiters+len(b.chainParams.CRCArbiters)) { + b.chainParams.DPoSConfiguration.NormalArbitratorsCount+len(b.chainParams.DPoSConfiguration.CRCArbiters)) { CalculateTxsFee(block.Block) } @@ -318,7 +321,7 @@ func (b *BlockChain) InitCheckpoint(interrupt <-chan struct{}, break } - b.chainParams.CkpManager.OnBlockSaved(block, nil, b.state.ConsensusAlgorithm == state.POW) + b.CkpManager.OnBlockSaved(block, nil, b.state.ConsensusAlgorithm == state.POW) // Notify process increase. if increase != nil { @@ -342,7 +345,6 @@ func (b *BlockChain) InitCheckpoint(interrupt <-chan struct{}, NextPeers: nextArbiters, CRPeers: crArbiters}) - case <-interrupt: } return err @@ -416,7 +418,7 @@ func (b *BlockChain) getUTXOsFromAddress(address Uint168) ([]*common.UTXO, Fixed return nil, 0, err } diff := curHeight - referTxn.LockTime() - if referTxn.IsCoinBaseTx() && diff < b.chainParams.CoinbaseMaturity { + if referTxn.IsCoinBaseTx() && diff < b.chainParams.PowConfiguration.CoinbaseMaturity { lockedAmount += utxo.Value continue } @@ -473,7 +475,9 @@ func (b *BlockChain) createInputs(fromAddress Uint168, } func (b *BlockChain) CreateCRCAppropriationTransaction() (interfaces.Transaction, Fixed64, error) { - utxos, lockedAmount, err := b.getUTXOsFromAddress(b.chainParams.CRAssetsAddress) + CRAssetsAddress, _ := Uint168FromAddress(b.chainParams.CRConfiguration.CRAssetsAddress) + CRExpensesAddress, _ := Uint168FromAddress(b.chainParams.CRConfiguration.CRExpensesAddress) + utxos, lockedAmount, err := b.getUTXOsFromAddress(*CRAssetsAddress) if err != nil { return nil, 0, err } @@ -481,18 +485,18 @@ func (b *BlockChain) CreateCRCAppropriationTransaction() (interfaces.Transaction for _, u := range utxos { crcFoundationBalance += u.Value } - p := b.chainParams.CRCAppropriatePercentage + p := b.chainParams.CRConfiguration.CRCAppropriatePercentage appropriationAmount := Fixed64(float64(crcFoundationBalance) * p / 100.0) log.Info("create appropriation transaction amount:", appropriationAmount) if appropriationAmount <= 0 { return nil, 0, nil } - outputs := []*common.OutputInfo{{b.chainParams.CRExpensesAddress, + outputs := []*common.OutputInfo{{*CRExpensesAddress, appropriationAmount}} tx, err := b.createTransaction(&payload.CRCAppropriation{}, common.CRCAppropriation, - b.chainParams.CRAssetsAddress, Fixed64(0), uint32(0), utxos, outputs...) + *CRAssetsAddress, Fixed64(0), uint32(0), utxos, outputs...) if err != nil { return nil, 0, err } @@ -501,7 +505,8 @@ func (b *BlockChain) CreateCRCAppropriationTransaction() (interfaces.Transaction func (b *BlockChain) CreateDposV2RealWithdrawTransaction( withdrawTransactionHashes []Uint256, outputs []*common.OutputInfo) (interfaces.Transaction, error) { - utxos, _, err := b.getUTXOsFromAddress(b.chainParams.DPoSV2RewardAccumulateAddress) + DPoSV2RewardAccumulateAddress, _ := Uint168FromAddress(b.chainParams.DPoSConfiguration.DPoSV2RewardAccumulateAddress) + utxos, _, err := b.getUTXOsFromAddress(*DPoSV2RewardAccumulateAddress) if err != nil { return nil, err } @@ -511,13 +516,13 @@ func (b *BlockChain) CreateDposV2RealWithdrawTransaction( } for _, v := range outputs { - v.Amount -= b.chainParams.RealWithdrawSingleFee + v.Amount -= b.chainParams.CRConfiguration.RealWithdrawSingleFee } - txFee := b.chainParams.RealWithdrawSingleFee * Fixed64(len(withdrawTransactionHashes)) + txFee := b.chainParams.CRConfiguration.RealWithdrawSingleFee * Fixed64(len(withdrawTransactionHashes)) var tx interfaces.Transaction tx, err = b.createTransaction(wPayload, common.DposV2ClaimRewardRealWithdraw, - b.chainParams.DPoSV2RewardAccumulateAddress, txFee, uint32(0), utxos, outputs...) + *DPoSV2RewardAccumulateAddress, txFee, uint32(0), utxos, outputs...) if err != nil { return nil, err } @@ -526,7 +531,8 @@ func (b *BlockChain) CreateDposV2RealWithdrawTransaction( func (b *BlockChain) CreateVotesRealWithdrawTransaction( returnVotesTXHashes []Uint256, outputs []*common.OutputInfo) (interfaces.Transaction, error) { - utxos, _, err := b.getUTXOsFromAddress(b.chainParams.StakePool) + StakePool, _ := Uint168FromAddress(b.chainParams.StakePool) + utxos, _, err := b.getUTXOsFromAddress(*StakePool) if err != nil { return nil, err } @@ -545,13 +551,13 @@ func (b *BlockChain) CreateVotesRealWithdrawTransaction( } for _, v := range outputs { - v.Amount -= b.chainParams.RealWithdrawSingleFee + v.Amount -= b.chainParams.CRConfiguration.RealWithdrawSingleFee } //todo fee - txFee := b.chainParams.RealWithdrawSingleFee * Fixed64(len(returnVotesTXHashes)) + txFee := b.chainParams.CRConfiguration.RealWithdrawSingleFee * Fixed64(len(returnVotesTXHashes)) var tx interfaces.Transaction tx, err = b.createTransaction(wPayload, common.VotesRealWithdraw, - b.chainParams.StakePool, txFee, uint32(0), utxos, outputs...) + *StakePool, txFee, uint32(0), utxos, outputs...) if err != nil { return nil, err } @@ -560,7 +566,8 @@ func (b *BlockChain) CreateVotesRealWithdrawTransaction( func (b *BlockChain) CreateCRRealWithdrawTransaction( withdrawTransactionHashes []Uint256, outputs []*common.OutputInfo) (interfaces.Transaction, error) { - utxos, _, err := b.getUTXOsFromAddress(b.chainParams.CRExpensesAddress) + CRExpensesAddress, _ := Uint168FromAddress(b.chainParams.CRConfiguration.CRExpensesAddress) + utxos, _, err := b.getUTXOsFromAddress(*CRExpensesAddress) if err != nil { return nil, err } @@ -570,12 +577,12 @@ func (b *BlockChain) CreateCRRealWithdrawTransaction( } for _, v := range outputs { - v.Amount -= b.chainParams.RealWithdrawSingleFee + v.Amount -= b.chainParams.CRConfiguration.RealWithdrawSingleFee } - txFee := b.chainParams.RealWithdrawSingleFee * Fixed64(len(withdrawTransactionHashes)) + txFee := b.chainParams.CRConfiguration.RealWithdrawSingleFee * Fixed64(len(withdrawTransactionHashes)) tx, err := b.createTransaction(wPayload, common.CRCProposalRealWithdraw, - b.chainParams.CRExpensesAddress, txFee, uint32(0), utxos, outputs...) + *CRExpensesAddress, txFee, uint32(0), utxos, outputs...) if err != nil { return nil, err } @@ -583,34 +590,35 @@ func (b *BlockChain) CreateCRRealWithdrawTransaction( } func (b *BlockChain) CreateCRAssetsRectifyTransaction() (interfaces.Transaction, error) { - utxos, _, err := b.getUTXOsFromAddress(b.chainParams.CRAssetsAddress) + CRAssetsAddress, _ := Uint168FromAddress(b.chainParams.CRConfiguration.CRAssetsAddress) + utxos, _, err := b.getUTXOsFromAddress(*CRAssetsAddress) if err != nil { return nil, err } - if len(utxos) < int(b.chainParams.MinCRAssetsAddressUTXOCount) { + if len(utxos) < int(b.chainParams.CRConfiguration.MinCRAssetsAddressUTXOCount) { return nil, errors.New("Available utxo is less than MinCRAssetsAddressUTXOCount") } - if len(utxos) > int(b.chainParams.MaxCRAssetsAddressUTXOCount) { - utxos = utxos[:b.chainParams.MaxCRAssetsAddressUTXOCount] + if len(utxos) > int(b.chainParams.CRConfiguration.MaxCRAssetsAddressUTXOCount) { + utxos = utxos[:b.chainParams.CRConfiguration.MaxCRAssetsAddressUTXOCount] } var crcFoundationBalance Fixed64 for i, u := range utxos { - if i >= int(b.chainParams.MaxCRAssetsAddressUTXOCount) { + if i >= int(b.chainParams.CRConfiguration.MaxCRAssetsAddressUTXOCount) { break } crcFoundationBalance += u.Value } - rectifyAmount := crcFoundationBalance - b.chainParams.RectifyTxFee + rectifyAmount := crcFoundationBalance - b.chainParams.CRConfiguration.RectifyTxFee log.Info("create CR assets rectify amount:", rectifyAmount) if rectifyAmount <= 0 { return nil, nil } - outputs := []*common.OutputInfo{{b.chainParams.CRAssetsAddress, + outputs := []*common.OutputInfo{{*CRAssetsAddress, rectifyAmount}} tx, err := b.createTransaction(&payload.CRAssetsRectify{}, common.CRAssetsRectify, - b.chainParams.CRAssetsAddress, b.chainParams.RectifyTxFee, uint32(0), utxos, outputs...) + *CRAssetsAddress, b.chainParams.CRConfiguration.RectifyTxFee, uint32(0), utxos, outputs...) if err != nil { return nil, err } @@ -659,6 +667,19 @@ func (b *BlockChain) SetCRCommittee(c *crstate.Committee) { b.crCommittee = c } +func (b *BlockChain) GetBlock(height uint32) (*Block, error) { + hash, err := b.GetBlockHash(height) + if err != nil { + return nil, err + } + block, err := b.db.GetFFLDB().GetBlock(hash) + if err != nil { + return nil, err + } + CalculateTxsFee(block.Block) + return block.Block, nil +} + func (b *BlockChain) GetBestBlockHash() *Uint256 { b.IndexLock.RLock() defer b.IndexLock.RUnlock() @@ -1298,7 +1319,7 @@ func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error // roll back state about the last block before disconnect if block.Height-1 >= b.chainParams.VoteStartHeight { - err = b.chainParams.CkpManager.OnRollbackTo( + err = b.CkpManager.OnRollbackTo( block.Height-1, b.state.ConsensusAlgorithm == state.POW) if err != nil { return err @@ -1326,7 +1347,7 @@ func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error } // update state after connected block - b.chainParams.CkpManager.OnBlockSaved(&DposBlock{ + b.CkpManager.OnBlockSaved(&DposBlock{ Block: block, HaveConfirm: confirm != nil, Confirm: confirm, @@ -1338,8 +1359,8 @@ func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error return nil } -//// disconnectBlock handles disconnecting the passed node/block from the end of -//// the main (best) chain. +// // disconnectBlock handles disconnecting the passed node/block from the end of +// // the main (best) chain. func (b *BlockChain) disconnectBlock(node *BlockNode, block *Block, confirm *payload.Confirm) error { // Make sure the node being disconnected is the end of the best chain. if b.BestChain == nil || !node.Hash.IsEqual(*b.BestChain.Hash) { @@ -1399,7 +1420,7 @@ func (b *BlockChain) connectBlock(node *BlockNode, block *Block, confirm *payloa if block.Height >= b.chainParams.CRCOnlyDPOSHeight && !revertToPOW && b.state.ConsensusAlgorithm != state.POW && confirm != nil { if err := checkBlockWithConfirmation(block, confirm, - b.chainParams.CkpManager, b.state.ConsensusAlgorithm == state.POW); err != nil { + b.CkpManager, b.state.ConsensusAlgorithm == state.POW); err != nil { return fmt.Errorf("block confirmation validate failed: %s", err) } } @@ -1536,7 +1557,7 @@ func (b *BlockChain) maybeAcceptBlock(block *Block, confirm *payload.Confirm) (b } if inMainChain && !reorganized { - b.chainParams.CkpManager.OnBlockSaved(&DposBlock{ + b.CkpManager.OnBlockSaved(&DposBlock{ Block: block, HaveConfirm: confirm != nil, Confirm: confirm, @@ -1697,10 +1718,10 @@ func (b *BlockChain) ReorganizeChain(block *Block) error { return nil } -//(bool, bool, error) -//1. inMainChain -//2. isOphan -//3. error +// (bool, bool, error) +// 1. inMainChain +// 2. isOphan +// 3. error func (b *BlockChain) processBlock(block *Block, confirm *payload.Confirm) (bool, bool, error) { blockHash := block.Hash() @@ -1989,11 +2010,11 @@ func (b *BlockChain) locateBlocks(startHash *Uint256, stopHash *Uint256, maxBloc // // In addition, there are two special cases: // -// - When no locators are provided, the stop hash is treated as a request for -// that block, so it will either return the stop hash itself if it is known, -// or nil if it is unknown -// - When locators are provided, but none of them are known, hashes starting -// after the genesis block will be returned +// - When no locators are provided, the stop hash is treated as a request for +// that block, so it will either return the stop hash itself if it is known, +// or nil if it is unknown +// - When locators are provided, but none of them are known, hashes starting +// after the genesis block will be returned // // This function is safe for concurrent access. func (b *BlockChain) LocateBlocks(locator []*Uint256, hashStop *Uint256, maxHashes uint32) []*Uint256 { diff --git a/blockchain/blockindex.go b/blockchain/blockindex.go index 74c11b518..8ef13b728 100644 --- a/blockchain/blockindex.go +++ b/blockchain/blockindex.go @@ -12,12 +12,12 @@ package blockchain import ( - common2 "github.com/elastos/Elastos.ELA/core/types/common" "math/big" "sync" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/database" ) @@ -115,7 +115,7 @@ type blockIndex struct { // be changed afterwards, so there is no need to protect them with a // separate mutex. db IChainStore - chainParams *config.Params + chainParams *config.Configuration sync.RWMutex index map[common.Uint256]*BlockNode @@ -125,7 +125,7 @@ type blockIndex struct { // newBlockIndex returns a new empty instance of a block index. The index will // be dynamically populated as block nodes are loaded from the database and // manually added. -func newBlockIndex(db IChainStore, chainParams *config.Params) *blockIndex { +func newBlockIndex(db IChainStore, chainParams *config.Configuration) *blockIndex { return &blockIndex{ db: db, chainParams: chainParams, diff --git a/blockchain/blockvalidator.go b/blockchain/blockvalidator.go index 1e0a11fd1..6a687712b 100644 --- a/blockchain/blockvalidator.go +++ b/blockchain/blockvalidator.go @@ -15,8 +15,10 @@ import ( . "github.com/elastos/Elastos.ELA/auxpow" . "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" . "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" @@ -37,7 +39,7 @@ func (b *BlockChain) CheckBlockSanity(block *Block) error { if !header.AuxPow.Check(&hash, AuxPowChainID) { return errors.New("[PowCheckBlockSanity] block check aux pow failed") } - if CheckProofOfWork(&header, b.chainParams.PowLimit) != nil { + if CheckProofOfWork(&header, b.chainParams.PowConfiguration.PowLimit) != nil { return errors.New("[PowCheckBlockSanity] block check proof of work failed") } @@ -253,6 +255,7 @@ func (b *BlockChain) checkTxsContext(block *Block) error { var totalTxFee = Fixed64(0) var proposalsUsedAmount Fixed64 + ELAAssetID, _ := common2.Uint256FromHexString(core.ELAAssetID) for i := 1; i < len(block.Transactions); i++ { references, errCode := b.CheckTransactionContext(block.Height, block.Transactions[i], proposalsUsedAmount, block.Timestamp) @@ -262,7 +265,7 @@ func (b *BlockChain) checkTxsContext(block *Block) error { } // Calculate transaction fee - totalTxFee += GetTxFee(block.Transactions[i], config.ELAAssetID, references) + totalTxFee += GetTxFee(block.Transactions[i], *ELAAssetID, references) if block.Transactions[i].IsCRCProposalTx() { RecordCRCProposalAmount(&proposalsUsedAmount, block.Transactions[i]) } @@ -463,17 +466,20 @@ func (b *BlockChain) checkCoinbaseTransactionContext(blockHeight uint32, coinbas } if b.state.GetConsensusAlgorithm() == state.POW { - if !coinbase.Outputs()[2].ProgramHash.IsEqual(b.chainParams.DestroyELAAddress) { + DestroyELAAddress, _ := common2.Uint168FromAddress(b.chainParams.DestroyELAAddress) + if !coinbase.Outputs()[2].ProgramHash.IsEqual(*DestroyELAAddress) { return errors.New("DPoS reward address not correct") } - if !coinbase.Outputs()[0].ProgramHash.IsEqual(b.chainParams.DestroyELAAddress) { + if !coinbase.Outputs()[0].ProgramHash.IsEqual(*DestroyELAAddress) { return errors.New("rewardCyberRepublic address not correct") } } else { - if !coinbase.Outputs()[0].ProgramHash.IsEqual(b.chainParams.CRAssetsAddress) { + CRAssetsAddress, _ := common2.Uint168FromAddress(b.chainParams.CRConfiguration.CRAssetsAddress) + DPoSV2RewardAccumulateAddress, _ := common2.Uint168FromAddress(b.chainParams.DPoSConfiguration.DPoSV2RewardAccumulateAddress) + if !coinbase.Outputs()[0].ProgramHash.IsEqual(*CRAssetsAddress) { return errors.New("rewardCyberRepublic address not correct") } - if !coinbase.Outputs()[2].ProgramHash.IsEqual(b.chainParams.DPoSV2RewardAccumulateAddress) { + if !coinbase.Outputs()[2].ProgramHash.IsEqual(*DPoSV2RewardAccumulateAddress) { return errors.New("DPoS reward address not correct") } } diff --git a/blockchain/chainio.go b/blockchain/chainio.go index 66c3422bc..f3c84101b 100644 --- a/blockchain/chainio.go +++ b/blockchain/chainio.go @@ -21,6 +21,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/database" @@ -332,7 +333,7 @@ func DBRemoveData(dbTx database.Tx, bucketName, key []byte) error { func (b *BlockChain) createChainState() error { // Create a new node from the genesis block and set it as the best node. - genesisBlock := b.chainParams.GenesisBlock + genesisBlock := core.GenesisBlock(b.chainParams.FoundationAddress) header := &genesisBlock.Header hash := genesisBlock.Hash() @@ -479,7 +480,7 @@ func (b *BlockChain) initChainState() error { return err } curHash := header.Hash() - if lastNode == nil && !curHash.IsEqual(b.chainParams.GenesisBlock.Hash()) { + if lastNode == nil && !curHash.IsEqual(core.GenesisBlock(b.chainParams.FoundationAddress).Hash()) { return fmt.Errorf("initChainState: Expected "+ "first entry in block index to be genesis block, "+ "found %s", curHash) diff --git a/blockchain/chainstore.go b/blockchain/chainstore.go index 2a5ab9ca4..1c64c30d4 100644 --- a/blockchain/chainstore.go +++ b/blockchain/chainstore.go @@ -9,7 +9,6 @@ import ( "bytes" "encoding/hex" "errors" - "github.com/elastos/Elastos.ELA/database" "path/filepath" "sync" "sync/atomic" @@ -23,6 +22,7 @@ import ( "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" + "github.com/elastos/Elastos.ELA/database" _ "github.com/elastos/Elastos.ELA/database/ffldb" ) @@ -43,7 +43,7 @@ type ChainStore struct { persistMutex sync.Mutex } -func NewChainStore(dataDir string, params *config.Params) (IChainStore, error) { +func NewChainStore(dataDir string, params *config.Configuration) (IChainStore, error) { db, err := NewLevelDB(filepath.Join(dataDir, "chain")) if err != nil { return nil, err diff --git a/blockchain/chainstoreffldb.go b/blockchain/chainstoreffldb.go index 1e382474e..66cbe4604 100644 --- a/blockchain/chainstoreffldb.go +++ b/blockchain/chainstoreffldb.go @@ -44,10 +44,10 @@ type ChainStoreFFLDB struct { mtx sync.RWMutex blockHashesCache []Uint256 blocksCache map[Uint256]*DposBlock - params *config.Params + params *config.Configuration } -func NewChainStoreFFLDB(dataDir string, params *config.Params) (IFFLDBChainStore, error) { +func NewChainStoreFFLDB(dataDir string, params *config.Configuration) (IFFLDBChainStore, error) { fflDB, err := LoadBlockDB(dataDir, blockDbName) if err != nil { return nil, err diff --git a/blockchain/confirmvalidator.go b/blockchain/confirmvalidator.go index 8fdff1794..db5a54924 100644 --- a/blockchain/confirmvalidator.go +++ b/blockchain/confirmvalidator.go @@ -9,6 +9,7 @@ import ( "bytes" "encoding/hex" "errors" + "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/checkpoint" diff --git a/blockchain/difficulty.go b/blockchain/difficulty.go index 1e96eb49f..619d88b07 100644 --- a/blockchain/difficulty.go +++ b/blockchain/difficulty.go @@ -56,7 +56,7 @@ func (b *BlockChain) GetNetworkHashPS() *big.Int { } func (b *BlockChain) CalcCurrentDifficulty(currentBits uint32) string { - targetGenesisBlockBig := CompactToBig(b.chainParams.PowLimitBits) + targetGenesisBlockBig := CompactToBig(b.chainParams.PowConfiguration.PowLimitBits) targetCurrentBig := CompactToBig(currentBits) return new(big.Int).Div(targetGenesisBlockBig, targetCurrentBig).String() } @@ -64,8 +64,8 @@ func (b *BlockChain) CalcCurrentDifficulty(currentBits uint32) string { func (b *BlockChain) CalcNextRequiredDifficulty(prevNode *BlockNode, newBlockTime time.Time) (uint32, error) { // 1. Genesis block. // 2. when we want to generate block instantly, don't change difficulty - if (prevNode.Height == 0) || (b.chainParams.PowLimitBits == 0x207fffff) { - return uint32(b.chainParams.PowLimitBits), nil + if (prevNode.Height == 0) || (b.chainParams.PowConfiguration.PowLimitBits == 0x207fffff) { + return uint32(b.chainParams.PowConfiguration.PowLimitBits), nil } // Return the previous block's difficulty requirements if this block @@ -102,12 +102,12 @@ func (b *BlockChain) CalcNextRequiredDifficulty(prevNode *BlockNode, newBlockTim // result. oldTarget := CompactToBig(prevNode.Bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) - targetTimeSpan := int64(b.chainParams.TargetTimespan / time.Second) + targetTimeSpan := int64(b.chainParams.PowConfiguration.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. - if newTarget.Cmp(b.chainParams.PowLimit) > 0 { - newTarget.Set(b.chainParams.PowLimit) + if newTarget.Cmp(b.chainParams.PowConfiguration.PowLimit) > 0 { + newTarget.Set(b.chainParams.PowConfiguration.PowLimit) } // Log new target difficulty and return it. The new target logging is @@ -121,7 +121,7 @@ func (b *BlockChain) CalcNextRequiredDifficulty(prevNode *BlockNode, newBlockTim log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, - b.chainParams.TargetTimespan) + b.chainParams.PowConfiguration.TargetTimespan) return newTargetBits, nil } diff --git a/blockchain/difficulty_test.go b/blockchain/difficulty_test.go index 5818b0f35..dde140206 100644 --- a/blockchain/difficulty_test.go +++ b/blockchain/difficulty_test.go @@ -6,11 +6,11 @@ package blockchain import ( - common2 "github.com/elastos/Elastos.ELA/core/types/common" "math/big" "testing" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/stretchr/testify/assert" ) diff --git a/blockchain/indexers/manager.go b/blockchain/indexers/manager.go index f5f2f3c8c..3fc5fc1ad 100644 --- a/blockchain/indexers/manager.go +++ b/blockchain/indexers/manager.go @@ -520,7 +520,7 @@ func (m *Manager) IsSideChainReturnDepositExist(txHash *common.Uint256) bool { // // The manager returned satisfies the blockchain.IndexManager interface and thus // cleanly plugs into the normal blockchain processing path. -func NewManager(db database.DB, params *config.Params) *Manager { +func NewManager(db database.DB, params *config.Configuration) *Manager { txIndex := NewTxIndex(db) unspentIndex := NewUnspentIndex(db, params) utxoIndex := NewUtxoIndex(db, unspentIndex) diff --git a/blockchain/indexers/returndepositindex.go b/blockchain/indexers/returndepositindex.go index 131fc63df..64246a8e7 100644 --- a/blockchain/indexers/returndepositindex.go +++ b/blockchain/indexers/returndepositindex.go @@ -2,6 +2,7 @@ package indexers import ( "bytes" + "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" diff --git a/blockchain/indexers/txcache.go b/blockchain/indexers/txcache.go index 49f65a9ff..6a3eac353 100644 --- a/blockchain/indexers/txcache.go +++ b/blockchain/indexers/txcache.go @@ -6,12 +6,12 @@ package indexers import ( - "github.com/elastos/Elastos.ELA/core/types/functions" "io" "sync" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" ) @@ -58,7 +58,7 @@ type TxCache struct { txns map[common.Uint256]*TxInfo sync.RWMutex - params *config.Params + params *config.Configuration } func (t *TxCache) Serialize(w io.Writer) (err error) { @@ -99,8 +99,7 @@ func (t *TxCache) Deserialize(r io.Reader) (err error) { } func (t *TxCache) setTxn(height uint32, txn interfaces.Transaction) { - if t.params.NodeProfileStrategy == - config.MemoryFirst.String() { + if t.params.MemoryFirst { return } @@ -117,8 +116,7 @@ func (t *TxCache) setTxn(height uint32, txn interfaces.Transaction) { } func (t *TxCache) deleteTxn(hash common.Uint256) { - if t.params.NodeProfileStrategy == - config.MemoryFirst.String() { + if t.params.MemoryFirst { return } @@ -135,8 +133,7 @@ func (t *TxCache) GetTxn(hash common.Uint256) *TxInfo { } func (t *TxCache) trim() { - if t.params.NodeProfileStrategy == - config.MemoryFirst.String() { + if t.params.MemoryFirst { return } @@ -156,7 +153,7 @@ func (t *TxCache) trim() { } } -func NewTxCache(params *config.Params) *TxCache { +func NewTxCache(params *config.Configuration) *TxCache { return &TxCache{ txns: make(map[common.Uint256]*TxInfo), params: params, diff --git a/blockchain/indexers/txindex.go b/blockchain/indexers/txindex.go index 8fff2bbb6..0025fccae 100644 --- a/blockchain/indexers/txindex.go +++ b/blockchain/indexers/txindex.go @@ -14,6 +14,7 @@ import ( "bytes" "errors" "fmt" + "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/types" diff --git a/blockchain/indexers/unspentindex.go b/blockchain/indexers/unspentindex.go index 5804774e7..83b059ef7 100644 --- a/blockchain/indexers/unspentindex.go +++ b/blockchain/indexers/unspentindex.go @@ -9,11 +9,11 @@ import ( "errors" "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" - "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/types" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/database" ) @@ -287,14 +287,10 @@ func dbFetchHeightByHash(dbTx database.Tx, hash *common.Uint256) (uint32, error) // It implements the Indexer interface which plugs into the IndexManager that in // turn is used by the blockchain package. This allows the index to be // seamlessly maintained along with the chain. -func NewUnspentIndex(db database.DB, params *config.Params) *UnspentIndex { +func NewUnspentIndex(db database.DB, params *config.Configuration) *UnspentIndex { unspentIndex := &UnspentIndex{ DB: db, TxCache: NewTxCache(params), } - //if params.NodeProfileStrategy != - // config.MemoryFirst.String() { - // params.CkpManager.Register(NewCheckpoint(unspentIndex)) - //} return unspentIndex } diff --git a/blockchain/indexers/utxoindex.go b/blockchain/indexers/utxoindex.go index e24496ca7..41a0175e4 100644 --- a/blockchain/indexers/utxoindex.go +++ b/blockchain/indexers/utxoindex.go @@ -7,6 +7,7 @@ package indexers import ( "bytes" + "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" diff --git a/blockchain/ledger.go b/blockchain/ledger.go index ceffd4c91..fa8c29632 100644 --- a/blockchain/ledger.go +++ b/blockchain/ledger.go @@ -29,12 +29,24 @@ type Ledger struct { Committee *crstate.Committee } -//check weather the transaction contains the doubleSpend. +func (l *Ledger) GetAmount(programHash Uint168) (Fixed64, error) { + amount := Fixed64(0) + utxos, err := l.Store.GetFFLDB().GetUTXO(&programHash) + if err != nil { + return amount, err + } + for _, utxo := range utxos { + amount += utxo.Value + } + return amount, nil +} + +// check weather the transaction contains the doubleSpend. func (l *Ledger) IsDoubleSpend(Tx interfaces.Transaction) bool { return DefaultLedger.Store.IsDoubleSpend(Tx) } -//Get Block With Height. +// Get Block With Height. func (l *Ledger) GetBlockWithHeight(height uint32) (*Block, error) { temp, err := l.Blockchain.GetBlockHash(height) if err != nil { @@ -47,7 +59,7 @@ func (l *Ledger) GetBlockWithHeight(height uint32) (*Block, error) { return bk.Block, nil } -//Get block with block hash. +// Get block with block hash. func (l *Ledger) GetBlockWithHash(hash Uint256) (*Block, error) { bk, err := l.Store.GetFFLDB().GetBlock(hash) if err != nil { @@ -56,7 +68,7 @@ func (l *Ledger) GetBlockWithHash(hash Uint256) (*Block, error) { return bk.Block, nil } -//Get transaction with hash. +// Get transaction with hash. func (l *Ledger) GetTransactionWithHash(hash Uint256) (interfaces.Transaction, error) { tx, _, err := l.Store.GetTransaction(hash) if err != nil { @@ -65,18 +77,18 @@ func (l *Ledger) GetTransactionWithHash(hash Uint256) (interfaces.Transaction, e return tx, nil } -//Get local block chain height. +// Get local block chain height. func (l *Ledger) GetLocalBlockChainHeight() uint32 { return l.Blockchain.GetHeight() } -//Get blocks and confirms by given height range, if end equals zero will be treat as current highest block height +// Get blocks and confirms by given height range, if end equals zero will be treat as current highest block height func (l *Ledger) GetDposBlocks(start, end uint32) ([]*DposBlock, error) { //todo complete me return nil, nil } -//Append blocks and confirms directly +// Append blocks and confirms directly func (l *Ledger) AppendDposBlocks(confirms []*DposBlock) error { //todo complete me return nil diff --git a/blockchain/txvalidator.go b/blockchain/txvalidator.go index 45d932eda..90e579b11 100644 --- a/blockchain/txvalidator.go +++ b/blockchain/txvalidator.go @@ -13,6 +13,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" common2 "github.com/elastos/Elastos.ELA/core/types/common" @@ -297,7 +298,7 @@ func (b *BlockChain) checkVoteCRContent(blockHeight uint32, if payloadVersion < outputpayload.VoteProducerAndCRVersion { return errors.New("payload VoteProducerVersion not support vote CR") } - if blockHeight >= b.chainParams.CheckVoteCRCountHeight { + if blockHeight >= b.chainParams.CRConfiguration.CheckVoteCRCountHeight { if len(content.CandidateVotes) > outputpayload.MaxVoteProducersPerTransaction { return errors.New("invalid count of CR candidates ") } @@ -359,15 +360,16 @@ func getCRMembersMap(members []*crstate.CRMember) map[string]struct{} { } func CheckDestructionAddress(references map[*common2.Input]common2.Output) error { + DestroyELAAddress, _ := common.Uint168FromAddress(config.DestroyELAAddress) for _, output := range references { - if output.ProgramHash == config.DestroyELAAddress { + if output.ProgramHash == *DestroyELAAddress { return errors.New("cannot use utxo from the destruction address") } } return nil } -//validate the transaction of duplicate UTXO input +// validate the transaction of duplicate UTXO input func CheckTransactionInput(txn interfaces.Transaction) error { if txn.IsCoinBaseTx() { if len(txn.Inputs()) != 1 { @@ -426,9 +428,10 @@ func (b *BlockChain) CheckTransactionOutput(txn interfaces.Transaction, foundationReward := txn.Outputs()[0].Value var totalReward = common.Fixed64(0) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) if blockHeight < b.chainParams.PublicDPOSHeight { for _, output := range txn.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in coinbase is invalid") } totalReward += output.Value @@ -461,14 +464,16 @@ func (b *BlockChain) CheckTransactionOutput(txn interfaces.Transaction, } if txn.IsCRCAppropriationTx() { + CRAssetsAddress, _ := common.Uint168FromAddress(b.chainParams.CRConfiguration.CRAssetsAddress) + CRExpensesAddress, _ := common.Uint168FromAddress(b.chainParams.CRConfiguration.CRExpensesAddress) if len(txn.Outputs()) != 2 { return errors.New("new CRCAppropriation tx must have two output") } - if !txn.Outputs()[0].ProgramHash.IsEqual(b.chainParams.CRExpensesAddress) { + if !txn.Outputs()[0].ProgramHash.IsEqual(*CRExpensesAddress) { return errors.New("new CRCAppropriation tx must have the first" + "output to CR expenses address") } - if !txn.Outputs()[1].ProgramHash.IsEqual(b.chainParams.CRAssetsAddress) { + if !txn.Outputs()[1].ProgramHash.IsEqual(*CRAssetsAddress) { return errors.New("new CRCAppropriation tx must have the second" + "output to CR assets address") } @@ -493,8 +498,9 @@ func (b *BlockChain) CheckTransactionOutput(txn interfaces.Transaction, // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range txn.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } @@ -530,15 +536,17 @@ func (b *BlockChain) CheckTransactionOutput(txn interfaces.Transaction, func CheckOutputProgramHash(height uint32, programHash common.Uint168) error { // main version >= 88812 + CRAssetsAddress, _ := common.Uint168FromAddress(config.CRAssetsAddress) + CRCExpensesAddress, _ := common.Uint168FromAddress(config.CRCExpensesAddress) if height >= config.DefaultParams.CheckAddressHeight { var empty = common.Uint168{} if programHash.IsEqual(empty) { return nil } - if programHash.IsEqual(config.CRAssetsAddress) { + if programHash.IsEqual(*CRAssetsAddress) { return nil } - if programHash.IsEqual(config.CRCExpensesAddress) { + if programHash.IsEqual(*CRCExpensesAddress) { return nil } @@ -548,6 +556,7 @@ func CheckOutputProgramHash(height uint32, programHash common.Uint168) error { case contract.PrefixMultiSig: case contract.PrefixCrossChain: case contract.PrefixDeposit: + case contract.PrefixDPoSV2: default: return errors.New("invalid program hash prefix") } @@ -650,7 +659,7 @@ func CheckTransactionSize(txn interfaces.Transaction) error { func CheckAssetPrecision(txn interfaces.Transaction) error { for _, output := range txn.Outputs() { - if !CheckAmountPrecise(output.Value, config.ELAPrecision) { + if !CheckAmountPrecise(output.Value, core.ELAPrecision) { return errors.New("the precision of asset is incorrect") } } diff --git a/blockchain/utxocache.go b/blockchain/utxocache.go index cf8f6669d..8301809f9 100644 --- a/blockchain/utxocache.go +++ b/blockchain/utxocache.go @@ -128,8 +128,8 @@ func (up *UTXOCache) CleanCache() { up.TxCache = make(map[common.Uint256]interfaces.Transaction) } -func NewUTXOCache(db IUTXOCacheStore, params *config.Params) *UTXOCache { - if params.NodeProfileStrategy == config.MemoryFirst.String() { +func NewUTXOCache(db IUTXOCacheStore, params *config.Configuration) *UTXOCache { + if params.MemoryFirst { MaxReferenceSize = memoryFirstReferenceSize } diff --git a/cmd/common/common.go b/cmd/common/common.go index ea83ace7a..d84ccdb15 100644 --- a/cmd/common/common.go +++ b/cmd/common/common.go @@ -17,11 +17,6 @@ import ( "github.com/urfave/cli" ) -const ( - defaultConfigPath = "./config.json" - defaultDataDir = "elastos" -) - var ( rpcUrl = "" rpcIp = "127.0.0.1" diff --git a/cmd/common/flags.go b/cmd/common/flags.go index 36f9644fa..70829d938 100644 --- a/cmd/common/flags.go +++ b/cmd/common/flags.go @@ -9,6 +9,7 @@ import ( "errors" "github.com/elastos/Elastos.ELA/account" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/utils" "github.com/urfave/cli" @@ -315,251 +316,35 @@ var ( TestNetFlag = cli.StringFlag{ Name: "testnet", Usage: "specify network type to test net", - Value: defaultConfigPath, + Value: config.ConfigFile, } RegTestFlag = cli.StringFlag{ Name: "regtest", Usage: "specify network type to reg test net", - Value: defaultConfigPath, + Value: config.ConfigFile, } ConfigFileFlag = cli.StringFlag{ Name: "conf", Usage: "config `` path, ", - Value: defaultConfigPath, + Value: config.ConfigFile, } DataDirFlag = cli.StringFlag{ Name: "datadir", Usage: "block data and logs storage ``", - Value: defaultDataDir, - } - MagicFlag = cli.StringFlag{ - Name: "magic", - Usage: "magic number for node to initialize p2p connection", - } - PrintLevelFlag = cli.StringFlag{ - Name: "printlevel", - Usage: "level to print log", + Value: config.DataDir, } EnableDnsFlag = cli.StringFlag{ Name: "dnsseed", Usage: "enable dns seeds for node to initialize p2p connection", } - DnsSeedFlag = cli.StringFlag{ - Name: "dns", - Usage: "dns seeds for node to initialize p2p connection", - } PeersFlag = cli.StringFlag{ Name: "peers", Usage: "peers seeds for node to initialize p2p connection", } - PortFlag = cli.StringFlag{ - Name: "port", - Usage: "default peer-to-peer port for the network", - } - InfoPortFlag = cli.StringFlag{ - Name: "infoport", - Usage: "port for the http info server", - } - RestPortFlag = cli.StringFlag{ - Name: "restport", - Usage: "port for the http restful server", - } - WsPortFlag = cli.StringFlag{ - Name: "wsport", - Usage: "port for the http web socket server", - } InstantBlockFlag = cli.StringFlag{ Name: "instant", Usage: "specify if need to generate instant block", } - FoundationAddrFlag = cli.StringFlag{ - Name: "foundation", - Usage: "specify the foundation address", - } - DIDSideChainAddressFlag = cli.StringFlag{ - Name: "didsidechainaddress", - Usage: "specify the did sidechain address", - } - PayToAddrFlag = cli.StringFlag{ - Name: "paytoaddr", - Usage: "specify the miner reward address", - } - AutoMiningFlag = cli.StringFlag{ - Name: "automining", - Usage: "specify if should open auto mining", - } - MinTxFeeFlag = cli.StringFlag{ - Name: "mintxfee", - Usage: "specify minimum transaction fee", - } - VoteStartHeightFlag = cli.StringFlag{ - Name: "votestartheight", - Usage: "indicates the height of starting register producer and " + - "vote related", - } - CheckAddressHeightFlag = cli.StringFlag{ - Name: "checkaddressheight", - Usage: "defines the height begin to check output hash", - } - CheckRewardHeightFlag = cli.StringFlag{ - Name: "checkrewardheight", - Usage: "defines the height begin to check reward", - } - EnableArbiterFlag = cli.StringFlag{ - Name: "arbiter", - Usage: "indicates where or not to enable DPoS arbiter switch", - } - CRCOnlyDPOSHeightFlag = cli.StringFlag{ - Name: "crconlydposheight", - Usage: "(H1) indicates the height of DPOS consensus begins with only " + - "CRC producers participate in producing block", - } - PublicDPOSHeightFlag = cli.StringFlag{ - Name: "publicdposheight", - Usage: "(H2) indicates the height when public registered and elected " + - "producers participate in DPOS consensus", - } - IllegalPenaltyFlag = cli.StringFlag{ - Name: "illegalpenalty", - Usage: "defines the num of illegal penalty should be punished ", - } - DPoSV2IllegalPenaltyFlag = cli.StringFlag{ - Name: "dposv2illegalpenalty", - Usage: "defines the num of illegal penalty should be punished ", - } - CRCommitteeStartHeightFlag = cli.StringFlag{ - Name: "crcommitteestartheight", - Usage: "defines the height of CR Committee started", - } - CRClaimDPOSNodeStartHeightFlag = cli.StringFlag{ - Name: "crclaimdposnodestartheight", - Usage: "defines the height of CR claim DPOS node started", - } - CRClaimDPOSNodePeriodFlag = cli.StringFlag{ - Name: "crclaimdposnodeperiod", - Usage: "defines the period of CR claim DPOS node", - } - CRVotingStartHeightFlag = cli.StringFlag{ - Name: "crvotingstartheight", - Usage: "defines the height of CR voting started", - } - MaxCommitteeProposalCount = cli.StringFlag{ - Name: "maxcommitteeproposalcount", - Usage: "defines max count of the proposal that one cr can proposal", - } - MaxNodePerHost = cli.StringFlag{ - Name: "maxnodeperhost", - Usage: "defines max nodes that one host can establish", - } - VoteStatisticsHeightFlag = cli.StringFlag{ - Name: "votestatisticsheight", - Usage: "defines the height to fix vote statistics error", - } - EnableActivateIllegalHeightFlag = cli.StringFlag{ - Name: "enableactivateillegalheight", - Usage: "defines the start height to enable activate illegal producer" + - " though activate tx", - } - DPoSMagicFlag = cli.StringFlag{ - Name: "dposmagic", - Usage: "defines the magic number used in the DPoS network", - } - DPoSIPAddressFlag = cli.StringFlag{ - Name: "dposipaddress", - Usage: "defines the default IP address for the DPoS network", - } - DPoSPortFlag = cli.StringFlag{ - Name: "dposport", - Usage: "defines the default port for the DPoS network", - } - SecretaryGeneralFlag = cli.StringFlag{ - Name: "secretarygeneral", - Usage: "defines the secretary general of CR", - } - MaxProposalTrackingCountFlag = cli.StringFlag{ - Name: "maxproposaltrackingcount", - Usage: "defines the max count of CRC proposal tracking", - } - OriginArbitersFlag = cli.StringFlag{ - Name: "originarbiters", - Usage: "defines origin arbiters", - } - CRCArbitersFlag = cli.StringFlag{ - Name: "crcarbiters", - Usage: "defines crc arbiters", - } - PreConnectOffsetFlag = cli.StringFlag{ - Name: "preconnectoffset", - Usage: "defines the offset blocks to pre-connect to the block producers", - } - NormalArbitratorsCountFlag = cli.StringFlag{ - Name: "normalarbitratorscount", - Usage: "defines the number of general(no-CRC) arbiters", - } - CandidatesCountFlag = cli.StringFlag{ - Name: "candidatescount", - Usage: "defines the number of needed candidate arbiters", - } - MaxInactiveRoundsFlag = cli.StringFlag{ - Name: "maxinactiverounds", - Usage: "defines the maximum inactive rounds before producer takes penalty", - } - InactivePenaltyFlag = cli.StringFlag{ - Name: "inactivepenalty", - Usage: "defines penalty of inactive", - } - EmergencyInactivePenaltyFlag = cli.StringFlag{ - Name: "emergencyinactivepenalty", - Usage: "defines penalty of emergency inactive", - } - DPoSV2DepositCoinMinLockTimeFlag = cli.StringFlag{ - Name: "dposv2depositcoinminlocktime", - Usage: "minimum lock time of DPoS V2 deposit coin", - } - DPoSV2MinVotesLockTimeFlag = cli.StringFlag{ - Name: "dposv2minvoteslocktime", - Usage: "minimum lock time of DPoS V2 votes", - } - DPoSV2MaxVotesLockTimeFlag = cli.StringFlag{ - Name: "dposv2maxvoteslocktime", - Usage: "max lock time of DPoS V2 votes", - } - CRMemberCountFlag = cli.StringFlag{ - Name: "crmembercount", - Usage: "defines the number of CR committee members", - } - CRDutyPeriodFlag = cli.StringFlag{ - Name: "crdutyperiod", - Usage: "defines the duration of a normal duty period which measured " + - "by block height", - } - CRDepositLockupBlocksFlag = cli.StringFlag{ - Name: "crdepositlockupblocks", - Usage: "DepositLockupBlocks indicates how many blocks need to wait when cancel", - } - CRVotingPeriodFlag = cli.StringFlag{ - Name: "crvotingperiod", - Usage: "defines the duration of voting period which measured by " + - "block height", - } - ProposalCRVotingPeriodFlag = cli.StringFlag{ - Name: "proposalcrvotingperiod", - Usage: "defines the duration of CR voting about a proposal", - } - ProposalPublicVotingPeriodFlag = cli.StringFlag{ - Name: "proposalpublicvotingperiod", - Usage: "defines the duration of all voters send reject vote about " + - "a proposal", - } - CRAgreementCountFlag = cli.StringFlag{ - Name: "cragreementcount", - Usage: "defines minimum count to let a registered proposal transfer " + - "to CRAgreed state", - } - VoterRejectPercentageFlag = cli.StringFlag{ - Name: "voterrejectpercentage", - Usage: "defines percentage about voters reject a proposal", - } CRCProposalHashFlag = cli.StringFlag{ Name: "proposalhash", Usage: "the `` of the transaction", @@ -572,199 +357,16 @@ var ( Name: "crccommiteeaddr", Usage: "the ``", } - CRCAppropriatePercentageFlag = cli.StringFlag{ - Name: "crcappropriatepercentage", - Usage: "defines percentage about CRC appropriation", - } - CRAssetsAddressFlag = cli.StringFlag{ - Name: "crassetsaddress", - Usage: "defines foundation address of CRC", - } - CRExpensesAddressFlag = cli.StringFlag{ - Name: "crexpensesaddress", - Usage: "defines appropriation address of CRC committee", - } - RegisterCRByDIDHeightFlag = cli.StringFlag{ - Name: "registercrbydidheight", - Usage: "defines the height to support register CR by CID", - } - ProhibitTransferToDIDHeightFlag = cli.StringFlag{ - Name: "prohibittransfertodidheight", - Usage: "defines the height to prohibit transfer to did", - } - MaxCRAssetsAddressUTXOCount = cli.StringFlag{ - Name: "maxcrassetsaddressutxocount", - Usage: "defines the maximum number of utxo cr assets address can have ", - } - MinCRAssetsAddressUTXOCount = cli.StringFlag{ - Name: "mincrassetsaddressutxocount", - Usage: "defines the minimum number of utxo cr assets address can rectify", - } - CRAssetsRectifyTransactionHeight = cli.StringFlag{ - Name: "crassetsrectifytransactionheight", - Usage: "defines the cr rectify transaction start height", - } - CRCProposalWithdrawPayloadV1Height = cli.StringFlag{ - Name: "crcproposalwithdrawpayloadv1height", - Usage: "defines the crc withdraw proposal payload type v1 accept height", - } - CRCProposalV1Height = cli.StringFlag{ - Name: "crcproposalv1height", - Usage: "defines the ChangeProposalOwner,CloseProposal and " + - "SecretaryGeneral crc proposal type accept height", - } - RectifyTxFee = cli.StringFlag{ - Name: "rectifytxfee", - Usage: "defines the fee of cr rectify transaction", - } - RealWithdrawSingleFee = cli.StringFlag{ - Name: "realwithdrawsinglefee", - Usage: "defines the single fee of cr real proposal withdraw transaction", - } - NewVersionHeight = cli.StringFlag{ - Name: "newversionheight", - Usage: "defines the new version message height", - } - - ChangeCommitteeNewCRHeight = cli.StringFlag{ - Name: "changecommitteenewcrheight", - Usage: "defines the change committee new cr height", - } - - CRCProposalDraftDataStartHeight = cli.StringFlag{ - Name: "crcproposaldraftdatastartheight", - Usage: "defines the proposal draft data start height", - } - - CRClaimPeriodFlag = cli.StringFlag{ - Name: "crclaimperiod", - Usage: "defines the duration of CR claim DPoS node", - } - - CustomIDProposalStartHeight = cli.StringFlag{ - Name: "CustomIDProposalStartHeight", - Usage: "defines the height to allow custom ID related transaction", - } - - MaxReservedCustomIDLength = cli.StringFlag{ - Name: "maxreservedcustomidlength", - Usage: "defines the max count of reserved custom iid list per tx", - } - - NoCRCDPOSNodeHeight = cli.StringFlag{ - Name: "nocrcdposnodeheight", - Usage: "defines the height when there is no DPOS node of CRC", - } - - RandomCandidatePeriod = cli.StringFlag{ - Name: "randomcandidateperiod", - Usage: "defines the period to get a candidate as DPOS node at random", - } - - MaxInactiveRoundsOfRandomNode = cli.StringFlag{ - Name: "maxinactiveroundsofrandomnode", - Usage: "defines the maximum inactive rounds before the random producer takes penalty", - } - - DPOSNodeCrossChainHeight = cli.StringFlag{ - Name: "dposnodecrosschainheight", - Usage: "defines the height at which not only CR members are responsible for working across the chain", - } - - RevertToPOWNoBlockTimeFlag = cli.StringFlag{ - Name: "reverttopownoblocktime", - Usage: "defines how long time does it take to revert to POW mode", - } - - StopConfirmBlockTimeFlag = cli.StringFlag{ - Name: "stopconfirmblocktime", - Usage: "defines how long time does it take to stop confirm block", - } - - RevertToPOWStartHeightFlag = cli.StringFlag{ - Name: "reverttopowstartheight", - Usage: "defines the start height to allow to revert to POW mode", - } - - HalvingRewardHeightFlag = cli.StringFlag{ - Name: "halvingrewardheight", - Usage: "defines height of having reward", - } - - HalvingRewardIntervalFlag = cli.StringFlag{ - Name: "halvingrewardinterval", - Usage: "defines interval of having reward", - } - - NewELAIssuanceHeightFlag = cli.StringFlag{ - Name: "newelaissuanceheight", - Usage: "defines height of using the new ela issuance (2000w)", - } - - SmallCrossTransferThreshold = cli.StringFlag{ - Name: "smallcrosstransferthreshold", - Usage: "defines the minimum amount of transfer consider as small cross transfer", - } - - ReturnDepositCoinFeeFlag = cli.StringFlag{ - Name: "returndepositcoinfee", - Usage: "defines the fee of return cross chain deposit coin", - } - - NewCrossChainStartHeightFlag = cli.StringFlag{ - Name: "newcrosschainstartheight", - Usage: "defines the height to only support TransferCrossChainAsset v1", - } - - ReturnCrossChainCoinStartHeightFlag = cli.StringFlag{ - Name: "returncrosschaincoinstartheight", - Usage: "defines the start height to support ReturnCrossChainDepositCoin transaction", - } - - DposV2StartHeightFlag = cli.StringFlag{ - Name: "dposv2startheight", - Usage: "defines the start height to support DposV2 transaction", - } - - DposV2EffectiveVotesFlag = cli.StringFlag{ - Name: "dposv2effectivevotes", - Usage: "defines the minimum votes to active a DposV2 producer", - } - - DposV2RewardAccumulateAddressFlag = cli.StringFlag{ - Name: "dposv2rewardaccumulateaddress", - Usage: "defines dposv2 reward accumulate address", + PayloadVersionFlag = cli.Int64Flag{ + Name: "payloadversion", + Usage: "payload version", + Value: 0, } StakePoolFlag = cli.StringFlag{ Name: "stakepool", Usage: "defines the stake address of DPoS v2 votes", } - - SchnorrStartHeightFlag = cli.StringFlag{ - Name: "schnorrstartheight", - Usage: "defines the start height to support schnorr transaction", - } - - CRDPoSNodeHotFixHeightFlag = cli.StringFlag{ - Name: "crdposnodehotfixheight", - Usage: "CRDPoSNodeHotFixHeight indicates the hot fix start height of CR DPoS node", - } - - CrossChainMonitorStartHeightFlag = cli.StringFlag{ - Name: "crosschainmonitorstartheight", - Usage: "defines the start height to monitor cr cross chain transaction", - } - - CrossChainMonitorIntervalFlag = cli.StringFlag{ - Name: "crosschainmonitorinterval", - Usage: "defines the interval cross chain arbitration", - } - PayloadVersionFlag = cli.Int64Flag{ - Name: "payloadversion", - Usage: "payload version", - Value: 0, - } ) // MoveRPCFlags finds the rpc argument and moves it to the front diff --git a/cmd/ela-cli.go b/cmd/ela-cli.go index 28e29129a..0c63285ba 100644 --- a/cmd/ela-cli.go +++ b/cmd/ela-cli.go @@ -78,5 +78,5 @@ func initFunctions() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } diff --git a/cmd/rollback/rollback.go b/cmd/rollback/rollback.go index e88ae7180..a1aead02c 100644 --- a/cmd/rollback/rollback.go +++ b/cmd/rollback/rollback.go @@ -8,13 +8,14 @@ package rollback import ( "errors" "fmt" - "github.com/elastos/Elastos.ELA/core/types/common" "strconv" "github.com/elastos/Elastos.ELA/blockchain" cmdcom "github.com/elastos/Elastos.ELA/cmd/common" "github.com/elastos/Elastos.ELA/common/config/settings" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" + "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/database" "github.com/urfave/cli" @@ -47,9 +48,7 @@ func NewCommand() *cli.Command { } func rollbackAction(c *cli.Context) error { - appSettings.SetContext(c) - appSettings.SetupConfig() - appSettings.InitParamsValue() + config := appSettings.SetupConfig() if c.NumFlags() == 0 { cli.ShowSubcommandHelp(c) @@ -67,14 +66,14 @@ func rollbackAction(c *cli.Context) error { } log.NewDefault("logs/node", 0, 0, 0) - chainStore, err := blockchain.NewChainStore(dataDir, appSettings.Params()) + chainStore, err := blockchain.NewChainStore(dataDir, config) if err != nil { fmt.Println("create chain store failed, ", err) return err } defer chainStore.Close() - - chain, err := blockchain.New(chainStore, appSettings.Params(), nil, nil) + ckpManager := checkpoint.NewManager(config) + chain, err := blockchain.New(chainStore, config, nil, nil, ckpManager) if err != nil { fmt.Println("create blockchain failed, ", err) return err diff --git a/cmd/script/api/api.go b/cmd/script/api/api.go index 295c69e98..22dda6fb4 100644 --- a/cmd/script/api/api.go +++ b/cmd/script/api/api.go @@ -19,6 +19,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" @@ -167,6 +168,7 @@ func setArbitrators(L *lua.LState) int { func initLedger(L *lua.LState) int { chainParams := &config.DefaultParams logLevel := uint8(L.ToInt(1)) + ckpManager := checkpoint.NewManager(chainParams) log.NewDefault(test.NodeLogPath, logLevel, 0, 0) dlog.Init("elastos", logLevel, 0, 0) @@ -179,7 +181,7 @@ func initLedger(L *lua.LState) int { arbiters, err := state.NewArbitrators(chainParams, nil, nil, nil, - nil, nil, nil, nil, nil) + nil, nil, nil, nil, nil, ckpManager) if err != nil { fmt.Printf("New arbitrators error: %s \n", err.Error()) } @@ -191,9 +193,10 @@ func initLedger(L *lua.LState) int { var interrupt = signal.NewInterrupt() chain, err := blockchain.New(chainStore, chainParams, - state.NewState(chainParams, arbiters.GetArbitrators, nil,nil, nil, + state.NewState(chainParams, arbiters.GetArbitrators, nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil), nil) + nil, nil, nil, nil), nil, + ckpManager) if err != nil { fmt.Printf("Init block chain error: %s \n", err.Error()) } @@ -205,8 +208,8 @@ func initLedger(L *lua.LState) int { if err != nil { fmt.Printf("Init fflDB error: %s \n", err.Error()) } - - blockchain.FoundationAddress = chainParams.Foundation + FoundationAddress, _ := common.Uint168FromAddress(chainParams.FoundationAddress) + blockchain.FoundationAddress = *FoundationAddress blockchain.DefaultLedger = &ledger // fixme blockchain.DefaultLedger.Blockchain = chain blockchain.DefaultLedger.Store = chainStore diff --git a/cmd/script/api/attribute.go b/cmd/script/api/attribute.go index fb45d359b..9a6b9e9d2 100644 --- a/cmd/script/api/attribute.go +++ b/cmd/script/api/attribute.go @@ -8,6 +8,7 @@ package api import ( "encoding/hex" "fmt" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/yuin/gopher-lua" diff --git a/cmd/script/api/block.go b/cmd/script/api/block.go index 68397bee0..2fec8f4cd 100644 --- a/cmd/script/api/block.go +++ b/cmd/script/api/block.go @@ -11,6 +11,7 @@ import ( "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/pow" @@ -133,9 +134,10 @@ func blockUpdate(L *lua.LState) int { func updateDposRewards(b *types.Block) { totalTxFee := common.Fixed64(0) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, tx := range b.Transactions { reference, _ := blockchain.DefaultLedger.Blockchain.UTXOCache.GetTxReference(tx) - fee := blockchain.GetTxFee(tx, config.ELAAssetID, reference) + fee := blockchain.GetTxFee(tx, *ELAAssetID, reference) if fee != tx.Fee() { continue } diff --git a/cmd/script/api/clienttype.go b/cmd/script/api/clienttype.go index 5943d3b84..ce683894c 100644 --- a/cmd/script/api/clienttype.go +++ b/cmd/script/api/clienttype.go @@ -9,6 +9,7 @@ import ( "encoding/hex" "errors" "fmt" + "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" diff --git a/cmd/script/api/header.go b/cmd/script/api/header.go index ef2684657..3f12cb2ed 100644 --- a/cmd/script/api/header.go +++ b/cmd/script/api/header.go @@ -6,12 +6,12 @@ package api import ( - common2 "github.com/elastos/Elastos.ELA/core/types/common" "math/rand" "time" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/yuin/gopher-lua" ) @@ -39,7 +39,7 @@ func newHeader(L *lua.LState) int { Previous: *hash, MerkleRoot: common.EmptyHash, Timestamp: uint32(time.Now().Unix()), - Bits: config.DefaultParams.PowLimitBits, + Bits: config.Parameters.PowConfiguration.PowLimitBits, Height: height, Nonce: rand.Uint32(), } diff --git a/cmd/script/api/illegalvotes.go b/cmd/script/api/illegalvotes.go index eece1e9ce..9e268a768 100644 --- a/cmd/script/api/illegalvotes.go +++ b/cmd/script/api/illegalvotes.go @@ -7,8 +7,8 @@ package api import ( "bytes" - "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/yuin/gopher-lua" diff --git a/cmd/script/api/inputtype.go b/cmd/script/api/inputtype.go index 778f3c654..7a766f2d6 100644 --- a/cmd/script/api/inputtype.go +++ b/cmd/script/api/inputtype.go @@ -8,9 +8,9 @@ package api import ( "encoding/hex" "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/yuin/gopher-lua" ) diff --git a/cmd/script/api/mock/peer.go b/cmd/script/api/mock/peer.go index edc6bff06..fe47f0cd3 100644 --- a/cmd/script/api/mock/peer.go +++ b/cmd/script/api/mock/peer.go @@ -7,6 +7,7 @@ package mock import ( "fmt" + "github.com/elastos/Elastos.ELA/core/checkpoint" "time" "github.com/elastos/Elastos.ELA/blockchain" @@ -27,9 +28,9 @@ type PeerMock interface { Broadcast(msg p2p.Message) } -func NewPeerMock(params *config.Params) PeerMock { +func NewPeerMock(params *config.Configuration) PeerMock { p := &peerMock{ - TxPool: mempool.NewTxPool(params), + TxPool: mempool.NewTxPool(params, checkpoint.NewManager(params)), BlockPool: mempool.NewBlockPool(params), relayList: make([]p2p.Message, 0), } diff --git a/cmd/script/api/outputtype.go b/cmd/script/api/outputtype.go index 04bc84f3a..b514074ef 100644 --- a/cmd/script/api/outputtype.go +++ b/cmd/script/api/outputtype.go @@ -8,7 +8,6 @@ package api import ( "encoding/hex" "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "os" "strconv" "strings" @@ -16,6 +15,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/contract" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/crypto" diff --git a/cmd/script/api/payloadtype.go b/cmd/script/api/payloadtype.go index 7282337bd..8bad0c87e 100644 --- a/cmd/script/api/payloadtype.go +++ b/cmd/script/api/payloadtype.go @@ -9,13 +9,13 @@ import ( "bytes" "encoding/hex" "fmt" - "github.com/elastos/Elastos.ELA/core/types/outputpayload" "os" "strconv" "strings" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" + "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" lua "github.com/yuin/gopher-lua" @@ -1230,7 +1230,6 @@ func registerCRGet(L *lua.LState) int { return 0 } -// // Registers my person type to given L. func RegisterUpdateCRType(L *lua.LState) { mt := L.NewTypeMetatable(luaUpdateCRName) diff --git a/common/config/config.go b/common/config/config.go index 3a4465f7b..91e72ca3e 100644 --- a/common/config/config.go +++ b/common/config/config.go @@ -6,22 +6,739 @@ package config import ( + "math" + "math/big" "time" "github.com/elastos/Elastos.ELA/common" ) +const ( + // ConfigFile for node config + ConfigFile = "./config.json" + // DataDir storing the chain data. + DataDir = "elastos" +) + +type Config struct { + *Configuration `json:"Configuration"` +} + var ( - Parameters *Configuration + // DefaultParams defines the default network parameters. + DefaultParams = *GetDefaultParams() + Parameters *Configuration + + // OriginIssuanceAmount is the origin issuance ELA amount. + OriginIssuanceAmount = 3300 * 10000 * 100000000 + + // AfterBurnIssuanceAmount is the new issurance ELA amount after cr proposal #1631. + AfterBurnIssuanceAmount = 2000 * 10000 * 100000000 + + // inflationPerYear is the inflation amount per year. + inflationPerYear = OriginIssuanceAmount * 4 / 100 + + // newInflationPerYear is the new inflation amount per year. + newInflationPerYear = AfterBurnIssuanceAmount * 4 / 100 + + // bigOne is 1 represented as a big.Int. It is defined here to avoid + // the overhead of creating it multiple times. + bigOne = big.NewInt(1) + + // powLimit is the highest proof of work value a block can have for the network. + // It is the value 2^255 - 1. + powLimit = new(big.Int).Sub(new(big.Int).Lsh(bigOne, 255), bigOne) + + // mainNetFoundation + mainNetFoundation = "8VYXVxKKSAxkmRrfmGpQR2Kc66XhG6m3ta" + + // testNetFoundation + testNetFoundation = "8ZNizBf4KhhPjeJRGpox6rPcHE5Np6tFx3" + + // mainNetCRCAddress + mainNetCRCAddress = "8ZZLWQUDSbjWUn8sEdxEFJsZiRFpzg53rJ" + + // testNetCRCAddress + testNetCRCAddress = "8JJCdEjMRm6x2rVsSMesL5gmoq7ts4wHMo" + + // destroyAddress + DestroyELAAddress = "ELANULLXXXXXXXXXXXXXXXXXXXXXYvs3rr" + + // CRAssetsAddress indicates the + // CR assets address. + CRAssetsAddress = "CRASSETSXXXXXXXXXXXXXXXXXXXX2qDX5J" + + // CRCExpensesAddress indicates the + // CRC council expenses address. + CRCExpensesAddress = "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" + + // DPoS 2.0 stake pool address. + StakePoolAddress = "STAKEPooLXXXXXXXXXXXXXXXXXXXpP1PQ2" + + // DPoS 2.0 stake reward pool address. + StakeRewardAddress = "STAKEREWARDXXXXXXXXXXXXXXXXXFD5SHU" ) +func SetParameters(configuration *Configuration) { + Parameters = configuration +} + +func GetDefaultParams() *Configuration { + // DefaultParams defines the default network parameters. + return &Configuration{ + Magic: 2017001, + NodePort: 20338, + DNSSeeds: []string{ + "node-mainnet-005.elastos.org:20338", + "node-mainnet-010.elastos.org:20338", + "node-mainnet-015.elastos.org:20338", + "node-mainnet-020.elastos.org:20338", + "node-mainnet-025.elastos.org:20338", + }, + DestroyELAAddress: DestroyELAAddress, + FoundationAddress: mainNetFoundation, + MaxTxPerBlock: 10000, + MaxBlockSize: 2000000, + MaxBlockHeaderSize: 1000000, + PowConfiguration: PowConfiguration{ + PowLimit: powLimit, + PowLimitBits: 0x1f0008ff, + TargetTimespan: 24 * time.Hour, // 24 hours + TargetTimePerBlock: 2 * time.Minute, // 2 minute + AdjustmentFactor: 4, // 25% less, 400% more + RewardPerBlock: RewardPerBlock(2 * time.Minute), + CoinbaseMaturity: 100, + }, + + CRConfiguration: CRConfiguration{ + CRCAddress: mainNetCRCAddress, + CRAssetsAddress: CRAssetsAddress, + CRExpensesAddress: CRCExpensesAddress, + CRClaimPeriod: 720 * 14, // todo complete me + MemberCount: 12, + VotingPeriod: 30 * 720, + DutyPeriod: 365 * 720, + DepositLockupBlocks: 2160, + CRVotingStartHeight: 537670, + CRCommitteeStartHeight: 658930, + CRClaimDPOSNodeStartHeight: 751400, + CRClaimDPOSNodePeriod: 720 * 14, + CRAgreementCount: 8, + RegisterCRByDIDHeight: 598000, + CRCProposalV1Height: 751400, + CRCAppropriatePercentage: 10, + CRCProposalWithdrawPayloadV1Height: 751400, + CRCProposalDraftDataStartHeight: 1056600, + SecretaryGeneral: "02712da531804d1c38d159a901313239d2100dfb5b693d71a2f76b15dec3f8fc32", + MaxProposalTrackingCount: 128, + CRAssetsRectifyTransactionHeight: 751400, + ProposalCRVotingPeriod: 7 * 720, + ProposalPublicVotingPeriod: 7 * 720, + VoterRejectPercentage: 10, + MaxCommitteeProposalCount: 128, + MaxCRAssetsAddressUTXOCount: 800, + MinCRAssetsAddressUTXOCount: 720, + RectifyTxFee: 10000, + RealWithdrawSingleFee: 10000, + NewP2PProtocolVersionHeight: 751400, + ChangeCommitteeNewCRHeight: 932530, + CheckVoteCRCountHeight: 658930, + }, + + DPoSConfiguration: DPoSConfiguration{ + DPoSMagic: 2019000, + DPoSPort: 20339, + CRDPoSNodeHotFixHeight: 0, + DPoSV2IllegalPenalty: 20000000000, // todo complete me + PreConnectOffset: 360, + NoCRCDPOSNodeHeight: 932530, + RevertToPOWStartHeight: 932530, + RandomCandidatePeriod: 36 * 10, + MaxInactiveRoundsOfRandomNode: 36 * 8, + DPOSNodeCrossChainHeight: 2000000, // todo complete me + RevertToPOWNoBlockTime: 12 * 3600, + StopConfirmBlockTime: 11 * 3600, + DPoSV2RewardAccumulateAddress: StakeRewardAddress, + DPoSV2DepositCoinMinLockTime: 7200, // todo complete me change to 216000 + DPoSV2MinVotesLockTime: 7200, // todo complete me + DPoSV2MaxVotesLockTime: 720000, // todo complete me + SignTolerance: 5 * time.Second, + MaxInactiveRounds: 720 * 2, + InactivePenalty: 0, //there will be no penalty in this version + IllegalPenalty: 0, + EmergencyInactivePenalty: 0, //there will be no penalty in this version + NormalArbitratorsCount: 24, + CandidatesCount: 72, + OriginArbiters: []string{ + "0248df6705a909432be041e0baa25b8f648741018f70d1911f2ed28778db4b8fe4", + "02771faf0f4d4235744b30972d5f2c470993920846c761e4d08889ecfdc061cddf", + "0342196610e57d75ba3afa26e030092020aec56822104e465cba1d8f69f8d83c8e", + "02fa3e0d14e0e93ca41c3c0f008679e417cf2adb6375dd4bbbee9ed8e8db606a56", + "03ab3ecd1148b018d480224520917c6c3663a3631f198e3b25cf4c9c76786b7850", + }, + CRCArbiters: []string{ + "02089d7e878171240ce0e3633d3ddc8b1128bc221f6b5f0d1551caa717c7493062", + "0268214956b8421c0621d62cf2f0b20a02c2dc8c2cc89528aff9bd43b45ed34b9f", + "03cce325c55057d2c8e3fb03fb5871794e73b85821e8d0f96a7e4510b4a922fad5", + "02661637ae97c3af0580e1954ee80a7323973b256ca862cfcf01b4a18432670db4", + "027d816821705e425415eb64a9704f25b4cd7eaca79616b0881fc92ac44ff8a46b", + "02d4a8f5016ae22b1acdf8a2d72f6eb712932213804efd2ce30ca8d0b9b4295ac5", + "029a4d8e4c99a1199f67a25d79724e14f8e6992a0c8b8acf102682bd8f500ce0c1", + "02871b650700137defc5d34a11e56a4187f43e74bb078e147dd4048b8f3c81209f", + "02fc66cba365f9957bcb2030e89a57fb3019c57ea057978756c1d46d40dfdd4df0", + "03e3fe6124a4ea269224f5f43552250d627b4133cfd49d1f9e0283d0cd2fd209bc", + "02b95b000f087a97e988c24331bf6769b4a75e4b7d5d2a38105092a3aa841be33b", + "02a0aa9eac0e168f3474c2a0d04e50130833905740a5270e8a44d6c6e85cf6d98c", + }, + }, + MinTransactionFee: 100, + MinCrossChainTxFee: 10000, + CheckAddressHeight: 88812, + VoteStartHeight: 290000, + CRCOnlyDPOSHeight: 343400, + PublicDPOSHeight: 402680, + EnableActivateIllegalHeight: 439000, + CheckRewardHeight: 436812, + VoteStatisticsHeight: 512881, + EnableUtxoDB: true, + EnableCORS: false, + WalletPath: "keystore.dat", + RPCServiceLevel: ConfigurationPermitted.String(), + MemoryFirst: false, + MaxNodePerHost: 72, + TxCacheVolume: 100000, + CustomIDProposalStartHeight: 932530, + MaxReservedCustomIDLength: 255, + HalvingRewardHeight: 1051200, // 4 * 365 * 720 + HalvingRewardInterval: 1051200, // 4 * 365 * 720 + NewELAIssuanceHeight: 919800, // 3.5 * 365 * 720 + SmallCrossTransferThreshold: 100000000, + ReturnDepositCoinFee: 100, + NewCrossChainStartHeight: 1032840, + ReturnCrossChainCoinStartHeight: 1032840, + ProhibitTransferToDIDHeight: 1032840, + DIDSideChainAddress: "XKUh4GLhFJiqAMTF6HyWQrV9pK9HcGUdfJ", + DPoSV2StartHeight: 2000000, // todo complete me + DPoSV2EffectiveVotes: 8000000000000, + StakePool: StakePoolAddress, // todo complete me + SchnorrStartHeight: 2000000, // todo complete me + CrossChainMonitorStartHeight: 2000000, // todo complete me + CrossChainMonitorInterval: 100, // todo complete me + HttpInfoPort: 20333, + HttpRestPort: 20334, + HttpWsPort: 20335, + HttpJsonPort: 20336, + CheckPointConfiguration: CheckPointConfiguration{ + EnableHistory: true, + HistoryStartHeight: uint32(0), + NeedSave: true, + }, + } +} + +// TestNet returns the network parameters for the test network. +func (p *Configuration) TestNet() *Configuration { + p.Magic = 2018101 + p.NodePort = 21338 + + p.DNSSeeds = []string{ + "node-testnet-002.elastos.org:21338", + "node-testnet-003.elastos.org:21338", + "node-testnet-004.elastos.org:21338", + } + p.DestroyELAAddress = DestroyELAAddress + p.FoundationAddress = testNetFoundation + p.MaxTxPerBlock = 10000 + p.MaxBlockSize = 8000000 + p.MaxBlockHeaderSize = 1000000 + p.CRConfiguration.CRCAddress = testNetCRCAddress + p.CRConfiguration.CRAssetsAddress = CRAssetsAddress + p.CRConfiguration.CRExpensesAddress = CRCExpensesAddress + + p.DPoSConfiguration.DPoSMagic = 2019100 + p.DPoSConfiguration.DPoSPort = 21339 + p.DPoSConfiguration.OriginArbiters = []string{ + "03e333657c788a20577c0288559bd489ee65514748d18cb1dc7560ae4ce3d45613", + "02dd22722c3b3a284929e4859b07e6a706595066ddd2a0b38e5837403718fb047c", + "03e4473b918b499e4112d281d805fc8d8ae7ac0a71ff938cba78006bf12dd90a85", + "03dd66833d28bac530ca80af0efbfc2ec43b4b87504a41ab4946702254e7f48961", + "02c8a87c076112a1b344633184673cfb0bb6bce1aca28c78986a7b1047d257a448", + } + p.DPoSConfiguration.CRCArbiters = []string{ + "03e435ccd6073813917c2d841a0815d21301ec3286bc1412bb5b099178c68a10b6", + "038a1829b4b2bee784a99bebabbfecfec53f33dadeeeff21b460f8b4fc7c2ca771", + "02435df9a4728e6250283cfa8215f16b48948d71936c4600b3a5b1c6fde70503ae", + "027d44ee7e7a6c6ff13a130d15b18c75a3b47494c3e54fcffe5f4b10e225351e09", + "02ad972fbfce4aaa797425138e4f3b22bcfa765ffad88b8a5af0ab515161c0a365", + "0373eeae2bac0f5f14373ca603fe2c9caa9c7a79c7793246cec415d005e2fe53c0", + "03503011cc4e44b94f73ed2c76c73182a75b4863f23d1e7083025eead945a8e764", + "0270b6880e7fab8d02bea7d22639d7b5e07279dd6477baa713dacf99bb1d65de69", + "030eed9f9c1d70307beba52ddb72a24a02582c0ee626ec93ee1dcef2eb308852dd", + "026bba43feb19ce5859ffcf0ce9dd8b9d625130b686221da8b445fa9b8f978d7b9", + "02bf9e37b3db0cbe86acf76a76578c6b17b4146df101ec934a00045f7d201f06dd", + "03111f1247c66755d369a8c8b3a736dfd5cf464ca6735b659533cbe1268cd102a9", + } + p.CRConfiguration.SecretaryGeneral = "0349cb77a69aa35be0bcb044ffd41a616b8367136d3b339d515b1023cc0f302f87" + p.CRConfiguration.MaxProposalTrackingCount = 128 + p.CheckAddressHeight = 0 + p.VoteStartHeight = 200000 + p.CRCOnlyDPOSHeight = 246700 + p.PublicDPOSHeight = 300000 + p.CRConfiguration.CRVotingStartHeight = 436900 + p.CRConfiguration.CRCommitteeStartHeight = 546500 + p.CRConfiguration.CRClaimDPOSNodeStartHeight = 646700 + p.CRConfiguration.CRClaimDPOSNodePeriod = 720 * 7 + p.CRConfiguration.CRCProposalV1Height = 646700 + p.CRConfiguration.NewP2PProtocolVersionHeight = 646700 + p.CRConfiguration.CRAssetsRectifyTransactionHeight = 646700 + p.CRConfiguration.CRCProposalWithdrawPayloadV1Height = 646700 + p.EnableActivateIllegalHeight = 546500 + p.CheckRewardHeight = 100 + p.VoteStatisticsHeight = 0 + p.CRConfiguration.RegisterCRByDIDHeight = 483500 + p.EnableUtxoDB = true + p.EnableCORS = false + p.CRConfiguration.VoterRejectPercentage = 10 + p.CRConfiguration.CRCAppropriatePercentage = 10 + p.CRConfiguration.MaxCommitteeProposalCount = 128 + p.MaxNodePerHost = 10 + p.CRConfiguration.CheckVoteCRCountHeight = 546500 + p.CRConfiguration.MaxCRAssetsAddressUTXOCount = 800 + p.CRConfiguration.ChangeCommitteeNewCRHeight = 815060 + p.CustomIDProposalStartHeight = 815060 + p.DPoSConfiguration.InactivePenalty = 0 + p.DPoSConfiguration.IllegalPenalty = 0 + p.DPoSConfiguration.DPoSV2IllegalPenalty = 200 * 100000000 + p.DPoSConfiguration.NoCRCDPOSNodeHeight = 815060 + p.DPoSConfiguration.RandomCandidatePeriod = 36 * 10 + p.DPoSConfiguration.MaxInactiveRoundsOfRandomNode = 36 * 8 + p.DPoSConfiguration.DPOSNodeCrossChainHeight = 2000000 // todo complete me + p.MaxReservedCustomIDLength = 255 + p.DPoSConfiguration.RevertToPOWNoBlockTime = 12 * 3600 + p.DPoSConfiguration.StopConfirmBlockTime = 11 * 3600 + p.DPoSConfiguration.RevertToPOWStartHeight = 815060 + p.HalvingRewardHeight = 877880 //767000 + 154 * 720 + p.HalvingRewardInterval = 1051200 //4 * 365 * 720 + p.NewELAIssuanceHeight = 774920 //767000 + 720 * 11 + p.SmallCrossTransferThreshold = 100000000 + p.ReturnDepositCoinFee = 100 + p.NewCrossChainStartHeight = 807000 + p.ReturnCrossChainCoinStartHeight = 807000 + p.CRConfiguration.CRCProposalDraftDataStartHeight = 807000 + p.ProhibitTransferToDIDHeight = 807000 + p.DIDSideChainAddress = "XKUh4GLhFJiqAMTF6HyWQrV9pK9HcGUdfJ" + p.DPoSV2StartHeight = 965800 + 720*3 + p.DPoSV2EffectiveVotes = 3000 * 100000000 + p.DPoSConfiguration.DPoSV2RewardAccumulateAddress = StakeRewardAddress + p.StakePool = StakePoolAddress + p.DPoSConfiguration.DPoSV2DepositCoinMinLockTime = 7200 * 3 + p.DPoSConfiguration.DPoSV2MinVotesLockTime = 7200 + p.DPoSConfiguration.DPoSV2MaxVotesLockTime = 720000 + p.CRConfiguration.RealWithdrawSingleFee = 50000 + p.SchnorrStartHeight = 965800 + 720*10 + p.DPoSConfiguration.CRDPoSNodeHotFixHeight = 0 + p.CrossChainMonitorStartHeight = 965800 + 720*3 + p.CrossChainMonitorInterval = 12 + p.CRConfiguration.CRClaimPeriod = 10080 + p.HttpInfoPort = 21333 + p.HttpRestPort = 21334 + p.HttpWsPort = 21335 + p.HttpJsonPort = 21336 + + return p +} + +// RegNet returns the network parameters for the test network. +func (p *Configuration) RegNet() *Configuration { + p.Magic = 2018201 + p.NodePort = 22338 + + p.DNSSeeds = []string{ + "node-regtest-102.eadd.co:22338", + "node-regtest-103.eadd.co:22338", + "node-regtest-104.eadd.co:22338", + } + + p.FoundationAddress = testNetFoundation + p.CRConfiguration.CRCAddress = testNetCRCAddress + p.CRConfiguration.CRAssetsAddress = CRAssetsAddress + p.CRConfiguration.CRExpensesAddress = CRCExpensesAddress + p.DestroyELAAddress = DestroyELAAddress + p.MaxTxPerBlock = 10000 + p.MaxBlockSize = 8000000 + p.MaxBlockHeaderSize = 1000000 + p.DPoSConfiguration.DPoSMagic = 2019200 + p.DPoSConfiguration.DPoSPort = 22339 + p.DPoSConfiguration.OriginArbiters = []string{ + "03e333657c788a20577c0288559bd489ee65514748d18cb1dc7560ae4ce3d45613", + "02dd22722c3b3a284929e4859b07e6a706595066ddd2a0b38e5837403718fb047c", + "03e4473b918b499e4112d281d805fc8d8ae7ac0a71ff938cba78006bf12dd90a85", + "03dd66833d28bac530ca80af0efbfc2ec43b4b87504a41ab4946702254e7f48961", + "02c8a87c076112a1b344633184673cfb0bb6bce1aca28c78986a7b1047d257a448", + } + p.DPoSConfiguration.CRCArbiters = []string{ + "0306e3deefee78e0e25f88e98f1f3290ccea98f08dd3a890616755f1a066c4b9b8", + "02b56a669d713db863c60171001a2eb155679cad186e9542486b93fa31ace78303", + "0250c5019a00f8bb4fd59bb6d613c70a39bb3026b87cfa247fd26f59fd04987855", + "02e00112e3e9defe0f38f33aaa55551c8fcad6aea79ab2b0f1ec41517fdd05950a", + "020aa2d111866b59c70c5acc60110ef81208dcdc6f17f570e90d5c65b83349134f", + "03cd41a8ed6104c1170332b02810237713369d0934282ca9885948960ae483a06d", + "02939f638f3923e6d990a70a2126590d5b31a825a0f506958b99e0a42b731670ca", + "032ade27506951c25127b0d2cb61d164e0bad8aec3f9c2e6785725a6ab6f4ad493", + "03f716b21d7ae9c62789a5d48aefb16ba1e797b04a2ec1424cd6d3e2e0b43db8cb", + "03488b0aace5fe5ee5a1564555819074b96cee1db5e7be1d74625240ef82ddd295", + "03c559769d5f7bb64c28f11760cb36a2933596ca8a966bc36a09d50c24c48cc3e8", + "03b5d90257ad24caf22fa8a11ce270ea57f3c2597e52322b453d4919ebec4e6300", + } + p.CRConfiguration.SecretaryGeneral = "0349cb77a69aa35be0bcb044ffd41a616b8367136d3b339d515b1023cc0f302f87" + p.CRConfiguration.MaxProposalTrackingCount = 128 + p.CheckAddressHeight = 0 + p.VoteStartHeight = 170000 + p.CRCOnlyDPOSHeight = 211000 + p.PublicDPOSHeight = 231500 + p.CRConfiguration.CRVotingStartHeight = 292000 + p.CRConfiguration.CRCommitteeStartHeight = 442000 + p.CRConfiguration.CRClaimDPOSNodeStartHeight = 532650 + p.CRConfiguration.CRClaimDPOSNodePeriod = 720 + p.CRConfiguration.CRCProposalV1Height = 530000 + p.CRConfiguration.NewP2PProtocolVersionHeight = 531030 + p.CRConfiguration.CRAssetsRectifyTransactionHeight = 532650 + p.CRConfiguration.CRCProposalWithdrawPayloadV1Height = 532650 + p.EnableActivateIllegalHeight = 256000 + p.CheckRewardHeight = 280000 + p.VoteStatisticsHeight = 0 + p.CRConfiguration.RegisterCRByDIDHeight = 393000 + + p.EnableUtxoDB = true + p.EnableCORS = false + p.CRConfiguration.VoterRejectPercentage = 10 + p.CRConfiguration.CRCAppropriatePercentage = 10 + p.CRConfiguration.MaxCommitteeProposalCount = 128 + p.MaxNodePerHost = 10 + p.CRConfiguration.CheckVoteCRCountHeight = 435000 + p.CRConfiguration.MaxCRAssetsAddressUTXOCount = 1440 + p.CRConfiguration.ChangeCommitteeNewCRHeight = 706240 + p.CustomIDProposalStartHeight = 706240 + p.DPoSConfiguration.IllegalPenalty = 0 + p.DPoSConfiguration.DPoSV2IllegalPenalty = 20000000000 + p.DPoSConfiguration.InactivePenalty = 0 + p.DPoSConfiguration.NoCRCDPOSNodeHeight = 706240 + p.DPoSConfiguration.RandomCandidatePeriod = 36 * 10 + p.DPoSConfiguration.MaxInactiveRoundsOfRandomNode = 36 * 8 + p.DPoSConfiguration.DPOSNodeCrossChainHeight = 2000000 // todo complete me + p.MaxReservedCustomIDLength = 255 + p.DPoSConfiguration.RevertToPOWNoBlockTime = 12 * 3600 + p.DPoSConfiguration.StopConfirmBlockTime = 11 * 3600 + p.DPoSConfiguration.RevertToPOWStartHeight = 706240 + p.HalvingRewardHeight = 801240 //690360 + 154 * 720 + p.HalvingRewardInterval = 1051200 //4 * 365 * 720 + p.NewELAIssuanceHeight = 691740 //690300 + 720 * 2 + p.SmallCrossTransferThreshold = 100000000 + p.ReturnDepositCoinFee = 100 + p.NewCrossChainStartHeight = 730000 + p.ReturnCrossChainCoinStartHeight = 730000 + p.CRConfiguration.CRCProposalDraftDataStartHeight = 730000 + p.ProhibitTransferToDIDHeight = 730000 + p.DIDSideChainAddress = "XKUh4GLhFJiqAMTF6HyWQrV9pK9HcGUdfJ" + p.DPoSV2StartHeight = 875544 + 720*2 + p.DPoSV2EffectiveVotes = 300000000000 + p.DPoSConfiguration.DPoSV2RewardAccumulateAddress = StakeRewardAddress + p.StakePool = StakePoolAddress + p.DPoSConfiguration.DPoSV2DepositCoinMinLockTime = 7200 * 3 + p.DPoSConfiguration.DPoSV2MinVotesLockTime = 7200 + p.DPoSConfiguration.DPoSV2MaxVotesLockTime = 720000 + p.CRConfiguration.RealWithdrawSingleFee = 10000 + p.SchnorrStartHeight = 875544 + 720*5 + p.DPoSConfiguration.CRDPoSNodeHotFixHeight = 0 + p.CrossChainMonitorStartHeight = 875544 + 720*2 + p.CrossChainMonitorInterval = 12 + p.CRConfiguration.CRClaimPeriod = 10080 + p.HttpInfoPort = 22333 + p.HttpRestPort = 22334 + p.HttpWsPort = 22335 + p.HttpJsonPort = 22336 + + return p +} + +// Configuration defines the configurable parameters to run a ELA node. +type Configuration struct { + ActiveNet string `json:"ActiveNet"` + DataDir string `screw:"short;--datadir" usage:"block data and logs storage path default: elastos"` + HttpInfoPort uint16 `screw:"--infoport" usage:"port for the http info server"` + HttpInfoStart bool `json:"HttpInfoStart"` + HttpRestPort int `screw:"--restport" usage:"port for the http restful server"` + HttpRestStart bool `json:"HttpRestStart"` + HttpWsPort int `screw:"--wsport" usage:"port for the http web socket server"` + HttpWsStart bool `json:"HttpWsStart"` + HttpJsonPort int `screw:"--rpcport" usage:"port for the http json rpc port server"` + ProfilePort uint32 `screw:"--profileport" usage:"port for the http profile port rpc server"` + ProfileHost string `screw:"--profilehost" usage:"port for the http profile rpc host server"` + DisableDNS bool `screw:"--disableDNS" usage:"disable DNS for node"` + EnableRPC bool `screw:"--enableRPC" usage:"enable RPC for node"` + MaxLogsSize int64 `json:"MaxLogsSize"` + MaxPerLogSize int64 `json:"MaxPerLogSize"` + RestCertPath string `json:"RestCertPath"` + RestKeyPath string `json:"RestKeyPath"` + // MaxBlockContextSize is the maximum number of bytes allowed per block context. default value 8000000 + MaxBlockSize uint32 `json:"MaxBlockSize"` + // MaxBlockHeaderSize is the maximum number of bytes allowed per block header. default value 1000000 + MaxBlockHeaderSize uint32 `json:"MaxBlockHeaderSize"` + // MaxTxPerBlock is the maximux number of transactions allowed per block. default value 10000 + MaxTxPerBlock uint32 `json:"MaxTxPerBlock"` + // Show Peers Ip + ShowPeersIp bool `json:"ShowPeersIp"` + // Disable transaction filter supports, include bloom filter tx type filter etc. + DisableTxFilters bool + // PrintLevel defines the level to print log. + PrintLevel uint32 `screw:"--printlevel" usage:"level to print log"` + // NodePort defines the default peer-to-peer port for the network. + NodePort uint16 `screw:"--nodeport" usage:"default peer-to-peer node port for the network"` + // Magic defines the magic number of the peer-to-peer network. + Magic uint32 `screw:"--magic" usage:"magic number for node to initialize p2p connection"` + // DNSSeeds defines a list of DNS seeds for the network to discover peers. + DNSSeeds []string `screw:"--dns" usage:"dns seeds for node to initialize p2p connection"` + // PermanentPeers defines peers seeds for node to initialize p2p connection. + PermanentPeers []string `json:"PermanentPeers"` + // The interface/port to listen for connections. + ListenAddrs []string `json:"ListenAddrs"` + // MinCrossChainTxFee defines the min fee of cross chain transaction + MinCrossChainTxFee common.Fixed64 `json:"MinCrossChainTxFee"` + // MinTransactionFee defines the minimum fee of a transaction. + MinTransactionFee common.Fixed64 `json:"MinTransactionFee"` + // DestroyELAAddress defines address which receiving destroyed ELA. + DestroyELAAddress string `json:"DestroyELAAddress"` + // Foundation defines the foundation address which receiving mining rewards. + FoundationAddress string `screw:"--foundation" usage:"specify the foundation address"` + // Did side chain address + DIDSideChainAddress string `screw:"--didsidechainaddress" usage:"specify the did sidechain address"` + //Prohibit transfers to did height + ProhibitTransferToDIDHeight uint32 `screw:"--prohibittransfertodidheight" usage:"defines the height to prohibit transfer to did"` + // CheckAddressHeight defines the height begin to check output hash. + CheckAddressHeight uint32 `screw:"--checkaddressheight" usage:"defines the height begin to check output hash"` + // VoteStartHeight indicates the height of starting register producer and vote related. + VoteStartHeight uint32 `screw:"--votestartheight" usage:"ndicates the height of starting register producer and vote related"` + // CRCOnlyDPOSHeight (H1) indicates the height of DPOS consensus begins with only CRC producers participate in producing blocks. + CRCOnlyDPOSHeight uint32 `screw:"--crconlydposheight" usage:"(H1) indicates the height of DPOS consensus begins with only CRC producers participate in producing block"` + // PublicDPOSHeight (H2) indicates the height when public registered and elected producers participate in DPOS consensus. + PublicDPOSHeight uint32 `screw:"--publicdposheight" usage:"(H2) indicates the height when public registered and elected producers participate in DPOS consensus"` + // PublicDPOSHeight defines the start height to enable activate illegal producer though activate tx. + EnableActivateIllegalHeight uint32 `screw:"--enableactivateillegalheight" usage:"defines the start height to enable activate illegal producer though activate tx"` + // CheckRewardHeight defines the height to check reward in coin base with new check function. + CheckRewardHeight uint32 `screw:"--checkrewardheight" usage:"defines the height begin to check reward"` + // VoteStatisticsHeight defines the height to deal with block with vote statistics error. + VoteStatisticsHeight uint32 `screw:"--votestatisticsheight" usage:"defines the height to fix vote statistics error"` + // EnableUtxoDB indicate whether to enable utxo database. + EnableUtxoDB bool `json:"EnableUtxoDB"` + // Enable cors for http server. + EnableCORS bool `json:"EnableCORS"` + // WalletPath defines the wallet path used by DPoS arbiters and CR members. + WalletPath string `json:"WalletPath"` + // RPCServiceLevel defines level of service provide to client. + RPCServiceLevel string `json:"RPCServiceLevel"` + // NodeProfileStrategy defines strategy about node profiling. + MemoryFirst bool `json:"NodeProfileStrategy"` + // TxCacheVolume defines the default volume of the transaction cache. + TxCacheVolume uint32 `json:"TxCacheVolume"` + // MaxNodePerHost defines max nodes that one host can establish. + MaxNodePerHost uint32 `screw:"--maxnodeperhost" usage:"defines max nodes that one host can establish"` + // CustomIDProposalStartHeight defines the height to allow custom ID related transaction. + CustomIDProposalStartHeight uint32 `screw:"--CustomIDProposalStartHeight" usage:"defines the height to allow custom ID related transaction"` + // MaxReservedCustomIDLength defines the max length of reserved custom id. + MaxReservedCustomIDLength uint32 `screw:"--maxreservedcustomidlength" usage:"defines the max count of reserved custom iid list per tx"` + // HalvingRewardHeight represents the height of halving reward + HalvingRewardHeight uint32 `screw:"--halvingrewardheight" usage:"defines height of having reward"` + // HalvingRewardInterval represents the interval of halving reward + HalvingRewardInterval uint32 `screw:"--halvingrewardinterval" usage:"defines interval of having reward"` + // NewELAIssuanceHeight represents the new issuance ELA amount after proposal #1631 + NewELAIssuanceHeight uint32 `screw:"--newelaissuanceheight" usage:"defines height of using the new ela issuance (2000w)"` + // SMALLCrossTransferThreshold indicates the minimum amount consider as Small transfer + SmallCrossTransferThreshold common.Fixed64 `screw:"--smallcrosstransferthreshold" usage:"defines the minimum amount of transfer consider as small cross transfer"` + // ReturnDepositCoinFee indicates the fee the + ReturnDepositCoinFee common.Fixed64 `screw:"--returndepositcoinfee" usage:"defines the fee of return cross chain deposit coin"` + // NewCrossChainStartHeight defines the height of new cross chain transaction started. + NewCrossChainStartHeight uint32 `screw:"--newcrosschainstartheight" usage:"defines the height to only support TransferCrossChainAsset v1"` + // ReturnCrossChainCoinStartHeight indicates the start height of ReturnCroossChainDepositCoin transaction + ReturnCrossChainCoinStartHeight uint32 `screw:"--returncrosschaincoinstartheight" usage:"defines the start height to support ReturnCrossChainDepositCoin transaction"` + // DPoSV2StartHeight defines the start height of dpos 2.0. + DPoSV2StartHeight uint32 `screw:"--dposv2startheight" usage:"defines the start height to support DposV2 transaction"` + // DPoSV2EffectiveVotes defines the votes which producer will become a dposV2 effective node + DPoSV2EffectiveVotes common.Fixed64 `screw:"--dposv2effectivevotes" usage:"defines the minimum votes to active a DposV2 producer"` + // ExchangeVotes address of votes + StakePool string `json:"StakePool"` + // SchnorrStartHeight indicates the start height of schnorr + SchnorrStartHeight uint32 `screw:"--schnorrstartheight" usage:"defines the start height to support schnorr transaction"` + // CrossChainMonitorStartHeight indicates the monitor height of cr cross chain arbitration + CrossChainMonitorStartHeight uint32 `screw:"--crosschainmonitorstartheight" usage:"defines the start height to monitor cr cross chain transaction"` + // CrossChainMonitorInterval indicates the interval value of cr cross chain arbitration + CrossChainMonitorInterval uint32 `screw:"--crosschainmonitorinterval" usage:"defines the interval cross chain arbitration"` + CRConfiguration CRConfiguration `json:"CRConfiguration"` + DPoSConfiguration DPoSConfiguration `json:"DPoSConfiguration"` + PowConfiguration PowConfiguration `json:"PowConfiguration"` + RpcConfiguration RpcConfiguration `json:"RpcConfiguration"` + CheckPointConfiguration CheckPointConfiguration `json:"CheckPointConfiguration"` +} + +type CheckPointConfiguration struct { + // EnableHistory is a switch about recording history of snapshots of checkpoints. + EnableHistory bool + // HistoryStartHeight defines the height manager should start to record snapshots of checkpoints. + HistoryStartHeight uint32 + // DataPath defines root directory path of all checkpoint related files. + DataPath string + // NeedSave indicate or not manager should save checkpoints when reached a save point. + NeedSave bool +} + +// DPoSConfiguration defines the DPoS consensus parameters. +type DPoSConfiguration struct { + EnableArbiter bool `screw:"--arbiter" usage:"indicates where or not to enable DPoS arbiter switch"` + // DPoSMagic defines the magic number used in the DPoS network. + DPoSMagic uint32 `screw:"--dposmagic" usage:"defines the magic number used in the DPoS network"` + // DPoSIPAddress defines the IP address for the DPoS network. + IPAddress string `screw:"--dposipaddress" usage:"defines the default IP address for the DPoS network"` + // DPoSDefaultPort defines the default port for the DPoS network. + DPoSPort uint16 `screw:"--dposport" usage:"defines the default port for the DPoS network"` + // ToleranceDuration defines the tolerance duration of the DPoS consensus. + SignTolerance time.Duration `json:"SignTolerance"` + // OriginArbiters defines the original arbiters producing the block. + OriginArbiters []string `screw:"--originarbiters" usage:"defines origin arbiters"` + // CRCArbiters defines the fixed CRC arbiters producing the block. + CRCArbiters []string `screw:"--crcarbiters" usage:"defines crc arbiters"` + // GeneralArbiters defines the number of general(no-CRC) arbiters. + NormalArbitratorsCount int `screw:"--normalarbitratorscount" usage:"defines the number of general(no-CRC) arbiters"` + // CandidateArbiters defines the number of needed candidate arbiters. + CandidatesCount int `screw:"--candidatescount" usage:"defines the number of needed candidate arbiters"` + // EmergencyInactivePenalty defines the penalty amount the emergency producer takes. + EmergencyInactivePenalty common.Fixed64 `screw:"--emergencyinactivepenalty" usage:"defines penalty of emergency inactive"` + // MaxInactiveRounds defines the maximum inactive rounds before producer takes penalty. + MaxInactiveRounds uint32 `screw:"--maxinactiverounds" usage:"defines the maximum inactive rounds before producer takes penalty"` + // InactivePenalty defines the penalty amount the producer takes. + InactivePenalty common.Fixed64 `screw:"--inactivepenalty" usage:"defines penalty of inactive"` + // InactivePenalty defines the penalty amount the producer takes. + IllegalPenalty common.Fixed64 `screw:"--illegalpenalty" usage:"defines the num of illegal penalty should be punished "` + // DPoSV2InactivePenalty defines the penalty amount the producer takes. + DPoSV2IllegalPenalty common.Fixed64 `screw:"--dposv2illegalpenalty" usage:"defines the num of illegal penalty should be punished"` + // PreConnectOffset defines the offset blocks to pre-connect to the block producers. + PreConnectOffset uint32 `screw:"--preconnectoffset" usage:"defines the offset blocks to pre-connect to the block producers"` + // NoCRCDPOSNodeHeight indicates the height when there is no DPOS node of CRC. + NoCRCDPOSNodeHeight uint32 `screw:"--nocrcdposnodeheight" usage:"defines the height when there is no DPOS node of CRC"` + // RandomCandidatePeriod defines the period to get a candidate as DPOS node at random. + RandomCandidatePeriod uint32 `screw:"--randomcandidateperiod" usage:"defines the period to get a candidate as DPOS node at random"` + // MaxInactiveRoundsOfRandomNode defines the maximum inactive rounds before the producer at random takes penalty. + MaxInactiveRoundsOfRandomNode uint32 `screw:"--maxinactiveroundsofrandomnode" usage:"defines the maximum inactive rounds before the random producer takes penalty"` + // DPOSNodeCrossChainHeight defines the height at which not only CR members are responsible for working across the chain. + DPOSNodeCrossChainHeight uint32 `screw:"--dposnodecrosschainheight" usage:"defines the height at which not only CR members are responsible for working across the chain"` + // RevertToPOWInterval defines how long time does it take to revert to POW mode. + RevertToPOWNoBlockTime int64 `screw:"--reverttopownoblocktime" usage:"defines how long time does it take to revert to POW mode"` + // StopConfirmBlockTime defines how long time dose it take before stop confirm block. + StopConfirmBlockTime int64 `screw:"--stopconfirmblocktime" usage:"defines how long time does it take to stop confirm block"` + // RevertToPOWStartHeight defines the start height to allow to revert to POW mode. + RevertToPOWStartHeight uint32 `screw:"--reverttopowstartheight" usage:"defines the start height to allow to revert to POW mode"` + // DPoSV2RewardAccumulateAddress defines the dposv2 reward accumulating address + DPoSV2RewardAccumulateAddress string `screw:"--dposv2rewardaccumulateaddress" usage:"defines dposv2 reward accumulate address"` + // minimum lock time of DPoS V2 deposit coin + DPoSV2DepositCoinMinLockTime uint32 `screw:"--dposv2depositcoinminlocktime" usage:"minimum lock time of DPoS V2 deposit coin"` + // minimum lock time of DPoS V2 votes + DPoSV2MinVotesLockTime uint32 `screw:"--dposv2minvoteslocktime" usage:"minimum lock time of DPoS V2 votes"` + // max lock time of DPoS V2 votes + DPoSV2MaxVotesLockTime uint32 `screw:"--dposv2maxvoteslocktime" usage:"max lock time of DPoS V2 votes"` + // CRDPoSNodeHotFixHeight indicates the hot fix start height of CR DPoS node + CRDPoSNodeHotFixHeight uint32 `screw:"--crdposnodehotfixheight" usage:"CRDPoSNodeHotFixHeight indicates the hot fix start height of CR DPoS node"` +} + +type CRConfiguration struct { + // CheckVoteCRCountHeight defines the height to check count of vote CR. + CheckVoteCRCountHeight uint32 + // CRMemberCount defines the number of CR committee members + MemberCount uint32 `screw:"--crmembercount" usage:"defines the number of CR committee members"` + // CRVotingPeriod defines the duration of voting period which measured by block height + VotingPeriod uint32 `screw:"--crvotingperiod" usage:"defines the duration of voting period which measured by block height"` + // CRDutyPeriod defines the duration of a normal duty period which measured by block height + DutyPeriod uint32 `screw:"--crdutyperiod" usage:"defines the duration of a normal duty period which measured by block height"` + // ProposalCRVotingPeriod defines the duration of CR voting about a proposal + ProposalCRVotingPeriod uint32 `screw:"--proposalcrvotingperiod" usage:"defines the duration of CR voting about a proposal"` + // ProposalPublicVotingPeriod defines the duration of all voters send reject vote about a proposal + ProposalPublicVotingPeriod uint32 `screw:"--proposalpublicvotingperiod" usage:"defines the duration of all voters send reject vote about a proposal"` + // CRAgreementCount defines minimum count to let a registered proposal transfer to CRAgreed state. + CRAgreementCount uint32 `screw:"--cragreementcount" usage:"defines minimum count to let a registered proposal transfer to CRAgreed state"` + // VoterRejectPercentage defines percentage about voters reject a proposal. + VoterRejectPercentage float64 `screw:"--voterrejectpercentage" usage:"defines percentage about voters reject a proposal"` + // CRCAppropriatePercentage defines percentage about CRC appropriation. + CRCAppropriatePercentage float64 `screw:"--crcappropriatepercentage" usage:"defines percentage about CRC appropriation"` + // MaxCommitteeProposalCount defines per committee max proposal count + MaxCommitteeProposalCount uint32 `screw:"--maxcommitteeproposalcount" usage:"defines max count of the proposal that one cr can proposal"` + // DepositLockupBlocks indicates how many blocks need to wait when cancel producer or CRC was triggered, and can submit return deposit coin request + DepositLockupBlocks uint32 `screw:"--crdepositlockupblocks" usage:"DepositLockupBlocks indicates how many blocks need to wait when cancel"` + // SecretaryGeneral defines the secretary general of CR by public key. + SecretaryGeneral string `screw:"--secretarygeneral" usage:"defines the secretary general of CR"` + // MaxProposalTrackingCount defines the max count of CRC proposal tracking transaction. + MaxProposalTrackingCount uint8 `screw:"--maxproposaltrackingcount" usage:"defines the max count of CRC proposal tracking"` + // RegisterCRByDIDHeight defines the height to support register and update CR by CID and CID. + RegisterCRByDIDHeight uint32 `screw:"--registercrbydidheight" usage:"defines the height to support register CR by CID"` + // MaxCRAssetsAddressUTXOCount defines the max UTXOs count of CRFoundation address. + MaxCRAssetsAddressUTXOCount uint32 `screw:"--maxcrassetsaddressutxocount" usage:"defines the maximum number of utxo cr assets address can have"` + // MinCRAssetsAddressUTXOCount defines the min UTXOs count of CRFoundation address. + MinCRAssetsAddressUTXOCount uint32 `screw:"--mincrassetsaddressutxocount" usage:"defines the minimum number of utxo cr assets address can rectify"` + // CRAssetsRectifyTransactionHeight defines the CR rectify transaction start height + CRAssetsRectifyTransactionHeight uint32 `screw:"--crassetsrectifytransactionheight" usage:"defines the cr rectify transaction start height"` + // CRCProposalWithdrawPayloadV1Height defines the CRC proposal withdraw payload height + CRCProposalWithdrawPayloadV1Height uint32 `screw:"--crcproposalwithdrawpayloadv1height" usage:"defines the crc withdraw proposal payload type v1 accept height"` + // CRCProposalV1Height defines the height to support ChangeProposalOwner, CloseProposal and SecretaryGeneral proposal. + CRCProposalV1Height uint32 `screw:"--crcproposalv1height" usage:"defines the ChangeProposalOwner,CloseProposal and SecretaryGeneral crc proposal type accept height"` + // CRCAddress defines the CRC address which receiving mining rewards. + CRCAddress string `screw:"--crcaddress" usage:"crc address of CRC"` + // CRAssetsAddress defines the CR assets address. + CRAssetsAddress string `screw:"--crassetsaddress" usage:"defines foundation address of CRC"` + // CRExpensesAddress defines the CR committee address which receiving appropriation from CR assets address. + CRExpensesAddress string `screw:"--crexpensesaddress" usage:"defines appropriation address of CRC committee"` + // CRVotingStartHeight defines the height of CR voting started. + CRVotingStartHeight uint32 `screw:"--crvotingstartheight" usage:"defines the height of CR voting started"` + // CRCommitteeStartHeight defines the height of CR Committee started. + CRCommitteeStartHeight uint32 `screw:"--crcommitteestartheight" usage:"defines the height of CR Committee started"` + // CRClaimDPOSNodeStartHeight defines the height of CR claim DPOS node started. + CRClaimDPOSNodeStartHeight uint32 `screw:"--crclaimdposnodestartheight" usage:"defines the height of CR claim DPOS node started"` + // CRClaimDPOSNodePeriod defines the period of CR claim DPOS node. + CRClaimDPOSNodePeriod uint32 `screw:"--crclaimdposnodeperiod" usage:"defines the period of CR claim DPOS node"` + // RectifyTxFee defines the fee of cr rectify transaction. + RectifyTxFee common.Fixed64 `screw:"--rectifytxfee" usage:"defines the fee of cr rectify transaction"` + // RealWithdrawSingleFee defines the single fee of cr real proposal withdraw transaction. + RealWithdrawSingleFee common.Fixed64 `screw:"--realwithdrawsinglefee" usage:"defines the single fee of cr real proposal withdraw transaction"` + // NewP2PProtocolVersionHeight defines the new p2p protocol version message height. + NewP2PProtocolVersionHeight uint64 `screw:"--newversionheight" usage:"defines the new version message height"` + // ChangeCommitteeNewCRHeight defines the new arbiter logic after change committee. + ChangeCommitteeNewCRHeight uint32 `screw:"--changecommitteenewcrheight" usage:"defines the change committee new cr height"` + // CRCProposalDraftDataStartHeight defines the proposal draft data start height. + CRCProposalDraftDataStartHeight uint32 `screw:"--crcproposaldraftdatastartheight" usage:"defines the proposal draft data start height"` + // CRClaimPeriod defines the duration of CR claim DPoS node period which measured by block height + CRClaimPeriod uint32 `screw:"--crclaimperiod" usage:"defines the duration of CR claim DPoS node"` +} + // PowConfiguration defines the Proof-of-Work parameters. type PowConfiguration struct { - PayToAddr string `json:"PayToAddr"` - AutoMining bool `json:"AutoMining"` + PayToAddr string `screw:"--paytoaddr" usage:"specify the miner reward address"` + AutoMining bool `screw:"--automining" usage:"specify if should open auto mining"` MinerInfo string `json:"MinerInfo"` - MinTxFee int `json:"MinTxFee"` + MinTxFee int `screw:"--mintxfee" usage:"specify minimum transaction fee"` InstantBlock bool `json:"InstantBlock"` + // powLimit defines the highest allowed proof of work value for a block as a uint256. + PowLimit *big.Int `json:"PowLimit"` + // PowLimitBits defines the highest allowed proof of work value for a block in compact form. + PowLimitBits uint32 `json:"PowLimitBits"` + // TargetTimespan is the desired amount of time that should elapse before the block difficulty requirement + //is examined to determine how it should be changed in order to maintain the desired block generation rate. + TargetTimespan time.Duration + // TargetTimePerBlock is the desired amount of time to generate each block. + TargetTimePerBlock time.Duration + // AdjustmentFactor is the adjustment factor used to limit the minimum and maximum amount of adjustment + //that can occur between difficulty retargets. + AdjustmentFactor int64 + // RewardPerBlock is the reward amount per block. + RewardPerBlock common.Fixed64 + // NewRewardPerBlock is the reward amount per block. + NewRewardPerBlock common.Fixed64 + // CoinbaseMaturity is the number of blocks required before newly mined coins (coinbase transactions) can be spent. + CoinbaseMaturity uint32 } // RpcConfiguration defines the JSON-RPC authenticate parameters. @@ -31,155 +748,50 @@ type RpcConfiguration struct { WhiteIPList []string `json:"WhiteIPList"` } -// Configuration defines the configurable parameters to run a ELA node. -type Configuration struct { - ActiveNet string `json:"ActiveNet"` - Magic uint32 `json:"Magic"` - DNSSeeds []string `json:"DNSSeeds"` - DisableDNS bool `json:"DisableDNS"` - PermanentPeers []string `json:"PermanentPeers"` - HttpInfoPort uint16 `json:"HttpInfoPort"` - HttpInfoStart bool `json:"HttpInfoStart"` - HttpRestPort int `json:"HttpRestPort"` - HttpRestStart bool `json:"HttpRestStart"` - HttpWsPort int `json:"HttpWsPort"` - HttpWsStart bool `json:"HttpWsStart"` - HttpJsonPort int `json:"HttpJsonPort"` - EnableRPC bool `json:"EnableRPC"` - NodePort uint16 `json:"NodePort"` - PrintLevel uint32 `json:"PrintLevel"` - MaxLogsSize int64 `json:"MaxLogsSize"` - MaxPerLogSize int64 `json:"MaxPerLogSize"` - RestCertPath string `json:"RestCertPath"` - RestKeyPath string `json:"RestKeyPath"` - MinCrossChainTxFee common.Fixed64 `json:"MinCrossChainTxFee"` - FoundationAddress string `json:"FoundationAddress"` - DIDSideChainAddress string `json:"DIDSideChainAddress"` - ProhibitTransferToDIDHeight uint32 `json:"ProhibitTransferToDIDHeight"` - PowConfiguration PowConfiguration `json:"PowConfiguration"` - RpcConfiguration RpcConfiguration `json:"RpcConfiguration"` - DPoSConfiguration DPoSConfiguration `json:"DPoSConfiguration"` - CRConfiguration CRConfiguration `json:"CRConfiguration"` - CheckAddressHeight uint32 `json:"CheckAddressHeight"` - VoteStartHeight uint32 `json:"VoteStartHeight"` - CRCOnlyDPOSHeight uint32 `json:"CRCOnlyDPOSHeight"` - PublicDPOSHeight uint32 `json:"PublicDPOSHeight"` - EnableActivateIllegalHeight uint32 `json:"EnableActivateIllegalHeight"` - CheckRewardHeight uint32 `json:"CheckRewardHeight"` - VoteStatisticsHeight uint32 `json:"VoteStatisticsHeight"` - ProfilePort uint32 `json:"ProfilePort"` - ProfileHost string `json:"ProfileHost"` - MaxBlockSize uint32 `json:"MaxBlockSize"` - MaxBlockHeaderSize uint32 `json:"MaxBlockHeaderSize"` - MaxTxPerBlock uint32 `json:"MaxTxPerBlock"` - EnableUtxoDB bool `json:"EnableUtxoDB"` - EnableCORS bool `json:"EnableCORS"` - WalletPath string `json:"WalletPath"` - RPCServiceLevel string `json:"RPCServiceLevel"` - NodeProfileStrategy string `json:"NodeProfileStrategy"` - TxCacheVolume uint32 `json:"TxCacheVolume"` - MaxNodePerHost uint32 `json:"MaxNodePerHost"` - CustomIDProposalStartHeight uint32 `json:"CustomIDProposalStartHeight"` - MaxReservedCustomIDLength uint32 `json:"MaxReservedCustomIDLength"` - HalvingRewardHeight uint32 `json:"HalvingRewardHeight"` - HalvingRewardInterval uint32 `json:"HalvingRewardInterval"` - NewELAIssuanceHeight uint32 `json:"NewELAIssuanceHeight"` - SmallCrossTransferThreshold common.Fixed64 `json:"SmallCrossTransferThreshold"` - ReturnDepositCoinFee common.Fixed64 `json:"ReturnDepositCoinFee"` - NewCrossChainStartHeight uint32 `json:"NewCrossChainStartHeight"` - ReturnCrossChainCoinStartHeight uint32 `json:"ReturnCrossChainCoinStartHeight"` - DPoSV2StartHeight uint32 `json:"DPoSV2StartHeight"` - DPoSV2EffectiveVotes common.Fixed64 `json:"DPoSV2EffectiveVotes"` - StakePool string `json:"StakePool"` - SchnorrStartHeight uint32 `json:"SchnorrStartHeight"` - CrossChainMonitorStartHeight uint32 `json:"CrossChainMonitorStartHeight"` - CrossChainMonitorInterval uint32 `json:"CrossChainMonitorInterval"` - ShowPeersIp bool `json:"ShowPeersIp"` +// InstantBlock returns the network parameters for generate instant block. +func (p *Configuration) InstantBlock() *Configuration { + p.PowConfiguration.PowLimitBits = 0x207fffff + p.PowConfiguration.TargetTimespan = 10 * time.Second + p.PowConfiguration.TargetTimePerBlock = 1 * time.Second + return p } -// DPoSConfiguration defines the DPoS consensus parameters. -type DPoSConfiguration struct { - EnableArbiter bool `json:"EnableArbiter"` - Magic uint32 `json:"Magic"` - IPAddress string `json:"IPAddress"` - DPoSPort uint16 `json:"DPoSPort"` - SignTolerance time.Duration `json:"SignTolerance"` - OriginArbiters []string `json:"OriginArbiters"` - CRCArbiters []string `json:"CRCArbiters"` - NormalArbitratorsCount int `json:"NormalArbitratorsCount"` - CandidatesCount int `json:"CandidatesCount"` - EmergencyInactivePenalty common.Fixed64 `json:"EmergencyInactivePenalty"` - MaxInactiveRounds uint32 `json:"MaxInactiveRounds"` - InactivePenalty common.Fixed64 `json:"InactivePenalty"` - IllegalPenalty common.Fixed64 `json:"IllegalPenalty"` - DPoSV2IllegalPenalty common.Fixed64 `json:"DPoSV2IllegalPenalty"` - PreConnectOffset uint32 `json:"PreConnectOffset"` - NoCRCDPOSNodeHeight uint32 `json:"NoCRCDPOSNodeHeight"` - RandomCandidatePeriod uint32 `json:"RandomCandidatePeriod"` - MaxInactiveRoundsOfRandomNode uint32 `json:"MaxInactiveRoundsOfRandomNode"` - DPOSNodeCrossChainHeight uint32 `json:"DPOSNodeCrossChainHeight"` - RevertToPOWNoBlockTime int64 `json:"RevertToPOWNoBlockTime"` - StopConfirmBlockTime int64 `json:"StopConfirmBlockTime"` - RevertToPOWStartHeight uint32 `json:"RevertToPOWStartHeight"` - DPoSV2RewardAccumulateAddress string `json:"DPoSV2RewardAccumulateAddress"` - DPoSV2DepositCoinMinLockTime uint32 `json:"DPoSV2DepositCoinMinLockTime"` - DPoSV2MinVotesLockTime uint32 `json:"DPoSV2MinVotesLockTime"` - DPoSV2MaxVotesLockTime uint32 `json:"DPoSV2MaxVotesLockTime"` - CRDPoSNodeHotFixHeight uint32 `json:"CRDPoSNodeHotFixHeight"` +// RewardPerBlock calculates the reward for each block by a specified time duration. +func RewardPerBlock(targetTimePerBlock time.Duration) common.Fixed64 { + blockGenerateInterval := int64(targetTimePerBlock / time.Second) + generatedBlocksPerYear := 365 * 24 * 60 * 60 / blockGenerateInterval + return common.Fixed64(float64(inflationPerYear) / float64(generatedBlocksPerYear)) } -type CRConfiguration struct { - MemberCount uint32 `json:"MemberCount"` - VotingPeriod uint32 `json:"VotingPeriod"` - DutyPeriod uint32 `json:"DutyPeriod"` - DepositLockupBlocks uint32 `json:"DepositLockupBlocks"` - ProposalCRVotingPeriod uint32 `json:"ProposalCRVotingPeriod"` - ProposalPublicVotingPeriod uint32 `json:"ProposalPublicVotingPeriod"` - CRAgreementCount uint32 `json:"CRAgreementCount"` - VoterRejectPercentage float64 `json:"VoterRejectPercentage"` - CRCAppropriatePercentage float64 `json:"CRCAppropriatePercentage"` - MaxCommitteeProposalCount uint32 `json:"MaxCommitteeProposalCount"` - SecretaryGeneral string `json:"SecretaryGeneral"` - MaxProposalTrackingCount uint8 `json:"MaxProposalTrackingCount"` - RegisterCRByDIDHeight uint32 `json:"RegisterCRByDIDHeight"` - MaxCRAssetsAddressUTXOCount uint32 `json:"MaxCRAssetsAddressUTXOCount"` - MinCRAssetsAddressUTXOCount uint32 `json:"MinCRAssetsAddressUTXOCount"` - CRAssetsRectifyTransactionHeight uint32 `json:"CRAssetsRectifyTransactionHeight"` - CRCProposalWithdrawPayloadV1Height uint32 `json:"CRCProposalWithdrawPayloadV1Height"` - CRCProposalV1Height uint32 `json:"CRCProposalV1Height"` - CRCAddress string `json:"CRCAddress"` - CRAssetsAddress string `json:"CRAssetsAddress"` - CRExpensesAddress string `json:"CRExpensesAddress"` - CRVotingStartHeight uint32 `json:"CRVotingStartHeight"` - CRCommitteeStartHeight uint32 `json:"CRCommitteeStartHeight"` - CRClaimDPOSNodeStartHeight uint32 `json:"CRClaimDPOSNodeStartHeight"` - CRClaimDPOSNodePeriod uint32 `json:"CRClaimDPOSNodePeriod"` - RectifyTxFee common.Fixed64 `json:"RectifyTxFee"` - RealWithdrawSingleFee common.Fixed64 `json:"RealWithdrawSingleFee"` - NewP2PProtocolVersionHeight uint64 `json:"NewP2PProtocolVersionHeight"` - ChangeCommitteeNewCRHeight uint32 `json:"ChangeCommitteeNewCRHeight"` - CRCProposalDraftDataStartHeight uint32 `json:"CRCProposalDraftDataStartHeight"` - CRClaimPeriod uint32 `json:"CRClaimPeriod"` +func (p *Configuration) GetBlockReward(height uint32) (rewardPerBlock common.Fixed64) { + if height < p.NewELAIssuanceHeight { + rewardPerBlock = p.PowConfiguration.RewardPerBlock + } else { + rewardPerBlock = p.newRewardPerBlock(2*time.Minute, height) + } + return } -type RPCServiceLevel byte - -const ( - // Allowed query transaction, and configuration related options. - ConfigurationPermitted RPCServiceLevel = iota - - // Allowed mining from RPC. - MiningPermitted +// newRewardPerBlock calculates the reward for each block by a specified time duration. +func (p *Configuration) newRewardPerBlock(targetTimePerBlock time.Duration, height uint32) common.Fixed64 { + blockGenerateInterval := int64(targetTimePerBlock / time.Second) + generatedBlocksPerYear := 365 * 24 * 60 * 60 / blockGenerateInterval + factor := uint32(1) + if height >= p.HalvingRewardHeight { + factor = 2 + (height-p.HalvingRewardHeight)/p.HalvingRewardInterval + } - // Allowed query and transaction ( - // such as sendrawtransaction) related options. - TransactionPermitted + return common.Fixed64(float64(newInflationPerYear) / float64(generatedBlocksPerYear) / math.Pow(2, float64(factor-1))) +} - // Allowed using wallet related function. - WalletPermitted +type RPCServiceLevel byte - // Allowed only query related options. - QueryOnly +const ( + ConfigurationPermitted RPCServiceLevel = iota // Allowed query transaction, and configuration related options. + MiningPermitted // Allowed mining from RPC. + TransactionPermitted // Allowed query and transaction (such as sendrawtransaction) related options. + WalletPermitted // Allowed using wallet related function. + QueryOnly // Allowed only query related options. ) func (l RPCServiceLevel) String() string { @@ -215,32 +827,3 @@ func RPCServiceLevelFromString(str string) RPCServiceLevel { return ConfigurationPermitted } } - -type NodeProfileStrategy byte - -const ( - // Node will balance usage of CPU and memory. - Balanced NodeProfileStrategy = iota - - // Node will optimise the block processing procedure, super node strongly - // recommended. - SpeedFirst - - // Node will optimise the usage of memory usage, note this may slow down - // block processing, do no use this if your memory is extremely low ( - // specifically small than 2G bytes). - MemoryFirst -) - -func (s NodeProfileStrategy) String() string { - switch s { - case Balanced: - return "Balanced" - case SpeedFirst: - return "SpeedFirst" - case MemoryFirst: - return "MemoryFirst" - default: - return "Unknown" - } -} diff --git a/common/config/config_test.go b/common/config/config_test.go new file mode 100644 index 000000000..8c44a8abb --- /dev/null +++ b/common/config/config_test.go @@ -0,0 +1,120 @@ +// Copyright (c) 2017-2020 The Elastos Foundation +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. +// + +package config + +import ( + "testing" + + "github.com/elastos/Elastos.ELA/common" + "github.com/stretchr/testify/assert" +) + +func TestStringUint(t *testing.T) { + // + mainNetFoundation := "8VYXVxKKSAxkmRrfmGpQR2Kc66XhG6m3ta" + uint168mainNetFoundation, _ := common.Uint168FromAddress(mainNetFoundation) + assert.Equal(t, uint168mainNetFoundation, + &common.Uint168{ + 0x12, 0x9e, 0x9c, 0xf1, 0xc5, 0xf3, 0x36, + 0xfc, 0xf3, 0xa6, 0xc9, 0x54, 0x44, 0x4e, + 0xd4, 0x82, 0xc5, 0xd9, 0x16, 0xe5, 0x06, + }) + + // + testNetFoundation := "8ZNizBf4KhhPjeJRGpox6rPcHE5Np6tFx3" + uint168testNetFoundation, _ := common.Uint168FromAddress(testNetFoundation) + assert.Equal(t, uint168testNetFoundation, + &common.Uint168{ + 0x12, 0xc8, 0xa2, 0xe0, 0x67, 0x72, 0x27, + 0x14, 0x4d, 0xf8, 0x22, 0xb7, 0xd9, 0x24, + 0x6c, 0x58, 0xdf, 0x68, 0xeb, 0x11, 0xce, + }) + + // + mainNetCRCAddress := "8ZZLWQUDSbjWUn8sEdxEFJsZiRFpzg53rJ" + uint168mainNetCRCAddress, _ := common.Uint168FromAddress(mainNetCRCAddress) + assert.Equal(t, uint168mainNetCRCAddress, + &common.Uint168{ + 0x12, 0xca, 0xa4, 0xb0, 0x0b, 0x86, 0x8b, + 0xe7, 0x92, 0xe2, 0x40, 0x1e, 0x97, 0x4e, + 0xcd, 0x5f, 0xcb, 0x1f, 0xd9, 0xab, 0x37, + }) + + // + testNetCRCAddress := "8JJCdEjMRm6x2rVsSMesL5gmoq7ts4wHMo" + uint168testNetCRCAddress, _ := common.Uint168FromAddress(testNetCRCAddress) + assert.Equal(t, uint168testNetCRCAddress, + &common.Uint168{ + 0x12, 0x23, 0x3d, 0xfb, 0x54, 0x88, 0xbb, + 0xa2, 0xe9, 0xfa, 0x9a, 0x11, 0xbb, 0x07, + 0xac, 0x10, 0xcd, 0x77, 0x29, 0x41, 0x22, + }) + + // + DestroyELAAddress := "ELANULLXXXXXXXXXXXXXXXXXXXXXYvs3rr" + uint168DestroyELAAddress, _ := common.Uint168FromAddress(DestroyELAAddress) + assert.Equal(t, uint168DestroyELAAddress, + &common.Uint168{ + 0x21, 0x20, 0xfe, 0xe5, 0xd7, 0xeb, 0x3e, + 0x5c, 0x7d, 0x31, 0x97, 0xfe, 0xcf, 0x6c, + 0x0d, 0xe3, 0x0f, 0x88, 0x9a, 0xce, 0xf7, + }) + + // CRAssetsAddress indicates the + // CR assets address. + CRAssetsAddress := "CRASSETSXXXXXXXXXXXXXXXXXXXX2qDX5J" + uint168CRAssetsAddress, _ := common.Uint168FromAddress(CRAssetsAddress) + assert.Equal(t, uint168CRAssetsAddress, + &common.Uint168{ + 0x1c, 0x5f, 0x6c, 0x3e, 0x9f, 0x0c, 0x9a, + 0x71, 0x10, 0xb8, 0xeb, 0x6e, 0x37, 0x02, + 0x63, 0x0f, 0x71, 0x27, 0x4d, 0xf1, 0xc0, + }) + + // CRCExpensesAddress indicates the + // CRC council expenses address. + CRCExpensesAddress := "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" + uint168CRCExpensesAddress, _ := common.Uint168FromAddress(CRCExpensesAddress) + assert.Equal(t, uint168CRCExpensesAddress, + &common.Uint168{ + 0x1c, 0x60, 0x32, 0x09, 0xff, 0x5d, 0x86, + 0x54, 0x2d, 0x26, 0x1a, 0x8d, 0x22, 0x7f, + 0xe0, 0xf5, 0xee, 0x2c, 0x4e, 0xd2, 0xd3, + }) + + // + // DPoS 2.0 stake pool address. + StakePoolAddress := "STAKEPooLXXXXXXXXXXXXXXXXXXXpP1PQ2" + uint168StakePoolAddress, _ := common.Uint168FromAddress(StakePoolAddress) + assert.Equal(t, uint168StakePoolAddress, + &common.Uint168{ + 0x3f, 0x40, 0x5c, 0x9e, 0x71, 0x3f, 0x20, + 0x13, 0xa3, 0x16, 0x39, 0x49, 0xbd, 0xd6, + 0xf0, 0xbc, 0xad, 0xd6, 0xc8, 0xf5, 0xab, + }) + + // + // DPoS 2.0 stake reward pool address. + StakeRewardAddress := "STAKEREWARDXXXXXXXXXXXXXXXXXFD5SHU" + uint168StakeRewardAddress, _ := common.Uint168FromAddress(StakeRewardAddress) + assert.Equal(t, uint168StakeRewardAddress, + &common.Uint168{ + 0x3f, 0x40, 0x5c, 0x9e, 0x88, 0x6f, 0x83, + 0xef, 0xe2, 0xeb, 0x7f, 0x86, 0x5c, 0xd4, + 0xf1, 0x44, 0x5f, 0xb2, 0x11, 0x9c, 0xe6, + }) + + ELAAssetID := "b037db964a231458d2d6ffd5ea18944c4f90e63d547c5d3b9874df66a4ead0a3" + uint256ELAAssetID, _ := common.Uint256FromHexString(ELAAssetID) + assert.Equal(t, uint256ELAAssetID, + &common.Uint256{ + 0xb0, 0x37, 0xdb, 0x96, 0x4a, 0x23, 0x14, + 0x58, 0xd2, 0xd6, 0xff, 0xd5, 0xea, 0x18, + 0x94, 0x4c, 0x4f, 0x90, 0xe6, 0x3d, 0x54, + 0x7c, 0x5d, 0x3b, 0x98, 0x74, 0xdf, 0x66, + 0xa4, 0xea, 0xd0, 0xa3, + }) +} diff --git a/common/config/params.go b/common/config/params.go deleted file mode 100644 index 2f06a9d94..000000000 --- a/common/config/params.go +++ /dev/null @@ -1,972 +0,0 @@ -// Copyright (c) 2017-2020 The Elastos Foundation -// Use of this source code is governed by an MIT -// license that can be found in the LICENSE file. -// - -package config - -import ( - "math" - "math/big" - "time" - - "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/checkpoint" - "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" - common2 "github.com/elastos/Elastos.ELA/core/types/common" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/core/types/interfaces" - "github.com/elastos/Elastos.ELA/core/types/payload" - "github.com/elastos/Elastos.ELA/crypto" -) - -// These variables are the chain consensus parameters for each default -// network. -var ( - // zeroHash represents a hash with all '0' value. - zeroHash = common.Uint256{} - - // attrNonce represents the nonce attribute used in the genesis coinbase - // transaction. - attrNonce = common2.NewAttribute(common2.Nonce, - []byte{77, 101, 130, 33, 7, 252, 253, 82}) - - // genesisTime indicates the time when ELA genesis block created. - genesisTime, _ = time.Parse(time.RFC3339, "2017-12-22T10:00:00Z") - - // OriginIssuanceAmount is the origin issuance ELA amount. - OriginIssuanceAmount = 3300 * 10000 * 100000000 - - // AfterBurnIssuanceAmount is the new issurance ELA amount after cr proposal #1631. - AfterBurnIssuanceAmount = 2000 * 10000 * 100000000 - - // inflationPerYear is the inflation amount per year. - inflationPerYear = OriginIssuanceAmount * 4 / 100 - - // newInflationPerYear is the new inflation amount per year. - newInflationPerYear = AfterBurnIssuanceAmount * 4 / 100 - - // bigOne is 1 represented as a big.Int. It is defined here to avoid - // the overhead of creating it multiple times. - bigOne = big.NewInt(1) - - // powLimit is the highest proof of work value a block can have for the network. - // It is the value 2^255 - 1. - powLimit = new(big.Int).Sub(new(big.Int).Lsh(bigOne, 255), bigOne) - - // "8VYXVxKKSAxkmRrfmGpQR2Kc66XhG6m3ta" - mainNetFoundation = common.Uint168{ - 0x12, 0x9e, 0x9c, 0xf1, 0xc5, 0xf3, 0x36, - 0xfc, 0xf3, 0xa6, 0xc9, 0x54, 0x44, 0x4e, - 0xd4, 0x82, 0xc5, 0xd9, 0x16, 0xe5, 0x06, - } - - // "8ZNizBf4KhhPjeJRGpox6rPcHE5Np6tFx3" - testNetFoundation = common.Uint168{ - 0x12, 0xc8, 0xa2, 0xe0, 0x67, 0x72, 0x27, - 0x14, 0x4d, 0xf8, 0x22, 0xb7, 0xd9, 0x24, - 0x6c, 0x58, 0xdf, 0x68, 0xeb, 0x11, 0xce, - } - - // "8ZZLWQUDSbjWUn8sEdxEFJsZiRFpzg53rJ" - mainNetCRCAddress = common.Uint168{ - 0x12, 0xca, 0xa4, 0xb0, 0x0b, 0x86, 0x8b, - 0xe7, 0x92, 0xe2, 0x40, 0x1e, 0x97, 0x4e, - 0xcd, 0x5f, 0xcb, 0x1f, 0xd9, 0xab, 0x37, - } - - // "8JJCdEjMRm6x2rVsSMesL5gmoq7ts4wHMo" - testNetCRCAddress = common.Uint168{ - 0x12, 0x23, 0x3d, 0xfb, 0x54, 0x88, 0xbb, - 0xa2, 0xe9, 0xfa, 0x9a, 0x11, 0xbb, 0x07, - 0xac, 0x10, 0xcd, 0x77, 0x29, 0x41, 0x22, - } - - // "ELANULLXXXXXXXXXXXXXXXXXXXXXYvs3rr" - DestroyELAAddress = common.Uint168{ - 0x21, 0x20, 0xfe, 0xe5, 0xd7, 0xeb, 0x3e, - 0x5c, 0x7d, 0x31, 0x97, 0xfe, 0xcf, 0x6c, - 0x0d, 0xe3, 0x0f, 0x88, 0x9a, 0xce, 0xf7, - } - - // ELAAssetID represents the asset ID of ELA coin. - ELAAssetID = common.Uint256{ - 0xb0, 0x37, 0xdb, 0x96, 0x4a, 0x23, 0x14, - 0x58, 0xd2, 0xd6, 0xff, 0xd5, 0xea, 0x18, - 0x94, 0x4c, 0x4f, 0x90, 0xe6, 0x3d, 0x54, - 0x7c, 0x5d, 0x3b, 0x98, 0x74, 0xdf, 0x66, - 0xa4, 0xea, 0xd0, 0xa3, - } - - // ELAPrecision represents the precision of ELA coin. - ELAPrecision = byte(0x08) - - // CRAssetsAddress indicates the "CRASSETSXXXXXXXXXXXXXXXXXXXX2qDX5J" - // CR assets address. - CRAssetsAddress = common.Uint168{ - 0x1c, 0x5f, 0x6c, 0x3e, 0x9f, 0x0c, 0x9a, - 0x71, 0x10, 0xb8, 0xeb, 0x6e, 0x37, 0x02, - 0x63, 0x0f, 0x71, 0x27, 0x4d, 0xf1, 0xc0, - } - - // CRCExpensesAddress indicates the "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" - // CRC council expenses address. - CRCExpensesAddress = common.Uint168{ - 0x1c, 0x60, 0x32, 0x09, 0xff, 0x5d, 0x86, - 0x54, 0x2d, 0x26, 0x1a, 0x8d, 0x22, 0x7f, - 0xe0, 0xf5, 0xee, 0x2c, 0x4e, 0xd2, 0xd3, - } - - // "STAKEPooLXXXXXXXXXXXXXXXXXXXpP1PQ2" - // DPoS 2.0 stake pool address. - StakePoolAddress = common.Uint168{ - 0x3f, 0x40, 0x5c, 0x9e, 0x71, 0x3f, 0x20, - 0x13, 0xa3, 0x16, 0x39, 0x49, 0xbd, 0xd6, - 0xf0, 0xbc, 0xad, 0xd6, 0xc8, 0xf5, 0xab, - } - - // "STAKEREWARDXXXXXXXXXXXXXXXXXFD5SHU" - // DPoS 2.0 stake reward pool address. - StakeRewardAddress = common.Uint168{ - 0x3f, 0x40, 0x5c, 0x9e, 0x88, 0x6f, 0x83, - 0xef, 0xe2, 0xeb, 0x7f, 0x86, 0x5c, 0xd4, - 0xf1, 0x44, 0x5f, 0xb2, 0x11, 0x9c, 0xe6, - } -) - -// DefaultParams defines the default network parameters. -var DefaultParams = Params{} - -func GetDefaultParams() Params { - - // DefaultParams defines the default network parameters. - return Params{ - Magic: 2017001, - DefaultPort: 20338, - - DNSSeeds: []string{ - "node-mainnet-005.elastos.org:20338", - "node-mainnet-010.elastos.org:20338", - "node-mainnet-015.elastos.org:20338", - "node-mainnet-020.elastos.org:20338", - "node-mainnet-025.elastos.org:20338", - }, - - Foundation: mainNetFoundation, - CRCAddress: mainNetCRCAddress, - CRAssetsAddress: CRAssetsAddress, - CRExpensesAddress: CRCExpensesAddress, - DestroyELAAddress: DestroyELAAddress, - GenesisBlock: GenesisBlock(&mainNetFoundation), - - DPoSMagic: 2019000, - DPoSDefaultPort: 20339, - OriginArbiters: []string{ - "0248df6705a909432be041e0baa25b8f648741018f70d1911f2ed28778db4b8fe4", - "02771faf0f4d4235744b30972d5f2c470993920846c761e4d08889ecfdc061cddf", - "0342196610e57d75ba3afa26e030092020aec56822104e465cba1d8f69f8d83c8e", - "02fa3e0d14e0e93ca41c3c0f008679e417cf2adb6375dd4bbbee9ed8e8db606a56", - "03ab3ecd1148b018d480224520917c6c3663a3631f198e3b25cf4c9c76786b7850", - }, - CRCArbiters: []string{ - "02089d7e878171240ce0e3633d3ddc8b1128bc221f6b5f0d1551caa717c7493062", - "0268214956b8421c0621d62cf2f0b20a02c2dc8c2cc89528aff9bd43b45ed34b9f", - "03cce325c55057d2c8e3fb03fb5871794e73b85821e8d0f96a7e4510b4a922fad5", - "02661637ae97c3af0580e1954ee80a7323973b256ca862cfcf01b4a18432670db4", - "027d816821705e425415eb64a9704f25b4cd7eaca79616b0881fc92ac44ff8a46b", - "02d4a8f5016ae22b1acdf8a2d72f6eb712932213804efd2ce30ca8d0b9b4295ac5", - "029a4d8e4c99a1199f67a25d79724e14f8e6992a0c8b8acf102682bd8f500ce0c1", - "02871b650700137defc5d34a11e56a4187f43e74bb078e147dd4048b8f3c81209f", - "02fc66cba365f9957bcb2030e89a57fb3019c57ea057978756c1d46d40dfdd4df0", - "03e3fe6124a4ea269224f5f43552250d627b4133cfd49d1f9e0283d0cd2fd209bc", - "02b95b000f087a97e988c24331bf6769b4a75e4b7d5d2a38105092a3aa841be33b", - "02a0aa9eac0e168f3474c2a0d04e50130833905740a5270e8a44d6c6e85cf6d98c", - }, - SecretaryGeneral: "02712da531804d1c38d159a901313239d2100dfb5b693d71a2f76b15dec3f8fc32", - MaxProposalTrackingCount: 128, - PowLimit: powLimit, - PowLimitBits: 0x1f0008ff, - TargetTimespan: 24 * time.Hour, // 24 hours - TargetTimePerBlock: 2 * time.Minute, // 2 minute - AdjustmentFactor: 4, // 25% less, 400% more - RewardPerBlock: RewardPerBlock(2 * time.Minute), - CoinbaseMaturity: 100, - MinTransactionFee: 100, - MinCrossChainTxFee: 10000, - CheckAddressHeight: 88812, - VoteStartHeight: 290000, - CRCOnlyDPOSHeight: 343400, - PublicDPOSHeight: 402680, - EnableActivateIllegalHeight: 439000, - CRVotingStartHeight: 537670, - CRCommitteeStartHeight: 658930, - CRClaimDPOSNodeStartHeight: 751400, - CRClaimDPOSNodePeriod: 720 * 14, - CheckRewardHeight: 436812, - VoteStatisticsHeight: 512881, - RegisterCRByDIDHeight: 598000, - ToleranceDuration: 5 * time.Second, - MaxInactiveRounds: 720 * 2, - InactivePenalty: 0, //there will be no penalty in this version - IllegalPenalty: 0, - DPoSV2IllegalPenalty: 20000000000, // todo complete me - EmergencyInactivePenalty: 0, //there will be no penalty in this version - GeneralArbiters: 24, - CandidateArbiters: 72, - PreConnectOffset: 360, - CRMemberCount: 12, - CRVotingPeriod: 30 * 720, - CRDutyPeriod: 365 * 720, - CRDepositLockupBlocks: 2160, - ProposalCRVotingPeriod: 7 * 720, - ProposalPublicVotingPeriod: 7 * 720, - CRAgreementCount: 8, - VoterRejectPercentage: 10, - CRCAppropriatePercentage: 10, - MaxCommitteeProposalCount: 128, - EnableUtxoDB: true, - EnableCORS: false, - WalletPath: "keystore.dat", - RPCServiceLevel: ConfigurationPermitted.String(), - NodeProfileStrategy: Balanced.String(), - MaxNodePerHost: 72, - CkpManager: checkpoint.NewManager(&checkpoint.Config{ - EnableHistory: true, - HistoryStartHeight: uint32(0), - NeedSave: true, - }), - TxCacheVolume: 100000, - CheckVoteCRCountHeight: 658930, - MaxCRAssetsAddressUTXOCount: 800, - MinCRAssetsAddressUTXOCount: 720, - CRAssetsRectifyTransactionHeight: 751400, - CRCProposalWithdrawPayloadV1Height: 751400, - CRCProposalV1Height: 751400, - RectifyTxFee: 10000, - RealWithdrawSingleFee: 10000, - NewP2PProtocolVersionHeight: 751400, - ChangeCommitteeNewCRHeight: 932530, - CustomIDProposalStartHeight: 932530, - NoCRCDPOSNodeHeight: 932530, - RevertToPOWStartHeight: 932530, - RandomCandidatePeriod: 36 * 10, - MaxInactiveRoundsOfRandomNode: 36 * 8, - MaxReservedCustomIDLength: 255, - CRCProposalDraftDataStartHeight: 1056600, - DPOSNodeCrossChainHeight: 2000000, // todo complete me - RevertToPOWNoBlockTime: 12 * 3600, - StopConfirmBlockTime: 11 * 3600, - HalvingRewardHeight: 1051200, // 4 * 365 * 720 - HalvingRewardInterval: 1051200, // 4 * 365 * 720 - NewELAIssuanceHeight: 919800, // 3.5 * 365 * 720 - SmallCrossTransferThreshold: 100000000, - ReturnDepositCoinFee: 100, - NewCrossChainStartHeight: 1032840, - ReturnCrossChainCoinStartHeight: 1032840, - ProhibitTransferToDIDHeight: 1032840, - DIDSideChainAddress: "XKUh4GLhFJiqAMTF6HyWQrV9pK9HcGUdfJ", - DPoSV2StartHeight: 2000000, // todo complete me - DPoSV2EffectiveVotes: 8000000000000, - DPoSV2RewardAccumulateAddress: StakeRewardAddress, - StakePool: StakePoolAddress, // todo complete me - DPoSV2DepositCoinMinLockTime: 7200, // todo complete me change to 216000 - DPoSV2MinVotesLockTime: 7200, // todo complete me - DPoSV2MaxVotesLockTime: 720000, // todo complete me - SchnorrStartHeight: 2000000, // todo complete me - CRDPoSNodeHotFixHeight: 0, - CrossChainMonitorStartHeight: 2000000, // todo complete me - CrossChainMonitorInterval: 100, // todo complete me - CRClaimPeriod: 720 * 14, // todo complete me - } -} - -// TestNet returns the network parameters for the test network. -func (p *Params) TestNet() *Params { - copy := *p - copy.Magic = 2018101 - copy.DefaultPort = 21338 - - copy.DNSSeeds = []string{ - "node-testnet-002.elastos.org:21338", - "node-testnet-003.elastos.org:21338", - "node-testnet-004.elastos.org:21338", - } - - copy.Foundation = testNetFoundation - copy.CRCAddress = testNetCRCAddress - copy.CRAssetsAddress = CRAssetsAddress - copy.CRExpensesAddress = CRCExpensesAddress - copy.DestroyELAAddress = DestroyELAAddress - copy.GenesisBlock = GenesisBlock(&testNetFoundation) - copy.DPoSMagic = 2019100 - copy.DPoSDefaultPort = 21339 - copy.OriginArbiters = []string{ - "03e333657c788a20577c0288559bd489ee65514748d18cb1dc7560ae4ce3d45613", - "02dd22722c3b3a284929e4859b07e6a706595066ddd2a0b38e5837403718fb047c", - "03e4473b918b499e4112d281d805fc8d8ae7ac0a71ff938cba78006bf12dd90a85", - "03dd66833d28bac530ca80af0efbfc2ec43b4b87504a41ab4946702254e7f48961", - "02c8a87c076112a1b344633184673cfb0bb6bce1aca28c78986a7b1047d257a448", - } - copy.CRCArbiters = []string{ - "03e435ccd6073813917c2d841a0815d21301ec3286bc1412bb5b099178c68a10b6", - "038a1829b4b2bee784a99bebabbfecfec53f33dadeeeff21b460f8b4fc7c2ca771", - "02435df9a4728e6250283cfa8215f16b48948d71936c4600b3a5b1c6fde70503ae", - "027d44ee7e7a6c6ff13a130d15b18c75a3b47494c3e54fcffe5f4b10e225351e09", - "02ad972fbfce4aaa797425138e4f3b22bcfa765ffad88b8a5af0ab515161c0a365", - "0373eeae2bac0f5f14373ca603fe2c9caa9c7a79c7793246cec415d005e2fe53c0", - "03503011cc4e44b94f73ed2c76c73182a75b4863f23d1e7083025eead945a8e764", - "0270b6880e7fab8d02bea7d22639d7b5e07279dd6477baa713dacf99bb1d65de69", - "030eed9f9c1d70307beba52ddb72a24a02582c0ee626ec93ee1dcef2eb308852dd", - "026bba43feb19ce5859ffcf0ce9dd8b9d625130b686221da8b445fa9b8f978d7b9", - "02bf9e37b3db0cbe86acf76a76578c6b17b4146df101ec934a00045f7d201f06dd", - "03111f1247c66755d369a8c8b3a736dfd5cf464ca6735b659533cbe1268cd102a9", - } - copy.SecretaryGeneral = "0349cb77a69aa35be0bcb044ffd41a616b8367136d3b339d515b1023cc0f302f87" - copy.MaxProposalTrackingCount = 128 - copy.CheckAddressHeight = 0 - copy.VoteStartHeight = 200000 - copy.CRCOnlyDPOSHeight = 246700 - copy.PublicDPOSHeight = 300000 - copy.CRVotingStartHeight = 436900 - copy.CRCommitteeStartHeight = 546500 - copy.CRClaimDPOSNodeStartHeight = 646700 - copy.CRClaimDPOSNodePeriod = 720 * 7 - copy.CRCProposalV1Height = 646700 - copy.NewP2PProtocolVersionHeight = 646700 - copy.CRAssetsRectifyTransactionHeight = 646700 - copy.CRCProposalWithdrawPayloadV1Height = 646700 - copy.EnableActivateIllegalHeight = 546500 - copy.CheckRewardHeight = 100 - copy.VoteStatisticsHeight = 0 - copy.RegisterCRByDIDHeight = 483500 - copy.EnableUtxoDB = true - copy.EnableCORS = false - copy.VoterRejectPercentage = 10 - copy.CRCAppropriatePercentage = 10 - copy.MaxCommitteeProposalCount = 128 - copy.MaxNodePerHost = 10 - copy.CheckVoteCRCountHeight = 546500 - copy.MaxCRAssetsAddressUTXOCount = 800 - copy.ChangeCommitteeNewCRHeight = 815060 - copy.CustomIDProposalStartHeight = 815060 - copy.InactivePenalty = 0 - copy.IllegalPenalty = 0 - copy.DPoSV2IllegalPenalty = 200 * 100000000 - copy.NoCRCDPOSNodeHeight = 815060 - copy.RandomCandidatePeriod = 36 * 10 - copy.MaxInactiveRoundsOfRandomNode = 36 * 8 - copy.DPOSNodeCrossChainHeight = 2000000 // todo complete me - copy.MaxReservedCustomIDLength = 255 - copy.RevertToPOWNoBlockTime = 12 * 3600 - copy.StopConfirmBlockTime = 11 * 3600 - copy.RevertToPOWStartHeight = 815060 - copy.HalvingRewardHeight = 877880 //767000 + 154 * 720 - copy.HalvingRewardInterval = 1051200 //4 * 365 * 720 - copy.NewELAIssuanceHeight = 774920 //767000 + 720 * 11 - copy.SmallCrossTransferThreshold = 100000000 - copy.ReturnDepositCoinFee = 100 - copy.NewCrossChainStartHeight = 807000 - copy.ReturnCrossChainCoinStartHeight = 807000 - copy.CRCProposalDraftDataStartHeight = 807000 - copy.ProhibitTransferToDIDHeight = 807000 - copy.DIDSideChainAddress = "XKUh4GLhFJiqAMTF6HyWQrV9pK9HcGUdfJ" - copy.DPoSV2StartHeight = 965800 + 720*3 - copy.DPoSV2EffectiveVotes = 3000 * 100000000 - copy.DPoSV2RewardAccumulateAddress = StakeRewardAddress - copy.StakePool = StakePoolAddress - copy.DPoSV2DepositCoinMinLockTime = 7200 * 3 - copy.DPoSV2MinVotesLockTime = 7200 - copy.DPoSV2MaxVotesLockTime = 720000 - copy.RealWithdrawSingleFee = 50000 - copy.SchnorrStartHeight = 965800 + 720*10 - copy.CRDPoSNodeHotFixHeight = 0 - copy.CrossChainMonitorStartHeight = 965800 + 720*3 - copy.CrossChainMonitorInterval = 12 - copy.CRClaimPeriod = 10080 - - return © -} - -// RegNet returns the network parameters for the test network. -func (p *Params) RegNet() *Params { - copy := *p - copy.Magic = 2018201 - copy.DefaultPort = 22338 - - copy.DNSSeeds = []string{ - "node-regtest-102.eadd.co:22338", - "node-regtest-103.eadd.co:22338", - "node-regtest-104.eadd.co:22338", - } - - copy.Foundation = testNetFoundation - copy.CRCAddress = testNetCRCAddress - copy.CRAssetsAddress = CRAssetsAddress - copy.CRExpensesAddress = CRCExpensesAddress - copy.DestroyELAAddress = DestroyELAAddress - copy.GenesisBlock = GenesisBlock(&testNetFoundation) - copy.DPoSMagic = 2019200 - copy.DPoSDefaultPort = 22339 - copy.OriginArbiters = []string{ - "03e333657c788a20577c0288559bd489ee65514748d18cb1dc7560ae4ce3d45613", - "02dd22722c3b3a284929e4859b07e6a706595066ddd2a0b38e5837403718fb047c", - "03e4473b918b499e4112d281d805fc8d8ae7ac0a71ff938cba78006bf12dd90a85", - "03dd66833d28bac530ca80af0efbfc2ec43b4b87504a41ab4946702254e7f48961", - "02c8a87c076112a1b344633184673cfb0bb6bce1aca28c78986a7b1047d257a448", - } - copy.CRCArbiters = []string{ - "0306e3deefee78e0e25f88e98f1f3290ccea98f08dd3a890616755f1a066c4b9b8", - "02b56a669d713db863c60171001a2eb155679cad186e9542486b93fa31ace78303", - "0250c5019a00f8bb4fd59bb6d613c70a39bb3026b87cfa247fd26f59fd04987855", - "02e00112e3e9defe0f38f33aaa55551c8fcad6aea79ab2b0f1ec41517fdd05950a", - "020aa2d111866b59c70c5acc60110ef81208dcdc6f17f570e90d5c65b83349134f", - "03cd41a8ed6104c1170332b02810237713369d0934282ca9885948960ae483a06d", - "02939f638f3923e6d990a70a2126590d5b31a825a0f506958b99e0a42b731670ca", - "032ade27506951c25127b0d2cb61d164e0bad8aec3f9c2e6785725a6ab6f4ad493", - "03f716b21d7ae9c62789a5d48aefb16ba1e797b04a2ec1424cd6d3e2e0b43db8cb", - "03488b0aace5fe5ee5a1564555819074b96cee1db5e7be1d74625240ef82ddd295", - "03c559769d5f7bb64c28f11760cb36a2933596ca8a966bc36a09d50c24c48cc3e8", - "03b5d90257ad24caf22fa8a11ce270ea57f3c2597e52322b453d4919ebec4e6300", - } - copy.SecretaryGeneral = "0349cb77a69aa35be0bcb044ffd41a616b8367136d3b339d515b1023cc0f302f87" - copy.MaxProposalTrackingCount = 128 - copy.CheckAddressHeight = 0 - copy.VoteStartHeight = 170000 - copy.CRCOnlyDPOSHeight = 211000 - copy.PublicDPOSHeight = 231500 - copy.CRVotingStartHeight = 292000 - copy.CRCommitteeStartHeight = 442000 - copy.CRClaimDPOSNodeStartHeight = 532650 - copy.CRClaimDPOSNodePeriod = 720 - copy.CRCProposalV1Height = 530000 - copy.NewP2PProtocolVersionHeight = 531030 - copy.CRAssetsRectifyTransactionHeight = 532650 - copy.CRCProposalWithdrawPayloadV1Height = 532650 - copy.EnableActivateIllegalHeight = 256000 - copy.CheckRewardHeight = 280000 - copy.VoteStatisticsHeight = 0 - copy.RegisterCRByDIDHeight = 393000 - - copy.EnableUtxoDB = true - copy.EnableCORS = false - copy.VoterRejectPercentage = 10 - copy.CRCAppropriatePercentage = 10 - copy.MaxCommitteeProposalCount = 128 - copy.MaxNodePerHost = 10 - copy.CheckVoteCRCountHeight = 435000 - copy.MaxCRAssetsAddressUTXOCount = 1440 - copy.ChangeCommitteeNewCRHeight = 706240 - copy.CustomIDProposalStartHeight = 706240 - copy.IllegalPenalty = 0 - copy.DPoSV2IllegalPenalty = 20000000000 - copy.InactivePenalty = 0 - copy.NoCRCDPOSNodeHeight = 706240 - copy.RandomCandidatePeriod = 36 * 10 - copy.MaxInactiveRoundsOfRandomNode = 36 * 8 - copy.DPOSNodeCrossChainHeight = 2000000 // todo complete me - copy.MaxReservedCustomIDLength = 255 - copy.RevertToPOWNoBlockTime = 12 * 3600 - copy.StopConfirmBlockTime = 11 * 3600 - copy.RevertToPOWStartHeight = 706240 - copy.HalvingRewardHeight = 801240 //690360 + 154 * 720 - copy.HalvingRewardInterval = 1051200 //4 * 365 * 720 - copy.NewELAIssuanceHeight = 691740 //690300 + 720 * 2 - copy.SmallCrossTransferThreshold = 100000000 - copy.ReturnDepositCoinFee = 100 - copy.NewCrossChainStartHeight = 730000 - copy.ReturnCrossChainCoinStartHeight = 730000 - copy.CRCProposalDraftDataStartHeight = 730000 - copy.ProhibitTransferToDIDHeight = 730000 - copy.DIDSideChainAddress = "XKUh4GLhFJiqAMTF6HyWQrV9pK9HcGUdfJ" - copy.DPoSV2StartHeight = 875544 + 720*2 - copy.DPoSV2EffectiveVotes = 300000000000 - copy.DPoSV2RewardAccumulateAddress = StakeRewardAddress - copy.StakePool = StakePoolAddress - copy.DPoSV2DepositCoinMinLockTime = 7200 * 3 - copy.DPoSV2MinVotesLockTime = 7200 - copy.DPoSV2MaxVotesLockTime = 720000 - copy.RealWithdrawSingleFee = 10000 - copy.SchnorrStartHeight = 875544 + 720*5 - copy.CRDPoSNodeHotFixHeight = 0 - copy.CrossChainMonitorStartHeight = 875544 + 720*2 - copy.CrossChainMonitorInterval = 12 - copy.CRClaimPeriod = 10080 - - return © -} - -// InstantBlock returns the network parameters for generate instant block. -func (p *Params) InstantBlock() *Params { - copy := *p - copy.PowLimitBits = 0x207fffff - copy.TargetTimespan = 10 * time.Second - copy.TargetTimePerBlock = 1 * time.Second - return © -} - -type Params struct { - // Magic defines the magic number of the peer-to-peer network. - Magic uint32 - - // DefaultPort defines the default peer-to-peer port for the network. - DefaultPort uint16 - - // PrintLevel defines the level to print log. - PrintLevel uint32 - - // DNSSeeds defines a list of DNS seeds for the network to discover peers. - DNSSeeds []string - - // The interface/port to listen for connections. - ListenAddrs []string - - // PermanentPeers defines peers seeds for node to initialize p2p connection. - PermanentPeers []string - - // Foundation defines the foundation address which receiving mining - // rewards. - Foundation common.Uint168 - - // CRCAddress defines the CRC address which receiving mining rewards. - CRCAddress common.Uint168 - - // CRAssetsAddress defines the CR assets address address. - CRAssetsAddress common.Uint168 - - // CRExpensesAddress defines the CR committee address which receiving - // appropriation from CR assets address. - CRExpensesAddress common.Uint168 - - // DestroyELAAddress defines address which receiving destroyed ELA. - DestroyELAAddress common.Uint168 - - // GenesisBlock defines the first block of the chain. - GenesisBlock *types.Block - - // powLimit defines the highest allowed proof of work value for a block - // as a uint256. - PowLimit *big.Int - - // PowLimitBits defines the highest allowed proof of work value for a - // block in compact form. - PowLimitBits uint32 - - // TargetTimespan is the desired amount of time that should elapse - // before the block difficulty requirement is examined to determine how - // it should be changed in order to maintain the desired block - // generation rate. - TargetTimespan time.Duration - - // TargetTimePerBlock is the desired amount of time to generate each - // block. - TargetTimePerBlock time.Duration - - // AdjustmentFactor is the adjustment factor used to limit the minimum - // and maximum amount of adjustment that can occur between difficulty - // retargets. - AdjustmentFactor int64 - - // RewardPerBlock is the reward amount per block. - RewardPerBlock common.Fixed64 - - // NewRewardPerBlock is the reward amount per block. - NewRewardPerBlock common.Fixed64 - - // CoinbaseMaturity is the number of blocks required before newly mined - // coins (coinbase transactions) can be spent. - CoinbaseMaturity uint32 - - // Disable transaction filter supports, include bloom filter tx type filter - // etc. - DisableTxFilters bool - - // MinTransactionFee defines the minimum fee of a transaction. - MinTransactionFee common.Fixed64 - - // MinCrossChainTxFee defines the min fee of cross chain transaction - MinCrossChainTxFee common.Fixed64 - - // OriginArbiters defines the original arbiters producing the block. - OriginArbiters []string - - // CheckAddressHeight defines the height begin to check output hash. - CheckAddressHeight uint32 - - // VoteStartHeight indicates the height of starting register producer and - // vote related. - VoteStartHeight uint32 - - // CRCOnlyDPOSHeight (H1) indicates the height of DPOS consensus begins with - // only CRC producers participate in producing blocks. - CRCOnlyDPOSHeight uint32 - - // PublicDPOSHeight (H2) indicates the height when public registered and - // elected producers participate in DPOS consensus. - PublicDPOSHeight uint32 - - // NoCRCDPOSNodeHeight indicates the height when there is no DPOS node of CRC. - NoCRCDPOSNodeHeight uint32 - - // CRVotingStartHeight defines the height of CR voting started. - CRVotingStartHeight uint32 - - // NewCrossChainStartHeight defines the height of new cross chain transaction started. - NewCrossChainStartHeight uint32 - - // CRCommitteeStartHeight defines the height of CR Committee started. - CRCommitteeStartHeight uint32 - - // CRClaimDPOSNodeStartHeight defines the height of CR claim DPOS node started. - CRClaimDPOSNodeStartHeight uint32 - - // CRClaimDPOSNodePeriod defines the period of CR claim DPOS node. - CRClaimDPOSNodePeriod uint32 - - // PublicDPOSHeight defines the start height to enable activate illegal - // producer though activate tx. - EnableActivateIllegalHeight uint32 - - // CheckRewardHeight defines the height to check reward in coin base - // with new check function. - CheckRewardHeight uint32 - - // VoteStatisticsHeight defines the height to deal with block with vote - // statistics error. - VoteStatisticsHeight uint32 - - // RegisterCRByDIDHeight defines the height to support register and update - // CR by CID and CID. - RegisterCRByDIDHeight uint32 - - //Prohibit transfers to did height - ProhibitTransferToDIDHeight uint32 - - //did side chain address - DIDSideChainAddress string - - // CRCArbiters defines the fixed CRC arbiters producing the block. - CRCArbiters []string - - // DPoSMagic defines the magic number used in the DPoS network. - DPoSMagic uint32 - - // DPoSIPAddress defines the IP address for the DPoS network. - DPoSIPAddress string - - // DPoSDefaultPort defines the default port for the DPoS network. - DPoSDefaultPort uint16 - - // PreConnectOffset defines the offset blocks to pre-connect to the block - // producers. - PreConnectOffset uint32 - - // GeneralArbiters defines the number of general(no-CRC) arbiters. - GeneralArbiters int - - // CandidateArbiters defines the number of needed candidate arbiters. - CandidateArbiters int - - // ToleranceDuration defines the tolerance duration of the DPoS consensus. - ToleranceDuration time.Duration - - // MaxInactiveRounds defines the maximum inactive rounds before producer - // takes penalty. - MaxInactiveRounds uint32 - - // MaxInactiveRoundsOfRandomNode defines the maximum inactive rounds before - // the producer at random takes penalty. - MaxInactiveRoundsOfRandomNode uint32 - - // DPOSNodeCrossChainHeight defines the height at which not only CR members - // are responsible for working across the chain. - DPOSNodeCrossChainHeight uint32 - - // InactivePenalty defines the penalty amount the producer takes. - InactivePenalty common.Fixed64 - - // InactivePenalty defines the penalty amount the producer takes. - IllegalPenalty common.Fixed64 - - // DPoSV2InactivePenalty defines the penalty amount the producer takes. - DPoSV2IllegalPenalty common.Fixed64 - - // EmergencyInactivePenalty defines the penalty amount the emergency - // producer takes. - EmergencyInactivePenalty common.Fixed64 - - // CRMemberCount defines the number of CR committee members - CRMemberCount uint32 - - // CRVotingPeriod defines the duration of voting period which measured by - // block height - CRVotingPeriod uint32 - - // CRDutyPeriod defines the duration of a normal duty period which - // measured by block height - CRDutyPeriod uint32 - - // CRClaimPeriod defines the duration of CR claim DPoS node period which - // measured by block height - CRClaimPeriod uint32 - - // DepositLockupBlocks indicates how many blocks need to wait when cancel - // producer or CRC was triggered, and can submit return deposit coin request - CRDepositLockupBlocks uint32 - - // ProposalCRVotingPeriod defines the duration of CR voting about a proposal - ProposalCRVotingPeriod uint32 - - // ProposalPublicVotingPeriod defines the duration of all voters send - // reject vote about a proposal - ProposalPublicVotingPeriod uint32 - - // CRAgreementCount defines minimum count to let a registered proposal - // transfer to CRAgreed state. - CRAgreementCount uint32 - - // VoterRejectPercentage defines percentage about voters reject a proposal. - VoterRejectPercentage float64 - - // CRCAppropriatePercentage defines percentage about CRC appropriation. - CRCAppropriatePercentage float64 - - //MaxCommitteeProposalCount defines per committee max proposal count - MaxCommitteeProposalCount uint32 - - // SecretaryGeneral defines the secretary general of CR by public key. - SecretaryGeneral string - - // MaxProposalTrackingCount defines the max count of CRC proposal tracking - // transaction. - MaxProposalTrackingCount uint8 - - // CkpManager holds checkpoints save automatically. - CkpManager *checkpoint.Manager - - // EnableUtxoDB indicate whether to enable utxo database. - EnableUtxoDB bool - - // Enable cors for http server. - EnableCORS bool - - // WalletPath defines the wallet path used by DPoS arbiters and CR members. - WalletPath string - - // RPCServiceLevel defines level of service provide to client. - RPCServiceLevel string - - // NodeProfileStrategy defines strategy about node profiling. - NodeProfileStrategy string - - // TxCacheVolume defines the default volume of the transaction cache. - TxCacheVolume uint32 - - //MaxNodePerHost defines max nodes that one host can establish. - MaxNodePerHost uint32 - - // CheckVoteCRCountHeight defines the height to check count of vote CR. - CheckVoteCRCountHeight uint32 - - // MaxCRAssetsAddressUTXOCount defines the max UTXOs count of CRFoundation - // address. - MaxCRAssetsAddressUTXOCount uint32 - - // MinCRAssetsAddressUTXOCount defines the min UTXOs count of CRFoundation - // address. - MinCRAssetsAddressUTXOCount uint32 - - // CRAssetsRectifyTransactionHeight defines the CR rectify transaction start height - CRAssetsRectifyTransactionHeight uint32 - - // CRCProposalWithdrawPayloadV1Height defines the CRC proposal withdraw payload height - CRCProposalWithdrawPayloadV1Height uint32 - - // CRCProposalV1Height defines the height to support ChangeProposalOwner, - // CloseProposal and SecretaryGeneral proposal. - CRCProposalV1Height uint32 - - // RectifyTxFee defines the fee of cr rectify transaction. - RectifyTxFee common.Fixed64 - - // RealWithdrawSingleFee defines the single fee of cr real proposal withdraw transaction. - RealWithdrawSingleFee common.Fixed64 - - // NewP2PProtocolVersionHeight defines the new p2p protocol version message height. - NewP2PProtocolVersionHeight uint64 - - // ChangeCommitteeNewCRHeight defines the new arbiter logic after change committee. - ChangeCommitteeNewCRHeight uint32 - - // CRCProposalDraftDataStartHeight defines the proposal draft data start height. - CRCProposalDraftDataStartHeight uint32 - - // CustomIDProposalStartHeight defines the height to allow custom ID related transaction. - CustomIDProposalStartHeight uint32 - - // RandomCandidatePeriod defines the period to get a candidate as DPOS node at random. - RandomCandidatePeriod uint32 - - // MaxReservedCustomIDLength defines the max length of reserved custom id. - MaxReservedCustomIDLength uint32 - - // RevertToPOWInterval defines how long time does it take to revert to POW mode. - RevertToPOWNoBlockTime int64 - - // StopConfirmBlockTime defines how long time dose it take before stop confirm block. - StopConfirmBlockTime int64 - - // RevertToPOWStartHeight defines the start height to allow to revert to POW mode. - RevertToPOWStartHeight uint32 - - // HalvingRewardHeight represents the height of halving reward - HalvingRewardHeight uint32 - - // HalvingRewardInterval represents the interval of halving reward - HalvingRewardInterval uint32 - - // NewELAIssuanceHeight represents the new issuance ELA amount after proposal #1631 - NewELAIssuanceHeight uint32 - - // SMALLCrossTransferThreshold indicates the minimum amount consider as Small transfer - SmallCrossTransferThreshold common.Fixed64 - - // ReturnDepositCoinFee indicates the fee the - ReturnDepositCoinFee common.Fixed64 - - // ReturnCrossChainCoinStartHeight indicates the start height of - // ReturnCroossChainDepositCoin transaction - ReturnCrossChainCoinStartHeight uint32 - - // DPoSV2StartHeight defines the start height of dpos 2.0. - DPoSV2StartHeight uint32 - - // DPoSV2EffectiveVotes defines the votes which producer will become a dposV2 effective node - DPoSV2EffectiveVotes common.Fixed64 - - // DPoSV2RewardAccumulateAddress defines the dposv2 reward accumulating address - DPoSV2RewardAccumulateAddress common.Uint168 - - // ExchangeVotes address of votes - StakePool common.Uint168 - - // minimum lock time of DPoS V2 deposit coin - DPoSV2DepositCoinMinLockTime uint32 - - // minimum lock time of DPoS V2 votes - DPoSV2MinVotesLockTime uint32 - - // max lock time of DPoS V2 votes - DPoSV2MaxVotesLockTime uint32 - - // SchnorrStartHeight indicates the start height of schnorr - SchnorrStartHeight uint32 - - // CRDPoSNodeHotFixHeight indicates the hot fix start height of CR DPoS node - CRDPoSNodeHotFixHeight uint32 - - // CrossChainMonitorStartHeight indicates the monitor height of cr cross chain arbitration - CrossChainMonitorStartHeight uint32 - - // CrossChainMonitorInterval indicates the interval value of cr cross chain arbitration - CrossChainMonitorInterval uint32 -} - -// RewardPerBlock calculates the reward for each block by a specified time -// duration. -func RewardPerBlock(targetTimePerBlock time.Duration) common.Fixed64 { - blockGenerateInterval := int64(targetTimePerBlock / time.Second) - generatedBlocksPerYear := 365 * 24 * 60 * 60 / blockGenerateInterval - return common.Fixed64(float64(inflationPerYear) / float64(generatedBlocksPerYear)) -} - -// newRewardPerBlock calculates the reward for each block by a specified time -// duration. -func (p *Params) newRewardPerBlock(targetTimePerBlock time.Duration, height uint32) common.Fixed64 { - blockGenerateInterval := int64(targetTimePerBlock / time.Second) - generatedBlocksPerYear := 365 * 24 * 60 * 60 / blockGenerateInterval - factor := uint32(1) - if height >= p.HalvingRewardHeight { - factor = 2 + (height-p.HalvingRewardHeight)/p.HalvingRewardInterval - } - - return common.Fixed64(float64(newInflationPerYear) / float64(generatedBlocksPerYear) / math.Pow(2, float64(factor-1))) -} - -// GenesisBlock creates a genesis block by the specified foundation address. -// The genesis block goes different because the foundation address in each -// network is different. -func GenesisBlock(foundation *common.Uint168) *types.Block { - - // elaAsset is the transaction that create and register the ELA coin. - elaAsset := functions.CreateTransaction( - 0, - common2.RegisterAsset, - 0, - &payload.RegisterAsset{ - Asset: payload.Asset{ - Name: "ELA", - Precision: ELAPrecision, - AssetType: 0x00, - }, - Amount: 0 * 100000000, - Controller: common.Uint168{}, - }, - []*common2.Attribute{}, - []*common2.Input{}, - []*common2.Output{}, - 0, - []*program.Program{}, - ) - - coinBase := functions.CreateTransaction( - 0, - common2.CoinBase, - payload.CoinBaseVersion, - &payload.CoinBase{}, - []*common2.Attribute{&attrNonce}, - []*common2.Input{ - { - Previous: common2.OutPoint{ - TxID: zeroHash, - Index: 0x0000, - }, - Sequence: 0x00000000, - }, - }, - []*common2.Output{ - { - AssetID: ELAAssetID, - Value: 3300 * 10000 * 100000000, - ProgramHash: *foundation, - }, - }, - 0, - []*program.Program{}, - ) - - merkleRoot, _ := crypto.ComputeRoot([]common.Uint256{coinBase.Hash(), - ELAAssetID}) - - return &types.Block{ - Header: common2.Header{ - Version: 0, - Previous: zeroHash, - MerkleRoot: merkleRoot, - Timestamp: uint32(genesisTime.Unix()), - Bits: 0x1d03ffff, - Nonce: 2083236893, - Height: 0, - }, - Transactions: []interfaces.Transaction{coinBase, elaAsset}, - } -} - -func (p *Params) GetBlockReward(height uint32) (rewardPerBlock common.Fixed64) { - if height < p.NewELAIssuanceHeight { - rewardPerBlock = p.RewardPerBlock - } else { - rewardPerBlock = p.newRewardPerBlock(2*time.Minute, height) - } - return -} diff --git a/common/config/params_test.go b/common/config/params_test.go deleted file mode 100644 index 6ef080ebf..000000000 --- a/common/config/params_test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2017-2020 The Elastos Foundation -// Use of this source code is governed by an MIT -// license that can be found in the LICENSE file. -// - -package config - -// -//import ( -// "testing" -// "time" -// -// "github.com/stretchr/testify/assert" -//) -// -//func TestGenesisBlock(t *testing.T) { -// block := GenesisBlock(&mainNetFoundation) -// assert.Equal(t, len(block.Transactions), 2) -// -// genesisHash := block.Hash().String() -// assert.Equal(t, "8d7014f2f941caa1972c8033b2f0a860ec8d4938b12bae2c62512852a558f405", genesisHash) -// -// genesisHash = GenesisBlock(&testNetFoundation).Hash().String() -// assert.Equal(t, "b3314f465ea5556d570bcc473d59a0855b4405a25b1ea0c957c81b2920be1864", genesisHash) -// -// date := time.Date(2017, time.December, 22, 10, -// 0, 0, 0, time.UTC).Unix() -// dateUnix := time.Unix(time.Date(2017, time.December, 22, 10, -// 0, 0, 0, time.UTC).Unix(), 0).Unix() -// -// dateTime, err := time.Parse(time.RFC3339, "2017-12-22T10:00:00Z") -// assert.NoError(t, err) -// assert.Equal(t, date, dateUnix) -// assert.Equal(t, date, dateTime.Unix()) -//} -// -//func TestFoundation(t *testing.T) { -// address, _ := mainNetFoundation.ToAddress() -// assert.Equal(t, "8VYXVxKKSAxkmRrfmGpQR2Kc66XhG6m3ta", address) -// -// address, _ = testNetFoundation.ToAddress() -// assert.Equal(t, "8ZNizBf4KhhPjeJRGpox6rPcHE5Np6tFx3", address) -//} diff --git a/common/config/settings/settings.go b/common/config/settings/settings.go index f76784fef..29e7c7c89 100644 --- a/common/config/settings/settings.go +++ b/common/config/settings/settings.go @@ -6,1306 +6,86 @@ package settings import ( - "bytes" - "encoding/json" "errors" "fmt" - "io/ioutil" - "net" - "os" - "strconv" + "path/filepath" "strings" - "time" - cmdcom "github.com/elastos/Elastos.ELA/cmd/common" - "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" - transaction2 "github.com/elastos/Elastos.ELA/core/transaction" + "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/elanet/pact" - "github.com/elastos/Elastos.ELA/utils/elalog" - "github.com/elastos/Elastos.ELA/utils/gpath" - "github.com/urfave/cli" + "github.com/fungolang/screw" + "github.com/spf13/viper" ) -const ( - // cmdValueSplitter defines the splitter to split raw string into a - // string array - cmdValueSplitter = "," - - // cmdNameSplitter defines the splitter to split raw string into a - // string array - commandNameSplitter = "," -) - -var ( - // defaultConfig defines the default parameters to running a ELA node. - defaultConfig = config.Configuration{ - PrintLevel: uint32(elalog.LevelInfo), - } -) - -type settingItem struct { - Flag cli.Flag - DefaultValue interface{} - ConfigPath string - ParamName string - ConfigSetter func(string, *config.Params, *config.Configuration) error - CliSetter func(interface{}, *config.Params, *config.Configuration) error -} - -func (s *settingItem) TryInitValue(params *config.Params, - conf *config.Configuration, c *cli.Context) error { - - if s.Flag != nil && c.IsSet(GetFullCommandName(s.Flag)) { - value, err := s.getCliValue(c) - if err != nil { - return err - } - - if s.CliSetter != nil { - return s.CliSetter(value, params, conf) - } else { - return gpath.Set(params, value, s.ParamName) - } - } else { - needSet, err := s.notDefault(conf) - if err != nil { - return err - } - if needSet { - return s.initByConfig(params, conf) - } - } - return nil -} - -func (s *settingItem) getCliValue(c *cli.Context) (interface{}, error) { - value := c.String(GetFullCommandName(s.Flag)) - switch s.DefaultValue.(type) { - case common.Fixed64: - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return nil, err - } - return common.Fixed64(v), nil - case time.Duration: - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return nil, err - } - return time.Duration(v), nil - case uint16: - v, err := strconv.ParseInt(value, 10, 16) - if err != nil { - return nil, err - } - return uint16(v), nil - case uint32: - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return nil, err - } - return uint32(v), nil - case int: - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return nil, err - } - return int(v), nil - case int64: - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return nil, err - } - return v, nil - case uint64: - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return nil, err - } - return v, nil - case bool: - v, err := strconv.ParseBool(value) - if err != nil { - return nil, err - } - return v, nil - case string: - return value, nil - case []string: - return strings.Split(value, cmdValueSplitter), nil - default: - return nil, errors.New("unknown value type") - } -} - -func (s *settingItem) notDefault(conf *config.Configuration) (bool, error) { - if len(s.ConfigPath) == 0 { - return false, nil - } - value, err := gpath.At(conf, s.ConfigPath) - if err != nil { - return false, err - } - - if gpath.IsNil(value) { - return false, nil - } - return !gpath.Equal(s.DefaultValue, value), nil -} - -func (s *settingItem) initByConfig(params *config.Params, - conf *config.Configuration) error { - if s.ConfigSetter != nil { - return s.ConfigSetter(s.ConfigPath, params, conf) - } else { - value, err := gpath.At(conf, s.ConfigPath) - if err != nil { - return err - } - return gpath.Set(params, value, s.ParamName) - } -} - type Settings struct { - items []settingItem - conf *config.Configuration - params *config.Params - context *cli.Context -} - -// Config return the loaded config parameters to running the ELA node. -func (s *Settings) Config() *config.Configuration { - return s.conf -} - -// Params return a pointer to the parameters specific to the currently -// active ELA network. -func (s *Settings) Params() *config.Params { - return s.params + viper *viper.Viper + params *config.Configuration } -func (s *Settings) SetContext(c *cli.Context) { - s.context = c +func (s *Settings) Viper() *viper.Viper { + return s.viper } -func (s *Settings) Flags() []cli.Flag { - result := make([]cli.Flag, 0, len(s.items)) - for _, v := range s.items { - if v.Flag != nil { - result = append(result, v.Flag) - } +func (s *Settings) loadConfigFile(files string, cfg config.Config) (*config.Configuration, error) { + paths, fileName := filepath.Split(files) + fileExt := filepath.Ext(files) + s.viper.AddConfigPath("./" + paths) + s.viper.SetConfigName(strings.TrimSuffix(fileName, fileExt)) + s.viper.SetConfigType(strings.TrimPrefix(fileExt, ".")) + if err := s.viper.ReadInConfig(); err != nil { + return &config.DefaultParams, errors.New("cannot read configuration" + err.Error()) } - return result -} - -func (s *Settings) InitParamsValue() { - if err := s.initNetSetting(); err != nil { - cmdcom.PrintErrorMsg(err.Error()) - os.Exit(1) + if err := s.viper.Unmarshal(&cfg); err != nil { + return &config.DefaultParams, errors.New("configuration files can't be loaded" + err.Error()) } - - for _, v := range s.items { - if err := v.TryInitValue(s.params, s.conf, s.context); err != nil { - cmdcom.PrintErrorMsg(err.Error()) - os.Exit(1) - } - } -} - -func (s *Settings) Add(item *settingItem) { - s.items = append(s.items, *item) + return cfg.Configuration, nil } -func (s *Settings) initNetSetting() (err error) { +func (s *Settings) SetupConfig() *config.Configuration { // Initialize functions - functions.GetTransactionByTxType = transaction2.GetTransaction - functions.GetTransactionByBytes = transaction2.GetTransactionByBytes - functions.CreateTransaction = transaction2.CreateTransaction - functions.GetTransactionParameters = transaction2.GetTransactionparameters - - // Initialize default parameters - config.DefaultParams = config.GetDefaultParams() + functions.GetTransactionByTxType = transaction.GetTransaction + functions.GetTransactionByBytes = transaction.GetTransactionByBytes + functions.CreateTransaction = transaction.CreateTransaction + functions.GetTransactionParameters = transaction.GetTransactionparameters - var testNet, regTest bool - switch strings.ToLower(s.conf.ActiveNet) { - case "testnet", "test": - testNet = true - case "regnet", "reg": - regTest = true - default: - testNet = false - regTest = false + configFile := config.ConfigFile + params := config.Config{ + Configuration: &config.DefaultParams, } - - if s.context.IsSet(GetFullCommandName(cmdcom.TestNetFlag)) { - if testNet, err = strconv.ParseBool(s.context.String( - GetFullCommandName(cmdcom.TestNetFlag))); err != nil { - return - } - } else if s.context.IsSet(GetFullCommandName(cmdcom.RegTestFlag)) { - if regTest, err = strconv.ParseBool(s.context.String( - GetFullCommandName(cmdcom.RegTestFlag))); err != nil { - return - } + // set mainNet params + conf, err := s.loadConfigFile(configFile, params) + if err != nil { + fmt.Println("loadConfigFile err", err.Error()) } - if testNet { - if err := s.testNetDefault(s.conf); err != nil { - return err - } - s.params = config.DefaultParams.TestNet() - } else if regTest { - if err := s.regNetDefault(s.conf); err != nil { - return err + // switch activeNet params + switch strings.ToLower(conf.ActiveNet) { + case "testnet", "test": + testnet := config.Config{ + Configuration: params.TestNet(), } - s.params = config.DefaultParams.RegNet() - } else { - if err := s.mainNetDefault(s.conf); err != nil { - return err + conf, err = s.loadConfigFile(configFile, testnet) + case "regnet", "regtest", "reg": + regnet := config.Config{ + Configuration: params.RegNet(), } - s.params = &config.DefaultParams - } - - if s.conf.MaxBlockSize > 0 { - pact.MaxBlockContextSize = s.conf.MaxBlockSize - } else if !testNet { - pact.MaxBlockContextSize = 2000000 - } - - if s.conf.MaxBlockHeaderSize > 0 { - pact.MaxBlockHeaderSize = s.conf.MaxBlockHeaderSize - } - - if s.conf.MaxTxPerBlock > 0 { - pact.MaxTxPerBlock = s.conf.MaxTxPerBlock - } else { - pact.MaxTxPerBlock = 10000 + conf, err = s.loadConfigFile(configFile, regnet) } - config.Parameters = s.conf - instantBlock := s.conf.PowConfiguration.InstantBlock - if s.context.IsSet(GetFullCommandName(cmdcom.InstantBlockFlag)) { - if instantBlock, err = strconv.ParseBool(s.context.String( - GetFullCommandName(cmdcom.InstantBlockFlag))); err != nil { - return - } - } + screw.Bind(conf) + instantBlock := conf.PowConfiguration.InstantBlock if instantBlock { - s.params = s.params.InstantBlock() + conf = conf.InstantBlock() } - return + config.Parameters = conf + return conf } func NewSettings() *Settings { - result := &Settings{ - items: make([]settingItem, 0), - } - - result.Add(&settingItem{ - Flag: cmdcom.MagicFlag, - DefaultValue: uint32(0), - ConfigPath: "Magic", - ParamName: "Magic"}) - - result.Add(&settingItem{ - Flag: cmdcom.PrintLevelFlag, - DefaultValue: uint32(0), - ConfigPath: "PrintLevel", - ParamName: "PrintLevel"}) - - result.Add(&settingItem{ - Flag: cmdcom.PortFlag, - DefaultValue: uint16(0), - ConfigPath: "NodePort", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - if conf.NodePort > 0 { - params.DefaultPort = conf.NodePort - } - return nil - }, - ParamName: "DefaultPort"}) - - result.Add(&settingItem{ - Flag: cmdcom.PeersFlag, - DefaultValue: []string{}, - ConfigPath: "PermanentPeers", - ParamName: "PermanentPeers"}) - - result.Add(&settingItem{ - Flag: cmdcom.DnsSeedFlag, - DefaultValue: []string{}, - ConfigPath: "DNSSeeds", - ParamName: "DNSSeeds"}) - - result.Add(&settingItem{ - Flag: cmdcom.AccountWalletFlag, - DefaultValue: "", - ConfigPath: "WalletPath", - ParamName: "WalletPath"}) - - result.Add(&settingItem{ - Flag: cmdcom.EnableDnsFlag, - DefaultValue: false, - ConfigPath: "DisableDNS", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - params.DNSSeeds = nil - return nil - }, - CliSetter: func(value interface{}, params *config.Params, - conf *config.Configuration) error { - disable, ok := value.(bool) - if !ok { - return errors.New("invalid dns seeds switch setting") - } - if disable { - params.DNSSeeds = nil - } - return nil - }, - ParamName: ""}) - - result.Add(&settingItem{Flag: cmdcom.MinTxFeeFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "MinCrossChainTxFee", - ParamName: "MinCrossChainTxFee"}) - - initFoundation := func(addr string, params *config.Params) error { - foundation, err := common.Uint168FromAddress(addr) - if err != nil { - return errors.New("invalid foundation address") - } - params.Foundation = *foundation - params.GenesisBlock = config.GenesisBlock(foundation) - return nil + settings := &Settings{ + viper: viper.New(), } - result.Add(&settingItem{ - Flag: cmdcom.DIDSideChainAddressFlag, - DefaultValue: "", - ConfigPath: "DIDSideChainAddress", - ParamName: "DIDSideChainAddress"}) - result.Add(&settingItem{ - Flag: cmdcom.FoundationAddrFlag, - DefaultValue: "", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - return initFoundation(conf.FoundationAddress, params) - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - value, ok := i.(string) - if !ok { - return errors.New("unknown foundation address type") - } - return initFoundation(value, params) - }, - ConfigPath: "FoundationAddress", - ParamName: "Foundation"}) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: "", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - crcAddress, err := common.Uint168FromAddress(conf.CRConfiguration.CRCAddress) - if err != nil { - return errors.New("invalid CRC address") - } - params.CRCAddress = *crcAddress - return nil - }, - ConfigPath: "CRConfiguration.CRCAddress", - ParamName: "CRCAddress"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRAssetsAddressFlag, - DefaultValue: "", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - crAssetsAddress, err := common.Uint168FromAddress(conf.CRConfiguration.CRAssetsAddress) - if err != nil { - return errors.New("invalid CR assets address") - } - params.CRAssetsAddress = *crAssetsAddress - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - value, ok := i.(string) - if !ok { - return errors.New("unknown foundation address type") - } - crAssetsAddress, err := common.Uint168FromAddress(value) - if err != nil { - return errors.New("invalid CR assets address") - } - params.CRAssetsAddress = *crAssetsAddress - return nil - }, - ConfigPath: "CRConfiguration.CRAssetsAddress", - ParamName: "CRAssetsAddress"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRExpensesAddressFlag, - DefaultValue: "", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - CRExpensesAddress, err := common.Uint168FromAddress(conf.CRConfiguration.CRExpensesAddress) - if err != nil { - return errors.New("invalid CR expenses address") - } - params.CRExpensesAddress = *CRExpensesAddress - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - value, ok := i.(string) - if !ok { - return errors.New("unknown foundation address type") - } - CRExpensesAddress, err := common.Uint168FromAddress(value) - if err != nil { - return errors.New("invalid CR expenses address") - } - params.CRExpensesAddress = *CRExpensesAddress - return nil - }, - ConfigPath: "CRConfiguration.CRExpensesAddress", - ParamName: "CRExpensesAddress"}) - - result.Add(&settingItem{ - Flag: cmdcom.VoteStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "VoteStartHeight", - ParamName: "VoteStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CheckAddressHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CheckAddressHeight", - ParamName: "CheckAddressHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CheckRewardHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CheckRewardHeight", - ParamName: "CheckRewardHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCOnlyDPOSHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CRCOnlyDPOSHeight", - ParamName: "CRCOnlyDPOSHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.PublicDPOSHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "PublicDPOSHeight", - ParamName: "PublicDPOSHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.IllegalPenaltyFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "DPoSConfiguration.IllegalPenalty", - ParamName: "IllegalPenalty"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSV2IllegalPenaltyFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "DPoSConfiguration.DPoSV2IllegalPenalty", - ParamName: "DPoSV2IllegalPenalty"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCommitteeStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRCommitteeStartHeight", - ParamName: "CRCommitteeStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRClaimDPOSNodeStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRClaimDPOSNodeStartHeight", - ParamName: "CRClaimDPOSNodeStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRClaimDPOSNodePeriodFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRClaimDPOSNodePeriod", - ParamName: "CRClaimDPOSNodePeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRVotingStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRVotingStartHeight", - ParamName: "CRVotingStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.MaxCommitteeProposalCount, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.MaxCommitteeProposalCount", - ParamName: "MaxCommitteeProposalCount"}) - - result.Add(&settingItem{ - Flag: cmdcom.MaxNodePerHost, - DefaultValue: uint32(0), - ConfigPath: "MaxNodePerHost", - ParamName: "MaxNodePerHost"}) - - result.Add(&settingItem{ - Flag: cmdcom.VoteStatisticsHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "VoteStatisticsHeight", - ParamName: "VoteStatisticsHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.EnableActivateIllegalHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "EnableActivateIllegalHeight", - ParamName: "EnableActivateIllegalHeight"}) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: false, - ConfigPath: "EnableUtxoDB", - ParamName: "EnableUtxoDB"}) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: false, - ConfigPath: "EnableCORS", - ParamName: "EnableCORS"}) - - result.Add(&settingItem{ - Flag: cmdcom.AutoMiningFlag, - DefaultValue: false, - ConfigSetter: func(string, *config.Params, - *config.Configuration) error { - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - mining, ok := i.(bool) - if !ok { - return errors.New("invalid auto mining value") - } - conf.PowConfiguration.AutoMining = mining - return nil - }}) - - result.Add(&settingItem{ - Flag: cmdcom.PayToAddrFlag, - DefaultValue: "", - ConfigSetter: func(string, *config.Params, - *config.Configuration) error { - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - addr, ok := i.(string) - if !ok { - return errors.New("invalid pay to address value") - } - conf.PowConfiguration.PayToAddr = addr - return nil - }}) - - result.Add(&settingItem{ - Flag: cmdcom.EnableRPCFlag, - DefaultValue: true, - ConfigSetter: func(string, *config.Params, - *config.Configuration) error { - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - enable, ok := i.(bool) - if !ok { - return errors.New("invalid enable rpc value") - } - conf.EnableRPC = enable - return nil - }}) - - result.Add(&settingItem{ - Flag: cmdcom.RPCUserFlag, - DefaultValue: "", - ConfigSetter: func(string, *config.Params, - *config.Configuration) error { - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - user, ok := i.(string) - if !ok { - return errors.New("invalid rpc user value") - } - conf.RpcConfiguration.User = user - return nil - }}) - - result.Add(&settingItem{ - Flag: cmdcom.RPCPasswordFlag, - DefaultValue: "", - ConfigSetter: func(string, *config.Params, - *config.Configuration) error { - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - pass, ok := i.(string) - if !ok { - return errors.New("invalid rpc password value") - } - conf.RpcConfiguration.Pass = pass - return nil - }}) - - result.Add(&settingItem{ - Flag: cmdcom.RPCAllowedIPsFlag, - DefaultValue: []string{}, - ConfigSetter: func(string, *config.Params, - *config.Configuration) error { - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - ipStr, ok := i.([]string) - if !ok { - return errors.New("invalid ip list") - } - conf.RpcConfiguration.WhiteIPList = ipStr - return nil - }}) - - // DPoS configurations - - result.Add(&settingItem{ - Flag: cmdcom.EnableArbiterFlag, - DefaultValue: false, - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - // When arbiter service enabled, IP address must be set. - return checkHost(conf.DPoSConfiguration.IPAddress) - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - enable, ok := i.(bool) - if !ok { - return errors.New("invalid enable arbiter value") - } - conf.DPoSConfiguration.EnableArbiter = enable - return nil - }, - ConfigPath: "DPoSConfiguration.EnableArbiter", - ParamName: ""}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSMagicFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.Magic", - ParamName: "DPoSMagic"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSIPAddressFlag, - DefaultValue: "", - ConfigPath: "DPoSConfiguration.IPAddress", - ParamName: "DPoSIPAddress"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSPortFlag, - DefaultValue: uint16(0), - ConfigPath: "DPoSConfiguration.DPoSPort", - ParamName: "DPoSDefaultPort"}) - - result.Add(&settingItem{ - Flag: cmdcom.OriginArbitersFlag, - DefaultValue: []string{}, - ConfigPath: "DPoSConfiguration.OriginArbiters", - ParamName: "OriginArbiters"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCArbitersFlag, - DefaultValue: []string{}, - ConfigPath: "DPoSConfiguration.CRCArbiters", - ParamName: "CRCArbiters"}) - - result.Add(&settingItem{ - Flag: cmdcom.NormalArbitratorsCountFlag, - DefaultValue: 0, - ConfigPath: "DPoSConfiguration.NormalArbitratorsCount", - ParamName: "GeneralArbiters"}) - - result.Add(&settingItem{ - Flag: cmdcom.PreConnectOffsetFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.PreConnectOffset", - ParamName: "PreConnectOffset"}) - - result.Add(&settingItem{ - Flag: cmdcom.CandidatesCountFlag, - DefaultValue: 0, - ConfigPath: "DPoSConfiguration.CandidatesCount", - ParamName: "CandidateArbiters"}) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: time.Duration(0), - ConfigPath: "DPoSConfiguration.SignTolerance", - ConfigSetter: func(s string, params *config.Params, - conf *config.Configuration) error { - params.ToleranceDuration = - conf.DPoSConfiguration.SignTolerance * time.Second - return nil - }, - ParamName: "ToleranceDuration"}) - - result.Add(&settingItem{ - Flag: cmdcom.RevertToPOWNoBlockTimeFlag, - DefaultValue: int64(0), - ConfigPath: "DPoSConfiguration.RevertToPOWNoBlockTime", - ParamName: "RevertToPOWNoBlockTime"}) - - result.Add(&settingItem{ - Flag: cmdcom.StopConfirmBlockTimeFlag, - DefaultValue: int64(0), - ConfigPath: "DPoSConfiguration.StopConfirmBlockTime", - ParamName: "StopConfirmBlockTime"}) - - result.Add(&settingItem{ - Flag: cmdcom.RevertToPOWStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.RevertToPOWStartHeight", - ParamName: "RevertToPOWStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.MaxInactiveRoundsFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.MaxInactiveRounds", - ParamName: "MaxInactiveRounds"}) - - result.Add(&settingItem{ - Flag: cmdcom.InactivePenaltyFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "DPoSConfiguration.InactivePenalty", - ParamName: "InactivePenalty"}) - - result.Add(&settingItem{ - Flag: cmdcom.EmergencyInactivePenaltyFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "DPoSConfiguration.EmergencyInactivePenalty", - ParamName: "EmergencyInactivePenalty"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSV2MinVotesLockTimeFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.DPoSV2MinVotesLockTime", - ParamName: "DPoSV2MinVotesLockTime"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSV2DepositCoinMinLockTimeFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.DPoSV2DepositCoinMinLockTime", - ParamName: "DPoSV2DepositCoinMinLockTime"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPoSV2MaxVotesLockTimeFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.DPoSV2MaxVotesLockTime", - ParamName: "DPoSV2MaxVotesLockTime"}) - - // CR configurations - - result.Add(&settingItem{ - Flag: cmdcom.CRMemberCountFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.MemberCount", - ParamName: "CRMemberCount"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRDutyPeriodFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.DutyPeriod", - ParamName: "CRDutyPeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRDepositLockupBlocksFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.DepositLockupBlocks", - ParamName: "CRDepositLockupBlocks"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRVotingPeriodFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.VotingPeriod", - ParamName: "CRVotingPeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.ProposalCRVotingPeriodFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.ProposalCRVotingPeriod", - ParamName: "ProposalCRVotingPeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.ProposalPublicVotingPeriodFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.ProposalPublicVotingPeriod", - ParamName: "ProposalPublicVotingPeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRAgreementCountFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRAgreementCount", - ParamName: "CRAgreementCount"}) - - result.Add(&settingItem{ - Flag: cmdcom.VoterRejectPercentageFlag, - DefaultValue: float64(0), - ConfigPath: "CRConfiguration.VoterRejectPercentage", - ParamName: "VoterRejectPercentage"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCAppropriatePercentageFlag, - DefaultValue: float64(0), - ConfigPath: "CRConfiguration.CRCAppropriatePercentage", - ParamName: "CRCAppropriatePercentage"}) - - result.Add(&settingItem{ - Flag: cmdcom.SecretaryGeneralFlag, - DefaultValue: "", - ConfigPath: "CRConfiguration.SecretaryGeneral", - ParamName: "SecretaryGeneral"}) - - result.Add(&settingItem{ - Flag: cmdcom.MaxProposalTrackingCountFlag, - DefaultValue: uint8(0), - ConfigPath: "CRConfiguration.MaxProposalTrackingCount", - ParamName: "MaxProposalTrackingCount"}) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: "", - ConfigPath: "RPCServiceLevel", - ParamName: "RPCServiceLevel", - }) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: "", - ConfigPath: "NodeProfileStrategy", - ParamName: "NodeProfileStrategy", - }) - - result.Add(&settingItem{ - Flag: nil, - DefaultValue: uint32(0), - ConfigPath: "TxCacheVolume", - ParamName: "TxCacheVolume", - }) - - result.Add(&settingItem{ - Flag: cmdcom.RegisterCRByDIDHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.RegisterCRByDIDHeight", - ParamName: "RegisterCRByDIDHeight", - }) - - result.Add(&settingItem{ - Flag: cmdcom.ProhibitTransferToDIDHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "ProhibitTransferToDIDHeight", - ParamName: "ProhibitTransferToDIDHeight", - }) - - result.Add(&settingItem{ - Flag: cmdcom.MaxCRAssetsAddressUTXOCount, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.MaxCRAssetsAddressUTXOCount", - ParamName: "MaxCRAssetsAddressUTXOCount"}) - - result.Add(&settingItem{ - Flag: cmdcom.MinCRAssetsAddressUTXOCount, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.MinCRAssetsAddressUTXOCount", - ParamName: "MinCRAssetsAddressUTXOCount"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRAssetsRectifyTransactionHeight, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRAssetsRectifyTransactionHeight", - ParamName: "CRAssetsRectifyTransactionHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCProposalWithdrawPayloadV1Height, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRCProposalWithdrawPayloadV1Height", - ParamName: "CRCProposalWithdrawPayloadV1Height"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCProposalV1Height, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRCProposalV1Height", - ParamName: "CRCProposalV1Height"}) - - result.Add(&settingItem{ - Flag: cmdcom.RectifyTxFee, - DefaultValue: common.Fixed64(0), - ConfigPath: "CRConfiguration.RectifyTxFee", - ParamName: "RectifyTxFee"}) - - result.Add(&settingItem{ - Flag: cmdcom.RealWithdrawSingleFee, - DefaultValue: common.Fixed64(0), - ConfigPath: "CRConfiguration.RealWithdrawSingleFee", - ParamName: "RealWithdrawSingleFee"}) - - result.Add(&settingItem{ - Flag: cmdcom.NewVersionHeight, - DefaultValue: uint64(0), - ConfigPath: "CRConfiguration.NewP2PProtocolVersionHeight", - ParamName: "NewP2PProtocolVersionHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.ChangeCommitteeNewCRHeight, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.ChangeCommitteeNewCRHeight", - ParamName: "ChangeCommitteeNewCRHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRCProposalDraftDataStartHeight, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRCProposalDraftDataStartHeight", - ParamName: "CRCProposalDraftDataStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRClaimPeriodFlag, - DefaultValue: uint32(0), - ConfigPath: "CRConfiguration.CRClaimPeriod", - ParamName: "CRClaimPeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.CustomIDProposalStartHeight, - DefaultValue: uint32(0), - ConfigPath: "CustomIDProposalStartHeight", - ParamName: "CustomIDProposalStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.MaxReservedCustomIDLength, - DefaultValue: uint32(0), - ConfigPath: "MaxReservedCustomIDLength", - ParamName: "MaxReservedCustomIDLength"}) - - result.Add(&settingItem{ - Flag: cmdcom.NoCRCDPOSNodeHeight, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.NoCRCDPOSNodeHeight", - ParamName: "NoCRCDPOSNodeHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.RandomCandidatePeriod, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.RandomCandidatePeriod", - ParamName: "RandomCandidatePeriod"}) - - result.Add(&settingItem{ - Flag: cmdcom.MaxInactiveRoundsOfRandomNode, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.MaxInactiveRoundsOfRandomNode", - ParamName: "MaxInactiveRoundsOfRandomNode"}) - - result.Add(&settingItem{ - Flag: cmdcom.DPOSNodeCrossChainHeight, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.DPOSNodeCrossChainHeight", - ParamName: "DPOSNodeCrossChainHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CRDPoSNodeHotFixHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSConfiguration.CRDPoSNodeHotFixHeight", - ParamName: "CRDPoSNodeHotFixHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.HalvingRewardHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "HalvingRewardHeight", - ParamName: "HalvingRewardHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.HalvingRewardIntervalFlag, - DefaultValue: uint32(0), - ConfigPath: "HalvingRewardInterval", - ParamName: "HalvingRewardInterval"}) - - result.Add(&settingItem{ - Flag: cmdcom.NewELAIssuanceHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "NewELAIssuanceHeight", - ParamName: "NewELAIssuanceHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.SmallCrossTransferThreshold, - DefaultValue: common.Fixed64(0), - ConfigPath: "SmallCrossTransferThreshold", - ParamName: "SmallCrossTransferThreshold"}) - - result.Add(&settingItem{ - Flag: cmdcom.ReturnDepositCoinFeeFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "ReturnDepositCoinFee", - ParamName: "ReturnDepositCoinFee"}) - - result.Add(&settingItem{ - Flag: cmdcom.NewCrossChainStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "NewCrossChainStartHeight", - ParamName: "NewCrossChainStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.ReturnCrossChainCoinStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "ReturnCrossChainCoinStartHeight", - ParamName: "ReturnCrossChainCoinStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.DposV2StartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "DPoSV2StartHeight", - ParamName: "DPoSV2StartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.DposV2EffectiveVotesFlag, - DefaultValue: common.Fixed64(0), - ConfigPath: "DPoSV2EffectiveVotes", - ParamName: "DPoSV2EffectiveVotes"}) - - result.Add(&settingItem{ - Flag: cmdcom.StakePoolFlag, - DefaultValue: "", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - stakePoolAddress, err := common.Uint168FromAddress(conf.StakePool) - if err != nil { - return errors.New("invalid stake pool address") - } - params.StakePool = *stakePoolAddress - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - value, ok := i.(string) - if !ok { - return errors.New("unknown foundation address type") - } - stakePoolAddress, err := common.Uint168FromAddress(value) - if err != nil { - return errors.New("invalid stake pool address") - } - params.StakePool = *stakePoolAddress - return nil - }, - ConfigPath: "StakePool", - ParamName: "StakePool"}) - - result.Add(&settingItem{ - Flag: cmdcom.DposV2RewardAccumulateAddressFlag, - DefaultValue: "", - ConfigSetter: func(path string, params *config.Params, - conf *config.Configuration) error { - DposV2RewardAccumulateAddress, err := common.Uint168FromAddress(conf.DPoSConfiguration.DPoSV2RewardAccumulateAddress) - if err != nil { - return errors.New("invalid CR expenses address") - } - params.DPoSV2RewardAccumulateAddress = *DposV2RewardAccumulateAddress - return nil - }, - CliSetter: func(i interface{}, params *config.Params, - conf *config.Configuration) error { - value, ok := i.(string) - if !ok { - return errors.New("unknown foundation address type") - } - DposV2RewardAccumulateAddress, err := common.Uint168FromAddress(value) - if err != nil { - return errors.New("invalid CR expenses address") - } - params.DPoSV2RewardAccumulateAddress = *DposV2RewardAccumulateAddress - return nil - }, - ConfigPath: "DPoSConfiguration.DPoSV2RewardAccumulateAddress", - ParamName: "DPoSV2RewardAccumulateAddress"}) - - result.Add(&settingItem{ - Flag: cmdcom.SchnorrStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "SchnorrStartHeight", - ParamName: "SchnorrStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CrossChainMonitorStartHeightFlag, - DefaultValue: uint32(0), - ConfigPath: "CrossChainMonitorStartHeight", - ParamName: "CrossChainMonitorStartHeight"}) - - result.Add(&settingItem{ - Flag: cmdcom.CrossChainMonitorIntervalFlag, - DefaultValue: uint32(0), - ConfigPath: "CrossChainMonitorInterval", - ParamName: "CrossChainMonitorInterval"}) - - return result -} - -func (s *Settings) SetupConfig() { - configPath := s.context.String("conf") - file, err := s.loadConfigFile(configPath) - if err != nil { - if s.context.IsSet("conf") { - cmdcom.PrintErrorMsg(err.Error()) - os.Exit(1) - } - file = &defaultConfig - } - - s.conf = file -} - -// loadConfigFile read configuration parameters through the config file. -func (s *Settings) loadConfigFile(path string) (*config.Configuration, error) { - file, err := ioutil.ReadFile(path) - if err != nil { - return nil, err - } - // Remove the UTF-8 Byte Order Mark - file = bytes.TrimPrefix(file, []byte("\xef\xbb\xbf")) - - cfgFile := struct { - config.Configuration `json:"Configuration"` - }{ - Configuration: defaultConfig, - } - - err = json.Unmarshal(file, &cfgFile) - if err != nil { - return nil, errors.New("config file parsing failed, " + err.Error()) - } - - return &cfgFile.Configuration, nil -} - -// checkHost check the host or IP address is valid and available. -func checkHost(host string) error { - // Empty host check. - if host == "" { - return errors.New("arbiter IPAddress must set when arbiter" + - " service enabled") - } - - // Skip if host is already an IP address. - if ip := net.ParseIP(host); ip != nil { - return nil - } - - // Attempt to look up an IP address associated with the parsed host. - ips, err := net.LookupIP(host) - if err != nil { - return err - } - if len(ips) == 0 { - return fmt.Errorf("no addresses found for %s", host) - } - - return nil -} - -// mainNetDefault set the default parameters for main net usage. -func (s *Settings) mainNetDefault(cfg *config.Configuration) error { - if err := s.trySetUintPortValue(cmdcom.InfoPortFlag.Name, &cfg.HttpInfoPort, - 20333); err != nil { - return err - } - if err := s.trySetPortValue(cmdcom.RestPortFlag.Name, &cfg.HttpRestPort, - 20334); err != nil { - return err - } - if err := s.trySetPortValue(cmdcom.WsPortFlag.Name, &cfg.HttpWsPort, - 20335); err != nil { - return err - } - return s.trySetPortValue(cmdcom.RPCPortFlag.Name, - &cfg.HttpJsonPort, 20336) -} - -// testNetDefault set the default parameters for test net usage. -func (s *Settings) testNetDefault(cfg *config.Configuration) error { - if err := s.trySetUintPortValue(cmdcom.InfoPortFlag.Name, &cfg.HttpInfoPort, - 21333); err != nil { - return err - } - if err := s.trySetPortValue(cmdcom.RestPortFlag.Name, &cfg.HttpRestPort, - 21334); err != nil { - return err - } - if err := s.trySetPortValue(cmdcom.WsPortFlag.Name, &cfg.HttpWsPort, - 21335); err != nil { - return err - } - return s.trySetPortValue(cmdcom.RPCPortFlag.Name, - &cfg.HttpJsonPort, 21336) -} - -// regNetDefault set the default parameters for reg net usage. -func (s *Settings) regNetDefault(cfg *config.Configuration) error { - if err := s.trySetUintPortValue(cmdcom.InfoPortFlag.Name, &cfg.HttpInfoPort, - 22333); err != nil { - return err - } - if err := s.trySetPortValue(cmdcom.RestPortFlag.Name, &cfg.HttpRestPort, - 22334); err != nil { - return err - } - if err := s.trySetPortValue(cmdcom.WsPortFlag.Name, &cfg.HttpWsPort, - 22335); err != nil { - return err - } - return s.trySetPortValue(cmdcom.RPCPortFlag.Name, - &cfg.HttpJsonPort, 22336) -} - -func (s *Settings) trySetPortValue(cliFlag string, value *int, - defaultValue int) error { - if s.context.IsSet(cliFlag) { - info, err := strconv.ParseInt(s.context.String( - cliFlag), 10, 32) - if err != nil { - return err - } - *value = int(info) - } else if *value == 0 { - *value = defaultValue - } - return nil -} - -func (s *Settings) trySetUintPortValue(cliFlag string, value *uint16, - defaultValue uint16) error { - if s.context.IsSet(cliFlag) { - info, err := strconv.ParseUint(s.context.String( - cliFlag), 10, 16) - if err != nil { - return err - } - *value = uint16(info) - } else if *value == 0 { - *value = defaultValue - } - return nil -} - -func GetFullCommandName(flag cli.Flag) string { - result := strings.Split(flag.GetName(), commandNameSplitter)[0] - return strings.TrimSpace(result) + return settings } diff --git a/core/checkpoint/channels.go b/core/checkpoint/channels.go index bb3227735..5c2b9d458 100644 --- a/core/checkpoint/channels.go +++ b/core/checkpoint/channels.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/utils" ) @@ -27,7 +28,7 @@ type heightFileMsg struct { } type fileChannels struct { - cfg *Config + cfg *config.Configuration save chan fileMsg clean chan fileMsg @@ -88,14 +89,14 @@ func (c *fileChannels) messageLoop() { func (c *fileChannels) saveCheckpoint(msg *fileMsg) (err error) { defer c.replyMsg(msg) - dir := getCheckpointDirectory(c.cfg.DataPath, msg.checkpoint) + dir := getCheckpointDirectory(c.cfg.CheckPointConfiguration.DataPath, msg.checkpoint) if !utils.FileExisted(dir) { if err = os.MkdirAll(dir, 0700); err != nil { return } } - filename := getFilePath(c.cfg.DataPath, msg.checkpoint) + filename := getFilePath(c.cfg.CheckPointConfiguration.DataPath, msg.checkpoint) var file *os.File file, err = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) @@ -113,7 +114,7 @@ func (c *fileChannels) saveCheckpoint(msg *fileMsg) (err error) { return } - if !c.cfg.EnableHistory { + if !c.cfg.CheckPointConfiguration.EnableHistory { return c.cleanCheckpoints(msg, false, false) } return nil @@ -125,7 +126,7 @@ func (c *fileChannels) cleanCheckpoints(msg *fileMsg, defer c.replyMsg(msg) } - dir := getCheckpointDirectory(c.cfg.DataPath, msg.checkpoint) + dir := getCheckpointDirectory(c.cfg.CheckPointConfiguration.DataPath, msg.checkpoint) reserveCurrentName := getFileName(msg.checkpoint, msg.checkpoint.GetHeight()) reservePrevName := getFileName(msg.checkpoint, msg.checkpoint.GetHeight()-msg.checkpoint.SavePeriod()) @@ -153,9 +154,9 @@ func (c *fileChannels) cleanCheckpoints(msg *fileMsg, func (c *fileChannels) replaceCheckpoints(msg *heightFileMsg) (err error) { defer c.replyMsg(&msg.fileMsg) - defaultFullName := getDefaultPath(c.cfg.DataPath, msg.checkpoint) + defaultFullName := getDefaultPath(c.cfg.CheckPointConfiguration.DataPath, msg.checkpoint) // source file is the previous saved checkpoint - sourceFullName := getFilePathByHeight(c.cfg.DataPath, msg.checkpoint, + sourceFullName := getFilePathByHeight(c.cfg.CheckPointConfiguration.DataPath, msg.checkpoint, msg.height) if !utils.FileExisted(sourceFullName) { return errors.New(fmt.Sprintf("source file %s does not exist", @@ -177,7 +178,7 @@ func (c *fileChannels) replyMsg(msg *fileMsg) { } } -func NewFileChannels(cfg *Config) *fileChannels { +func NewFileChannels(cfg *config.Configuration) *fileChannels { channels := &fileChannels{ cfg: cfg, save: make(chan fileMsg), diff --git a/core/checkpoint/channels_test.go b/core/checkpoint/channels_test.go index 53cb72d00..5ea29afd4 100644 --- a/core/checkpoint/channels_test.go +++ b/core/checkpoint/channels_test.go @@ -8,14 +8,17 @@ package checkpoint import ( "testing" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/utils" "github.com/stretchr/testify/assert" ) func TestFileChannels_LifeCycle(t *testing.T) { - channels := NewFileChannels(&Config{ - EnableHistory: true, - }) + cfg := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: true, + }} + channels := NewFileChannels(cfg) data := uint64(1) currentHeight := uint32(10) pt := &checkpoint{ diff --git a/core/checkpoint/manager.go b/core/checkpoint/manager.go index 785dec3af..c5814bd30 100644 --- a/core/checkpoint/manager.go +++ b/core/checkpoint/manager.go @@ -18,6 +18,7 @@ import ( "sync" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/utils" @@ -109,29 +110,11 @@ type ICheckPoint interface { StartHeight() uint32 } -// Config holds checkpoint related configurations. -type Config struct { - // EnableHistory is a switch about recording history of snapshots of - // checkpoints. - EnableHistory bool - - // HistoryStartHeight defines the height manager should start to record - // snapshots of checkpoints. - HistoryStartHeight uint32 - - // DataPath defines root directory path of all checkpoint related files. - DataPath string - - // NeedSave indicate whether or not manager should save checkpoints when - // reached a save point. - NeedSave bool -} - // Manager holds checkpoints save automatically. type Manager struct { checkpoints map[string]ICheckPoint channels map[string]*fileChannels - cfg *Config + cfg *config.Configuration mtx sync.RWMutex } @@ -207,7 +190,7 @@ func (m *Manager) GetCheckpoint(key string, height uint32) ( return } - if m.cfg.EnableHistory { + if m.cfg.CheckPointConfiguration.EnableHistory { return m.findHistoryCheckpoint(checkpoint, height) } else { return nil, false @@ -294,14 +277,14 @@ func (m *Manager) Close() { // SetDataPath set root path of all checkpoints. func (m *Manager) SetDataPath(path string) { - m.cfg.DataPath = path + m.cfg.CheckPointConfiguration.DataPath = path } // RegisterNeedSave register the need save function. func (m *Manager) SetNeedSave(needSave bool) { m.mtx.Lock() defer m.mtx.Unlock() - m.cfg.NeedSave = needSave + m.cfg.CheckPointConfiguration.NeedSave = needSave } func (m *Manager) getOrderedCheckpoints() []ICheckPoint { @@ -329,7 +312,7 @@ func (m *Manager) onBlockSaved(block *types.DposBlock, continue } v.OnBlockSaved(block) - if !m.cfg.NeedSave { + if !m.cfg.CheckPointConfiguration.NeedSave { continue } @@ -392,12 +375,12 @@ func (m *Manager) findHistoryCheckpoint(current ICheckPoint, bestHeight = 0 } - path := getFilePathByHeight(m.cfg.DataPath, current, bestHeight) + path := getFilePathByHeight(m.cfg.CheckPointConfiguration.DataPath, current, bestHeight) return m.constructCheckpoint(current, path) } func (m *Manager) loadDefaultCheckpoint(current ICheckPoint) (err error) { - path := getDefaultPath(m.cfg.DataPath, current) + path := getDefaultPath(m.cfg.CheckPointConfiguration.DataPath, current) data, err := m.readFileBuffer(path) if err != nil { return err @@ -408,7 +391,7 @@ func (m *Manager) loadDefaultCheckpoint(current ICheckPoint) (err error) { } func (m *Manager) loadSpecificHeightCheckpoint(current ICheckPoint, height int) (err error) { - path := getSpecificHeightPath(m.cfg.DataPath, current, height) + path := getSpecificHeightPath(m.cfg.CheckPointConfiguration.DataPath, current, height) data, err := m.readFileBuffer(path) if err != nil { return err @@ -480,11 +463,10 @@ func getCheckpointDirectory(root string, return filepath.Join(root, checkpoint.Key()) } -func NewManager(cfg *Config) *Manager { - m := &Manager{ +func NewManager(cfg *config.Configuration) *Manager { + return &Manager{ checkpoints: make(map[string]ICheckPoint), channels: make(map[string]*fileChannels), cfg: cfg, } - return m } diff --git a/core/checkpoint/manager_test.go b/core/checkpoint/manager_test.go index 7edc6fc92..66d580132 100644 --- a/core/checkpoint/manager_test.go +++ b/core/checkpoint/manager_test.go @@ -8,7 +8,6 @@ package checkpoint import ( "bytes" "errors" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "io" "io/ioutil" "math/rand" @@ -17,7 +16,9 @@ import ( "testing" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/types" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/utils/test" "github.com/stretchr/testify/assert" ) @@ -140,11 +141,12 @@ func TestManager_SaveAndRestore(t *testing.T) { data: &data, height: currentHeight, } - - manager := NewManager(&Config{ - EnableHistory: false, - NeedSave: true, - }) + cfg := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: false, + NeedSave: true, + }} + manager := NewManager(cfg) manager.Register(pt) // save nothing @@ -170,10 +172,12 @@ func TestManager_SaveAndRestore(t *testing.T) { }, }, nil, false, false) + cfg2 := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: false, + }} // new a checkpoint manager and restore - manager2 := NewManager(&Config{ - EnableHistory: false, - }) + manager2 := NewManager(cfg2) manager2.Register(&checkpoint{}) assert.NoError(t, manager2.Restore()) assert.Equal(t, currentHeight-pt.EffectivePeriod(), @@ -189,10 +193,11 @@ func TestManager_GetCheckpoint_DisableHistory(t *testing.T) { data: &data, height: currentHeight, } - - manager := NewManager(&Config{ - EnableHistory: false, - }) + cfg := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: false, + }} + manager := NewManager(cfg) manager.Register(pt) result, ok := manager.GetCheckpoint(pt.Key(), currentHeight-1) @@ -218,11 +223,13 @@ func TestManager_GetCheckpoint_EnableHistory(t *testing.T) { height: 0, } - manager := NewManager(&Config{ - EnableHistory: true, - HistoryStartHeight: currentHeight, - NeedSave: true, - }) + cfg := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: true, + HistoryStartHeight: currentHeight, + NeedSave: true, + }} + manager := NewManager(cfg) manager.Register(pt) manager.OnBlockSaved(&types.DposBlock{ @@ -252,10 +259,6 @@ func TestManager_GetCheckpoint_EnableHistory(t *testing.T) { assert.NotEqual(t, nil, result) assert.Equal(t, true, ok) - result, ok = manager.GetCheckpoint(pt.Key(), currentHeight) - assert.NotEqual(t, nil, result) - assert.Equal(t, true, ok) - cleanCheckpoints() } @@ -267,10 +270,13 @@ func TestManager_OnRollbackTo(t *testing.T) { height: currentHeight, } - manager := NewManager(&Config{ - EnableHistory: true, - HistoryStartHeight: currentHeight, - }) + cfg := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: true, + HistoryStartHeight: currentHeight, + }} + + manager := NewManager(cfg) manager.Register(pt) originalHeight := currentHeight @@ -289,7 +295,11 @@ func TestManager_OnRollbackTo(t *testing.T) { } func TestManager_getOrderedCheckpoints(t *testing.T) { - manager := NewManager(&Config{}) + cfg := &config.Configuration{ + CheckPointConfiguration: config.CheckPointConfiguration{ + EnableHistory: true, + }} + manager := NewManager(cfg) for i := 0; i < 10; i++ { manager.checkpoints[randomString()] = diff --git a/core/contract/contract_test.go b/core/contract/contract_test.go index 64cf60f4b..4c72f607d 100644 --- a/core/contract/contract_test.go +++ b/core/contract/contract_test.go @@ -7,9 +7,9 @@ package contract import ( "encoding/hex" - "github.com/elastos/Elastos.ELA/common" "testing" + "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/crypto" "github.com/stretchr/testify/assert" diff --git a/core/contract/crosschain.go b/core/contract/crosschain.go index 60a001af0..129f77e85 100644 --- a/core/contract/crosschain.go +++ b/core/contract/crosschain.go @@ -7,9 +7,9 @@ package contract import ( "bytes" - "github.com/elastos/Elastos.ELA/vm" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/vm" ) // A temporary file created for cross chain tx diff --git a/core/manager.go b/core/manager.go new file mode 100644 index 000000000..0d051fdaf --- /dev/null +++ b/core/manager.go @@ -0,0 +1,99 @@ +package core + +import ( + "time" + + common2 "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract/program" + "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/payload" + "github.com/elastos/Elastos.ELA/crypto" +) + +var ( + // ELAAssetID represents the asset ID of ELA coin. + ELAAssetID = "b037db964a231458d2d6ffd5ea18944c4f90e63d547c5d3b9874df66a4ead0a3" + + // attrNonce represents the nonce attribute used in the genesis coinbase transaction. + attrNonce = common.NewAttribute(common.Nonce, []byte{77, 101, 130, 33, 7, 252, 253, 82}) + + // ELAPrecision represents the precision of ELA coin. + ELAPrecision = byte(0x08) + + // genesisTime indicates the time when ELA genesis block created. + genesisTime, _ = time.Parse(time.RFC3339, "2017-12-22T10:00:00Z") + + // zeroHash represents a hash with all '0' value. + zeroHash = common2.Uint256{} +) + +// GenesisBlock creates a genesis block by the specified foundation address. +// The genesis block goes different because the foundation address in each network is different. +func GenesisBlock(foundationAddr string) *types.Block { + foundation, _ := common2.Uint168FromAddress(foundationAddr) + // elaAsset is the transaction that create and register the ELA coin. + elaAsset := functions.CreateTransaction( + 0, + common.RegisterAsset, + 0, + &payload.RegisterAsset{ + Asset: payload.Asset{ + Name: "ELA", + Precision: ELAPrecision, + AssetType: 0x00, + }, + Amount: 0 * 100000000, + Controller: common2.Uint168{}, + }, + []*common.Attribute{}, + []*common.Input{}, + []*common.Output{}, + 0, + []*program.Program{}, + ) + + assetID, _ := common2.Uint256FromHexString(ELAAssetID) + coinBase := functions.CreateTransaction( + 0, + common.CoinBase, + payload.CoinBaseVersion, + &payload.CoinBase{}, + []*common.Attribute{&attrNonce}, + []*common.Input{ + { + Previous: common.OutPoint{ + TxID: zeroHash, + Index: 0x0000, + }, + Sequence: 0x00000000, + }, + }, + []*common.Output{ + { + AssetID: *assetID, + Value: 3300 * 10000 * 100000000, + ProgramHash: *foundation, + }, + }, + 0, + []*program.Program{}, + ) + + merkleRoot, _ := crypto.ComputeRoot([]common2.Uint256{coinBase.Hash(), *assetID}) + + return &types.Block{ + Header: common.Header{ + Version: 0, + Previous: zeroHash, + MerkleRoot: merkleRoot, + Timestamp: uint32(genesisTime.Unix()), + Bits: 0x1d03ffff, + Nonce: 2083236893, + Height: 0, + }, + Transactions: []interfaces.Transaction{coinBase, elaAsset}, + } +} diff --git a/core/transaction/activateproducertransaction.go b/core/transaction/activateproducertransaction.go index 876c19bd0..6e0cfca83 100644 --- a/core/transaction/activateproducertransaction.go +++ b/core/transaction/activateproducertransaction.go @@ -101,7 +101,7 @@ func (t *ActivateProducerTransaction) SpecialContextCheck() (elaerr.ELAError, bo return elaerr.Simple(elaerr.ErrTxPayload, errors.New("can not activate this producer")), true } } else { - if t.parameters.BlockHeight < t.parameters.Config.ChangeCommitteeNewCRHeight { + if t.parameters.BlockHeight < t.parameters.Config.CRConfiguration.ChangeCommitteeNewCRHeight { if producer.State() != state.Active && producer.State() != state.Inactive && producer.State() != state.Illegal { @@ -122,7 +122,7 @@ func (t *ActivateProducerTransaction) SpecialContextCheck() (elaerr.ELAError, bo } depositAmount := common.Fixed64(0) - if t.parameters.BlockHeight < t.parameters.Config.CRVotingStartHeight { + if t.parameters.BlockHeight < t.parameters.Config.CRConfiguration.CRVotingStartHeight { programHash, err := contract.PublicKeyToDepositProgramHash( producer.OwnerPublicKey()) if err != nil { diff --git a/core/transaction/coinbasetransaction.go b/core/transaction/coinbasetransaction.go index f3d71fb62..a4f9620b2 100644 --- a/core/transaction/coinbasetransaction.go +++ b/core/transaction/coinbasetransaction.go @@ -10,7 +10,7 @@ import ( "math" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" @@ -50,9 +50,10 @@ func (t *CoinBaseTransaction) CheckTransactionOutput() error { foundationReward := t.Outputs()[0].Value var totalReward = common.Fixed64(0) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) if blockHeight < chainParams.PublicDPOSHeight { for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in coinbase is invalid") } totalReward += output.Value @@ -98,20 +99,23 @@ func (t *CoinBaseTransaction) IsAllowedInPOWConsensus() bool { func (a *CoinBaseTransaction) SpecialContextCheck() (result elaerr.ELAError, end bool) { para := a.parameters - if para.BlockHeight >= para.Config.CRCommitteeStartHeight { + DestroyELAAddress, _ := common.Uint168FromAddress(para.Config.DestroyELAAddress) + CRAssetsAddress, _ := common.Uint168FromAddress(para.Config.CRConfiguration.CRAssetsAddress) + FoundationAddress, _ := common.Uint168FromAddress(para.Config.FoundationAddress) + if para.BlockHeight >= para.Config.CRConfiguration.CRCommitteeStartHeight { if para.BlockChain.GetState().GetConsensusAlgorithm() == 0x01 { - if !a.outputs[0].ProgramHash.IsEqual(para.Config.DestroyELAAddress) { + if !a.outputs[0].ProgramHash.IsEqual(*DestroyELAAddress) { return elaerr.Simple(elaerr.ErrTxInvalidOutput, errors.New("first output address should be "+ "DestroyAddress in POW consensus algorithm")), true } } else { - if !a.outputs[0].ProgramHash.IsEqual(para.Config.CRAssetsAddress) { + if !a.outputs[0].ProgramHash.IsEqual(*CRAssetsAddress) { return elaerr.Simple(elaerr.ErrTxInvalidOutput, errors.New("first output address should be CR assets address")), true } } - } else if !a.outputs[0].ProgramHash.IsEqual(para.Config.Foundation) { + } else if !a.outputs[0].ProgramHash.IsEqual(*FoundationAddress) { return elaerr.Simple(elaerr.ErrTxInvalidOutput, errors.New("first output address should be foundation address")), true } diff --git a/core/transaction/common.go b/core/transaction/common.go index 714ee4e12..4c3dac1c0 100644 --- a/core/transaction/common.go +++ b/core/transaction/common.go @@ -86,7 +86,7 @@ func GetTransactionparameters( Transaction: transaction, BlockHeight: blockHeight, TimeStamp: timeStamp, - Config: cfg.(*config.Params), + Config: cfg.(*config.Configuration), BlockChain: bc.(*blockchain.BlockChain), ProposalsUsedAmount: proposalsUsedAmount, } diff --git a/core/transaction/crassetsrectifytransaction.go b/core/transaction/crassetsrectifytransaction.go index 00ceee8b0..2d66bbd3b 100644 --- a/core/transaction/crassetsrectifytransaction.go +++ b/core/transaction/crassetsrectifytransaction.go @@ -45,7 +45,7 @@ func (t *CRAssetsRectifyTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRAssetsRectifyTransactionHeight { + if blockHeight < chainParams.CRConfiguration.CRAssetsRectifyTransactionHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCProposalWithdrawPayloadV1Height", t.TxType().Name())) } @@ -54,22 +54,23 @@ func (t *CRAssetsRectifyTransaction) HeightVersionCheck() error { func (t *CRAssetsRectifyTransaction) SpecialContextCheck() (result elaerr.ELAError, end bool) { // Inputs count should be less than or equal to MaxCRAssetsAddressUTXOCount - if len(t.Inputs()) > int(t.parameters.Config.MaxCRAssetsAddressUTXOCount) { + if len(t.Inputs()) > int(t.parameters.Config.CRConfiguration.MaxCRAssetsAddressUTXOCount) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("inputs count should be less than or "+ "equal to MaxCRAssetsAddressUTXOCount")), true } // Inputs count should be greater than or equal to MinCRAssetsAddressUTXOCount - if len(t.Inputs()) < int(t.parameters.Config.MinCRAssetsAddressUTXOCount) { + if len(t.Inputs()) < int(t.parameters.Config.CRConfiguration.MinCRAssetsAddressUTXOCount) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("inputs count should be greater than or "+ "equal to MinCRAssetsAddressUTXOCount")), true } // Inputs need to only from CR assets address var totalInput common.Fixed64 + CRAssetsAddress, _ := common.Uint168FromAddress(t.parameters.Config.CRConfiguration.CRAssetsAddress) for _, output := range t.references { totalInput += output.Value - if !output.ProgramHash.IsEqual(t.parameters.Config.CRAssetsAddress) { + if !output.ProgramHash.IsEqual(*CRAssetsAddress) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("input does not from CRAssetsAddress")), true } } @@ -80,15 +81,15 @@ func (t *CRAssetsRectifyTransaction) SpecialContextCheck() (result elaerr.ELAErr } // common2.Output should translate to CR assets address only - if !t.Outputs()[0].ProgramHash.IsEqual(t.parameters.Config.CRAssetsAddress) { + if !t.Outputs()[0].ProgramHash.IsEqual(*CRAssetsAddress) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("output does not to CRAssetsAddress")), true } // Inputs amount need equal to outputs amount totalOutput := t.Outputs()[0].Value - if totalInput != totalOutput+t.parameters.Config.RectifyTxFee { + if totalInput != totalOutput+t.parameters.Config.CRConfiguration.RectifyTxFee { return elaerr.Simple(elaerr.ErrTxPayload, fmt.Errorf("inputs minus outputs does not match with %d sela fee , "+ - "inputs:%s outputs:%s", t.parameters.Config.RectifyTxFee, totalInput, totalOutput)), true + "inputs:%s outputs:%s", t.parameters.Config.CRConfiguration.RectifyTxFee, totalInput, totalOutput)), true } return nil, false diff --git a/core/transaction/crcappropriationtransaction.go b/core/transaction/crcappropriationtransaction.go index 7929aa470..6432fde5b 100644 --- a/core/transaction/crcappropriationtransaction.go +++ b/core/transaction/crcappropriationtransaction.go @@ -11,7 +11,7 @@ import ( "math" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" elaerr "github.com/elastos/Elastos.ELA/errors" @@ -24,6 +24,9 @@ type CRCAppropriationTransaction struct { func (t *CRCAppropriationTransaction) CheckTransactionOutput() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) + CRExpensesAddress, _ := common.Uint168FromAddress(chainParams.CRConfiguration.CRExpensesAddress) + CRAssetsAddress, _ := common.Uint168FromAddress(chainParams.CRConfiguration.CRAssetsAddress) if len(t.Outputs()) > math.MaxUint16 { return errors.New("output count should not be greater than 65535(MaxUint16)") } @@ -31,11 +34,11 @@ func (t *CRCAppropriationTransaction) CheckTransactionOutput() error { if len(t.Outputs()) != 2 { return errors.New("new CRCAppropriation tx must have two output") } - if !t.Outputs()[0].ProgramHash.IsEqual(chainParams.CRExpensesAddress) { + if !t.Outputs()[0].ProgramHash.IsEqual(*CRExpensesAddress) { return errors.New("new CRCAppropriation tx must have the first" + "output to CR expenses address") } - if !t.Outputs()[1].ProgramHash.IsEqual(chainParams.CRAssetsAddress) { + if !t.Outputs()[1].ProgramHash.IsEqual(*CRAssetsAddress) { return errors.New("new CRCAppropriation tx must have the second" + "output to CR assets address") } @@ -43,7 +46,7 @@ func (t *CRCAppropriationTransaction) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } @@ -100,7 +103,7 @@ func (t *CRCAppropriationTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRCommitteeStartHeight { + if blockHeight < chainParams.CRConfiguration.CRCommitteeStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCommitteeStartHeight", t.TxType().Name())) } @@ -115,9 +118,11 @@ func (t *CRCAppropriationTransaction) SpecialContextCheck() (result elaerr.ELAEr // Inputs need to only from CR assets address var totalInput common.Fixed64 + for _, output := range t.references { totalInput += output.Value - if !output.ProgramHash.IsEqual(t.parameters.Config.CRAssetsAddress) { + CRAssetsAddress, _ := common.Uint168FromAddress(t.parameters.Config.CRConfiguration.CRAssetsAddress) + if !output.ProgramHash.IsEqual(*CRAssetsAddress) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("input does not from CR assets address")), true } } diff --git a/core/transaction/crcouncilmemberclaimnodetransaction.go b/core/transaction/crcouncilmemberclaimnodetransaction.go index f8ae2e479..fcdd77430 100644 --- a/core/transaction/crcouncilmemberclaimnodetransaction.go +++ b/core/transaction/crcouncilmemberclaimnodetransaction.go @@ -39,7 +39,7 @@ func (t *CRCouncilMemberClaimNodeTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRClaimDPOSNodeStartHeight { + if blockHeight < chainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRClaimDPOSNodeStartHeight", t.TxType().Name())) } diff --git a/core/transaction/crcproposalrealwithdrawtransaction.go b/core/transaction/crcproposalrealwithdrawtransaction.go index 91b028241..c2b3a8ddb 100644 --- a/core/transaction/crcproposalrealwithdrawtransaction.go +++ b/core/transaction/crcproposalrealwithdrawtransaction.go @@ -45,7 +45,7 @@ func (t *CRCProposalRealWithdrawTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRAssetsRectifyTransactionHeight { + if blockHeight < chainParams.CRConfiguration.CRAssetsRectifyTransactionHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCProposalWithdrawPayloadV1Height", t.TxType().Name())) } @@ -53,6 +53,7 @@ func (t *CRCProposalRealWithdrawTransaction) HeightVersionCheck() error { } func (t *CRCProposalRealWithdrawTransaction) SpecialContextCheck() (result elaerr.ELAError, end bool) { + CRExpensesAddress, _ := common.Uint168FromAddress(t.parameters.Config.CRConfiguration.CRExpensesAddress) crcRealWithdraw, ok := t.Payload().(*payload.CRCProposalRealWithdraw) if !ok { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid payload")), true @@ -66,7 +67,7 @@ func (t *CRCProposalRealWithdrawTransaction) SpecialContextCheck() (result elaer // if need change, the last output is only allowed to CRExpensesAddress. if txsCount != len(t.Outputs()) { toProgramHash := t.Outputs()[len(t.Outputs())-1].ProgramHash - if !toProgramHash.IsEqual(t.parameters.Config.CRExpensesAddress) { + if !toProgramHash.IsEqual(*CRExpensesAddress) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("last output is invalid"))), true } } @@ -83,10 +84,10 @@ func (t *CRCProposalRealWithdrawTransaction) SpecialContextCheck() (result elaer if !output.ProgramHash.IsEqual(txInfo.Recipient) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid real withdraw output address")), true } - if output.Value != txInfo.Amount-t.parameters.Config.RealWithdrawSingleFee { + if output.Value != txInfo.Amount-t.parameters.Config.CRConfiguration.RealWithdrawSingleFee { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("invalid real withdraw output "+ "amount:%s, need to be:%s", - output.Value, txInfo.Amount-t.parameters.Config.RealWithdrawSingleFee))), true + output.Value, txInfo.Amount-t.parameters.Config.CRConfiguration.RealWithdrawSingleFee))), true } if _, ok := txsMap[hash]; ok { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("duplicated real withdraw transactions hash")), true @@ -103,10 +104,10 @@ func (t *CRCProposalRealWithdrawTransaction) SpecialContextCheck() (result elaer for _, o := range t.Outputs() { outputAmount += o.Value } - if inputAmount-outputAmount != t.parameters.Config.RealWithdrawSingleFee*common.Fixed64(txsCount) { + if inputAmount-outputAmount != t.parameters.Config.CRConfiguration.RealWithdrawSingleFee*common.Fixed64(txsCount) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("invalid real withdraw transaction"+ " fee:%s, need to be:%s, txsCount:%d", inputAmount-outputAmount, - t.parameters.Config.RealWithdrawSingleFee*common.Fixed64(txsCount), txsCount))), true + t.parameters.Config.CRConfiguration.RealWithdrawSingleFee*common.Fixed64(txsCount), txsCount))), true } return nil, false diff --git a/core/transaction/crcproposalreviewtransaction.go b/core/transaction/crcproposalreviewtransaction.go index d8749a64e..01e7d3d67 100644 --- a/core/transaction/crcproposalreviewtransaction.go +++ b/core/transaction/crcproposalreviewtransaction.go @@ -9,12 +9,12 @@ import ( "bytes" "errors" "fmt" - "github.com/elastos/Elastos.ELA/database" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types/payload" crstate "github.com/elastos/Elastos.ELA/cr/state" + "github.com/elastos/Elastos.ELA/database" elaerr "github.com/elastos/Elastos.ELA/errors" ) @@ -39,10 +39,10 @@ func (t *CRCProposalReviewTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRCommitteeStartHeight { + if blockHeight < chainParams.CRConfiguration.CRCommitteeStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCommitteeStartHeight", t.TxType().Name())) - } else if blockHeight < chainParams.CRCProposalDraftDataStartHeight { + } else if blockHeight < chainParams.CRConfiguration.CRCProposalDraftDataStartHeight { if t.PayloadVersion() != payload.CRCProposalVersion { return errors.New("payload version should be CRCProposalVersion") } diff --git a/core/transaction/crcproposaltrackingtransaction.go b/core/transaction/crcproposaltrackingtransaction.go index 84cb7143c..d00939652 100644 --- a/core/transaction/crcproposaltrackingtransaction.go +++ b/core/transaction/crcproposaltrackingtransaction.go @@ -10,7 +10,6 @@ import ( "encoding/hex" "errors" "fmt" - "github.com/elastos/Elastos.ELA/database" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" @@ -18,6 +17,7 @@ import ( "github.com/elastos/Elastos.ELA/core/types/payload" crstate "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/crypto" + "github.com/elastos/Elastos.ELA/database" elaerr "github.com/elastos/Elastos.ELA/errors" ) @@ -42,10 +42,10 @@ func (t *CRCProposalTrackingTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRCommitteeStartHeight { + if blockHeight < chainParams.CRConfiguration.CRCommitteeStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCommitteeStartHeight", t.TxType().Name())) - } else if blockHeight < chainParams.CRCProposalDraftDataStartHeight { + } else if blockHeight < chainParams.CRConfiguration.CRCProposalDraftDataStartHeight { if t.PayloadVersion() != payload.CRCProposalVersion { return errors.New("payload version should be CRCProposalVersion") } @@ -72,7 +72,7 @@ func (t *CRCProposalTrackingTransaction) SpecialContextCheck() (result elaerr.EL return elaerr.Simple(elaerr.ErrTxPayload, errors.New("proposal status is not VoterAgreed")), true } // Check proposal tracking count. - if proposalState.TrackingCount >= t.parameters.Config.MaxProposalTrackingCount { + if proposalState.TrackingCount >= t.parameters.Config.CRConfiguration.MaxProposalTrackingCount { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("reached max tracking count")), true } @@ -288,7 +288,7 @@ func (t *CRCProposalTrackingTransaction) checkCRCProposalProgressTracking( func (t *CRCProposalTrackingTransaction) checkCRCProposalRejectedTracking( params *TransactionParameters, cptPayload *payload.CRCProposalTracking, pState *crstate.ProposalState, blockHeight uint32, payloadVersion byte) error { - if blockHeight < t.parameters.Config.CRCProposalWithdrawPayloadV1Height { + if blockHeight < t.parameters.Config.CRConfiguration.CRCProposalWithdrawPayloadV1Height { return t.checkCRCProposalProgressTracking(t.parameters, cptPayload, pState, payloadVersion) } // Check stage of proposal diff --git a/core/transaction/crcproposaltransaction.go b/core/transaction/crcproposaltransaction.go index 45fe724a1..9c8667ce2 100644 --- a/core/transaction/crcproposaltransaction.go +++ b/core/transaction/crcproposaltransaction.go @@ -9,7 +9,6 @@ import ( "bytes" "errors" "fmt" - "github.com/elastos/Elastos.ELA/database" "sort" "github.com/elastos/Elastos.ELA/blockchain" @@ -18,6 +17,7 @@ import ( "github.com/elastos/Elastos.ELA/core/types/payload" crstate "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/crypto" + "github.com/elastos/Elastos.ELA/database" elaerr "github.com/elastos/Elastos.ELA/errors" "github.com/elastos/Elastos.ELA/utils" ) @@ -43,7 +43,7 @@ func (t *CRCProposalTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRCProposalDraftDataStartHeight { + if blockHeight < chainParams.CRConfiguration.CRCProposalDraftDataStartHeight { if t.PayloadVersion() != payload.CRCProposalVersion { return errors.New("payload version should be CRCProposalVersion") } @@ -59,7 +59,7 @@ func (t *CRCProposalTransaction) HeightVersionCheck() error { } switch p.ProposalType { case payload.ChangeProposalOwner, payload.CloseProposal, payload.SecretaryGeneral: - if blockHeight < chainParams.CRCProposalV1Height { + if blockHeight < chainParams.CRConfiguration.CRCProposalV1Height { return errors.New(fmt.Sprintf("not support %s CRCProposal"+ " transactio before CRCProposalV1Height", p.ProposalType.Name())) } @@ -74,7 +74,7 @@ func (t *CRCProposalTransaction) HeightVersionCheck() error { " transaction before NewCrossChainStartHeight", p.ProposalType.Name())) } default: - if blockHeight < chainParams.CRCommitteeStartHeight { + if blockHeight < chainParams.CRConfiguration.CRCommitteeStartHeight { return errors.New(fmt.Sprintf("not support %s CRCProposal"+ " transaction before CRCommitteeStartHeight", p.ProposalType.Name())) } diff --git a/core/transaction/crcproposalwithdraw.go b/core/transaction/crcproposalwithdraw.go index 447049d10..75cf1abb9 100644 --- a/core/transaction/crcproposalwithdraw.go +++ b/core/transaction/crcproposalwithdraw.go @@ -26,7 +26,7 @@ type CRCProposalWithdrawTransaction struct { func (t *CRCProposalWithdrawTransaction) CheckAttributeProgram() error { if len(t.Programs()) != 0 && t.parameters.BlockHeight < - t.parameters.Config.CRCProposalWithdrawPayloadV1Height { + t.parameters.Config.CRConfiguration.CRCProposalWithdrawPayloadV1Height { return errors.New("crcproposalwithdraw tx should have no programs") } if t.PayloadVersion() == payload.CRCProposalWithdrawDefault { @@ -73,18 +73,18 @@ func (t *CRCProposalWithdrawTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRCommitteeStartHeight { + if blockHeight < chainParams.CRConfiguration.CRCommitteeStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCommitteeStartHeight", t.TxType().Name())) } if t.PayloadVersion() == payload.CRCProposalWithdrawDefault && - blockHeight >= chainParams.CRCProposalWithdrawPayloadV1Height { + blockHeight >= chainParams.CRConfiguration.CRCProposalWithdrawPayloadV1Height { return errors.New(fmt.Sprintf("not support %s transaction "+ "after CRCProposalWithdrawPayloadV1Height", t.TxType().Name())) } if t.PayloadVersion() == payload.CRCProposalWithdrawVersion01 && - blockHeight < chainParams.CRCProposalWithdrawPayloadV1Height { + blockHeight < chainParams.CRConfiguration.CRCProposalWithdrawPayloadV1Height { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRCProposalWithdrawPayloadV1Height", t.TxType().Name())) } @@ -92,10 +92,10 @@ func (t *CRCProposalWithdrawTransaction) HeightVersionCheck() error { } func (t *CRCProposalWithdrawTransaction) SpecialContextCheck() (result elaerr.ELAError, end bool) { - + CRExpensesAddress, _ := common.Uint168FromAddress(t.parameters.Config.CRConfiguration.CRExpensesAddress) if t.PayloadVersion() == payload.CRCProposalWithdrawDefault { for _, output := range t.references { - if output.ProgramHash != t.parameters.Config.CRExpensesAddress { + if output.ProgramHash != *CRExpensesAddress { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("proposal withdrawal transaction for non-crc committee address")), true } } @@ -137,7 +137,7 @@ func (t *CRCProposalWithdrawTransaction) SpecialContextCheck() (result elaerr.EL // Check output[1] if exist must equal with CRCComitteeAddresss if len(t.Outputs()) > 1 { - if t.Outputs()[1].ProgramHash != t.parameters.Config.CRExpensesAddress { + if t.Outputs()[1].ProgramHash != *CRExpensesAddress { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("txn.Outputs()[1].ProgramHash !=CRCComitteeAddresss")), true } } @@ -159,7 +159,7 @@ func (t *CRCProposalWithdrawTransaction) SpecialContextCheck() (result elaerr.EL if withdrawPayload.Amount != withdrawAmount { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("withdrawPayload.Amount != withdrawAmount ")), true } - if withdrawPayload.Amount <= t.parameters.Config.RealWithdrawSingleFee { + if withdrawPayload.Amount <= t.parameters.Config.CRConfiguration.RealWithdrawSingleFee { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("withdraw amount should be bigger than RealWithdrawSingleFee")), true } } diff --git a/core/transaction/dposv2claimrewardrealwithdrawtransaction.go b/core/transaction/dposv2claimrewardrealwithdrawtransaction.go index 4cdabc74f..8468fb727 100644 --- a/core/transaction/dposv2claimrewardrealwithdrawtransaction.go +++ b/core/transaction/dposv2claimrewardrealwithdrawtransaction.go @@ -75,10 +75,10 @@ func (t *DposV2ClaimRewardRealWithdrawTransaction) SpecialContextCheck() (result if !output.ProgramHash.IsEqual(txInfo.Recipient) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid real withdraw output address")), true } - if output.Value != txInfo.Amount-t.parameters.Config.RealWithdrawSingleFee { + if output.Value != txInfo.Amount-t.parameters.Config.CRConfiguration.RealWithdrawSingleFee { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("invalid real withdraw output "+ "amount:%s, need to be:%s", - output.Value, txInfo.Amount-t.parameters.Config.RealWithdrawSingleFee))), true + output.Value, txInfo.Amount-t.parameters.Config.CRConfiguration.RealWithdrawSingleFee))), true } if _, ok := txsMap[hash]; ok { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("duplicated real withdraw transactions hash")), true @@ -95,10 +95,10 @@ func (t *DposV2ClaimRewardRealWithdrawTransaction) SpecialContextCheck() (result for _, o := range t.Outputs() { outputAmount += o.Value } - if inputAmount-outputAmount != t.parameters.Config.RealWithdrawSingleFee*common.Fixed64(txsCount) { + if inputAmount-outputAmount != t.parameters.Config.CRConfiguration.RealWithdrawSingleFee*common.Fixed64(txsCount) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("invalid real withdraw transaction"+ " fee:%s, need to be:%s, txsCount:%d", inputAmount-outputAmount, - t.parameters.Config.RealWithdrawSingleFee*common.Fixed64(txsCount), txsCount))), true + t.parameters.Config.CRConfiguration.RealWithdrawSingleFee*common.Fixed64(txsCount), txsCount))), true } return nil, false diff --git a/core/transaction/dposv2claimrewardtransaction.go b/core/transaction/dposv2claimrewardtransaction.go index 9c46f3f49..02b910660 100644 --- a/core/transaction/dposv2claimrewardtransaction.go +++ b/core/transaction/dposv2claimrewardtransaction.go @@ -9,13 +9,13 @@ import ( "bytes" "errors" "fmt" - "github.com/elastos/Elastos.ELA/utils" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" elaerr "github.com/elastos/Elastos.ELA/errors" + "github.com/elastos/Elastos.ELA/utils" "github.com/elastos/Elastos.ELA/vm" ) @@ -87,7 +87,7 @@ func (t *DPoSV2ClaimRewardTransaction) SpecialContextCheck() (elaerr.ELAError, b return elaerr.Simple(elaerr.ErrTxPayload, errors.New("claim reward exceeded , max claim reward "+claimAmount.String())), true } - if claimReward.Value <= t.parameters.Config.RealWithdrawSingleFee { + if claimReward.Value <= t.parameters.Config.CRConfiguration.RealWithdrawSingleFee { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("claim reward should be bigger than RealWithdrawSingleFee")), true } diff --git a/core/transaction/exchangevotes.go b/core/transaction/exchangevotes.go index f9e20ac99..122b8ab5c 100644 --- a/core/transaction/exchangevotes.go +++ b/core/transaction/exchangevotes.go @@ -10,7 +10,7 @@ import ( "fmt" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/contract" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" @@ -45,10 +45,10 @@ func (t *ExchangeVotesTransaction) CheckTransactionOutput() error { if len(t.Programs()) < 1 { return errors.New("invalid programs count") } - + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) // check if output address is valid for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } @@ -86,8 +86,9 @@ func (t *ExchangeVotesTransaction) CheckTransactionOutput() error { return errors.New("invalid stake address") } + StakePool, _ := common.Uint168FromAddress(t.parameters.Config.StakePool) // check output address, need to be stake pool - if t.outputs[0].ProgramHash != t.parameters.Config.StakePool { + if t.outputs[0].ProgramHash != *StakePool { return errors.New("first output address need to be stake address") } diff --git a/core/transaction/inactivearbitratorstransaction.go b/core/transaction/inactivearbitratorstransaction.go index 5ede98802..65dc4a9f4 100644 --- a/core/transaction/inactivearbitratorstransaction.go +++ b/core/transaction/inactivearbitratorstransaction.go @@ -10,9 +10,9 @@ import ( "fmt" "math" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/core/contract/program" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" @@ -31,7 +31,7 @@ func (t *InactiveArbitratorsTransaction) CheckTransactionInput() error { return nil } -func (t *InactiveArbitratorsTransaction) CheckTransactionOutput() error { +func (t *InactiveArbitratorsTransaction) CheckTransactionOutput() error { if len(t.Outputs()) > math.MaxUint16 { return errors.New("output count should not be greater than 65535(MaxUint16)") diff --git a/core/transaction/nexttrundposinfotransaction.go b/core/transaction/nexttrundposinfotransaction.go index e295338b4..40a5807a6 100644 --- a/core/transaction/nexttrundposinfotransaction.go +++ b/core/transaction/nexttrundposinfotransaction.go @@ -73,7 +73,7 @@ func (t *NextTurnDPOSInfoTransaction) SpecialContextCheck() (elaerr.ELAError, bo nextArbitrators := blockchain.DefaultLedger.Arbitrators.GetNextArbitrators() nextCRCArbitrators := blockchain.DefaultLedger.Arbitrators.GetAllNextCRCArbiters() conf := t.parameters.Config - if t.parameters.BlockHeight+uint32(conf.GeneralArbiters+len(conf.CRCArbiters)) >= + if t.parameters.BlockHeight+uint32(conf.DPoSConfiguration.NormalArbitratorsCount+len(conf.DPoSConfiguration.CRCArbiters)) >= blockchain.DefaultLedger.Arbitrators.GetDPoSV2ActiveHeight() { if !isNextArbitratorsSameV1(nextTurnDPOSInfo, nextArbitrators, nextCRCArbitrators) { log.Warnf("[checkNextTurnDPOSInfoTransaction] CRPublicKeys %v, DPOSPublicKeys%v\n", diff --git a/core/transaction/registercrtransaction.go b/core/transaction/registercrtransaction.go index e04b3ac1f..4ee356fd7 100644 --- a/core/transaction/registercrtransaction.go +++ b/core/transaction/registercrtransaction.go @@ -39,8 +39,8 @@ func (t *RegisterCRTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRVotingStartHeight || - (blockHeight < chainParams.RegisterCRByDIDHeight && + if blockHeight < chainParams.CRConfiguration.CRVotingStartHeight || + (blockHeight < chainParams.CRConfiguration.RegisterCRByDIDHeight && t.PayloadVersion() != payload.CRInfoVersion) { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRVotingStartHeight", t.TxType().Name())) @@ -101,7 +101,7 @@ func (t *RegisterCRTransaction) SpecialContextCheck() (elaerr.ELAError, bool) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid cid address")), true } - if t.parameters.BlockHeight >= t.parameters.Config.RegisterCRByDIDHeight && + if t.parameters.BlockHeight >= t.parameters.Config.CRConfiguration.RegisterCRByDIDHeight && t.PayloadVersion() == payload.CRInfoDIDVersion { // get DID program hash diff --git a/core/transaction/registerproducertransaction.go b/core/transaction/registerproducertransaction.go index 6258e653e..cde826ae6 100644 --- a/core/transaction/registerproducertransaction.go +++ b/core/transaction/registerproducertransaction.go @@ -9,15 +9,15 @@ import ( "bytes" "errors" "fmt" - "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/contract" - crstate "github.com/elastos/Elastos.ELA/cr/state" - "github.com/elastos/Elastos.ELA/vm" "github.com/elastos/Elastos.ELA/blockchain" + "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/types/payload" + crstate "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/crypto" elaerr "github.com/elastos/Elastos.ELA/errors" + "github.com/elastos/Elastos.ELA/vm" ) type RegisterProducerTransaction struct { @@ -142,7 +142,7 @@ func (t *RegisterProducerTransaction) SpecialContextCheck() (elaerr.ELAError, bo return elaerr.Simple(elaerr.ErrTxPayload, errors.New("there must be only one deposit address in outputs")), true } } else if t.PayloadVersion() == payload.ProducerInfoDposV2Version { - if t.parameters.BlockHeight+t.parameters.Config.DPoSV2DepositCoinMinLockTime >= info.StakeUntil { + if t.parameters.BlockHeight+t.parameters.Config.DPoSConfiguration.DPoSV2DepositCoinMinLockTime >= info.StakeUntil { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("v2 producer StakeUntil less than DPoSV2DepositCoinMinLockTime")), true } //if info.StakeUntil > t.parameters.BlockHeight+t.parameters.Config.DPoSV2MaxVotesLockTime { diff --git a/core/transaction/returncrdepositcointransaction.go b/core/transaction/returncrdepositcointransaction.go index 91244e31d..c5814d852 100644 --- a/core/transaction/returncrdepositcointransaction.go +++ b/core/transaction/returncrdepositcointransaction.go @@ -66,7 +66,7 @@ func (t *ReturnCRDepositCoinTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRVotingStartHeight { + if blockHeight < chainParams.CRConfiguration.CRVotingStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRVotingStartHeight", t.TxType().Name())) } diff --git a/core/transaction/returndepositcointransaction.go b/core/transaction/returndepositcointransaction.go index 90a454f47..46fd706cc 100644 --- a/core/transaction/returndepositcointransaction.go +++ b/core/transaction/returndepositcointransaction.go @@ -21,7 +21,7 @@ type ReturnDepositCoinTransaction struct { func (t *ReturnDepositCoinTransaction) CheckAttributeProgram() error { - if t.parameters.BlockHeight >= t.parameters.Config.CRVotingStartHeight { + if t.parameters.BlockHeight >= t.parameters.Config.CRConfiguration.CRVotingStartHeight { if len(t.Programs()) != 1 { return errors.New("return deposit coin transactions should have one and only one program") } diff --git a/core/transaction/returnsidechaindepositcointransaction.go b/core/transaction/returnsidechaindepositcointransaction.go index 0e15f9ecc..28007c352 100644 --- a/core/transaction/returnsidechaindepositcointransaction.go +++ b/core/transaction/returnsidechaindepositcointransaction.go @@ -12,7 +12,7 @@ import ( "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" @@ -35,8 +35,9 @@ func (t *ReturnSideChainDepositCoinTransaction) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } diff --git a/core/transaction/returnvotes.go b/core/transaction/returnvotes.go index 11b15c6f8..09fbb3b37 100644 --- a/core/transaction/returnvotes.go +++ b/core/transaction/returnvotes.go @@ -77,7 +77,7 @@ func (t *ReturnVotesTransaction) SpecialContextCheck() (result elaerr.ELAError, } // Value must bigger than RealWithdrawSingleFee - if pl.Value <= t.parameters.Config.RealWithdrawSingleFee { + if pl.Value <= t.parameters.Config.CRConfiguration.RealWithdrawSingleFee { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid return votes value")), true } diff --git a/core/transaction/reverttodpostransaction.go b/core/transaction/reverttodpostransaction.go index 15eb2c817..4f763c522 100644 --- a/core/transaction/reverttodpostransaction.go +++ b/core/transaction/reverttodpostransaction.go @@ -88,7 +88,7 @@ func (t *RevertToDPOSTransaction) IsAllowedInPOWConsensus() bool { } func (t *RevertToDPOSTransaction) HeightVersionCheck() error { - if t.parameters.BlockHeight < t.parameters.Config.RevertToPOWStartHeight { + if t.parameters.BlockHeight < t.parameters.Config.DPoSConfiguration.RevertToPOWStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before RevertToPOWStartHeight", t.TxType().Name())) } diff --git a/core/transaction/reverttopowtransaction.go b/core/transaction/reverttopowtransaction.go index 1e89bcccb..69eec9289 100644 --- a/core/transaction/reverttopowtransaction.go +++ b/core/transaction/reverttopowtransaction.go @@ -26,7 +26,7 @@ func (t *RevertToPOWTransaction) CheckTransactionInput() error { return nil } -func (t *RevertToPOWTransaction) CheckTransactionOutput() error { +func (t *RevertToPOWTransaction) CheckTransactionOutput() error { if len(t.Outputs()) > math.MaxUint16 { return errors.New("output count should not be greater than 65535(MaxUint16)") @@ -59,7 +59,7 @@ func (t *RevertToPOWTransaction) IsAllowedInPOWConsensus() bool { } func (t *RevertToPOWTransaction) HeightVersionCheck() error { - if t.parameters.BlockHeight < t.parameters.Config.RevertToPOWStartHeight { + if t.parameters.BlockHeight < t.parameters.Config.DPoSConfiguration.RevertToPOWStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before RevertToPOWStartHeight", t.TxType().Name())) } @@ -80,7 +80,7 @@ func (t *RevertToPOWTransaction) SpecialContextCheck() (result elaerr.ELAError, switch p.Type { case payload.NoBlock: lastBlockTime := int64(t.parameters.BlockChain.BestChain.Timestamp) - noBlockTime := t.parameters.Config.RevertToPOWNoBlockTime + noBlockTime := t.parameters.Config.DPoSConfiguration.RevertToPOWNoBlockTime if t.parameters.TimeStamp == 0 { // is not in block, check by local time. diff --git a/core/transaction/sidechainpowtransaction.go b/core/transaction/sidechainpowtransaction.go index cfe334f47..86e29b6a6 100644 --- a/core/transaction/sidechainpowtransaction.go +++ b/core/transaction/sidechainpowtransaction.go @@ -13,7 +13,7 @@ import ( "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" @@ -74,8 +74,9 @@ func (t *SideChainPOWTransaction) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } diff --git a/core/transaction/transactionCheckParameter.go b/core/transaction/transactionCheckParameter.go index c619c1529..7a8f9ec97 100644 --- a/core/transaction/transactionCheckParameter.go +++ b/core/transaction/transactionCheckParameter.go @@ -17,7 +17,7 @@ type TransactionParameters struct { BlockHeight uint32 TimeStamp uint32 - Config *config.Params + Config *config.Configuration BlockChain *blockchain.BlockChain ProposalsUsedAmount common.Fixed64 } diff --git a/core/transaction/transactionchecker.go b/core/transaction/transactionchecker.go index 1dcb8bf2d..d02a62b1f 100644 --- a/core/transaction/transactionchecker.go +++ b/core/transaction/transactionchecker.go @@ -14,6 +14,7 @@ import ( "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/contract" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" @@ -190,7 +191,7 @@ func (t *DefaultChecker) CheckTransactionSize() error { return nil } -//validate the transaction of duplicate UTXO input +// validate the transaction of duplicate UTXO input func (t *DefaultChecker) CheckTransactionInput() error { txn := t.parameters.Transaction if len(txn.Inputs()) <= 0 { @@ -225,8 +226,9 @@ func (t *DefaultChecker) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range txn.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } @@ -508,7 +510,7 @@ func (t *DefaultChecker) checkVoteCRContent(blockHeight uint32, if payloadVersion < outputpayload.VoteProducerAndCRVersion { return errors.New("payload VoteProducerVersion not support vote CR") } - if blockHeight >= t.parameters.Config.CheckVoteCRCountHeight { + if blockHeight >= t.parameters.Config.CRConfiguration.CheckVoteCRCountHeight { if len(content.CandidateVotes) > outputpayload.MaxVoteProducersPerTransaction { return errors.New("invalid count of CR candidates ") } @@ -570,7 +572,7 @@ func (t *DefaultChecker) checkInvalidUTXO(txn interfaces.Transaction) error { return err } if referTxn.IsCoinBaseTx() { - if currentHeight-referTxn.LockTime() < t.parameters.Config.CoinbaseMaturity { + if currentHeight-referTxn.LockTime() < t.parameters.Config.PowConfiguration.CoinbaseMaturity { return errors.New("the utxo of coinbase is locking") } } else if referTxn.IsNewSideChainPowTx() { @@ -643,8 +645,9 @@ func checkTransactionDepositUTXO(txn interfaces.Transaction, references map[*com } func checkDestructionAddress(references map[*common2.Input]common2.Output) error { + DestroyELAAddress, _ := common.Uint168FromAddress(config.DestroyELAAddress) for _, output := range references { - if output.ProgramHash == config.DestroyELAAddress { + if output.ProgramHash == *DestroyELAAddress { return errors.New("cannot use utxo from the destruction address") } } @@ -667,14 +670,16 @@ func (t *DefaultChecker) checkTransactionFee(tx interfaces.Transaction, referenc func checkOutputProgramHash(height uint32, programHash common.Uint168) error { // main version >= 88812 if height >= config.DefaultParams.CheckAddressHeight { + CRAssetsAddress, _ := common.Uint168FromAddress(config.CRAssetsAddress) + CRCExpensesAddress, _ := common.Uint168FromAddress(config.CRCExpensesAddress) var empty = common.Uint168{} if programHash.IsEqual(empty) { return nil } - if programHash.IsEqual(config.CRAssetsAddress) { + if programHash.IsEqual(*CRAssetsAddress) { return nil } - if programHash.IsEqual(config.CRCExpensesAddress) { + if programHash.IsEqual(*CRCExpensesAddress) { return nil } @@ -717,7 +722,7 @@ func checkOutputPayload(output *common2.Output) error { func checkAssetPrecision(txn interfaces.Transaction) error { for _, output := range txn.Outputs() { - if !checkAmountPrecise(output.Value, config.ELAPrecision) { + if !checkAmountPrecise(output.Value, core.ELAPrecision) { return errors.New("the precision of asset is incorrect") } } diff --git a/core/transaction/transferassettransaction.go b/core/transaction/transferassettransaction.go index 67ff944d8..5912cc196 100644 --- a/core/transaction/transferassettransaction.go +++ b/core/transaction/transferassettransaction.go @@ -10,7 +10,7 @@ import ( "math" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/contract" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" @@ -33,8 +33,9 @@ func (t *TransferAssetTransaction) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } @@ -144,7 +145,7 @@ func (t *TransferAssetTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight >= chainParams.CRVotingStartHeight { + if blockHeight >= chainParams.CRConfiguration.CRVotingStartHeight { return nil } if t.Version() >= common2.TxVersion09 { diff --git a/core/transaction/transfercrosschainassettransaction.go b/core/transaction/transfercrosschainassettransaction.go index 024824f79..b99f6ffb2 100644 --- a/core/transaction/transfercrosschainassettransaction.go +++ b/core/transaction/transfercrosschainassettransaction.go @@ -8,10 +8,10 @@ package transaction import ( "bytes" "errors" + "github.com/elastos/Elastos.ELA/core" "math" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" @@ -23,7 +23,7 @@ type TransferCrossChainAssetTransaction struct { BaseTransaction } -func (t *TransferCrossChainAssetTransaction) CheckTransactionOutput() error { +func (t *TransferCrossChainAssetTransaction) CheckTransactionOutput() error { blockHeight := t.parameters.BlockHeight if len(t.Outputs()) > math.MaxUint16 { return errors.New("output count should not be greater than 65535(MaxUint16)") @@ -35,8 +35,9 @@ func (t *TransferCrossChainAssetTransaction) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } diff --git a/core/transaction/txdeserialize_test.go b/core/transaction/txdeserialize_test.go index 2cc47fb2a..acd52375e 100644 --- a/core/transaction/txdeserialize_test.go +++ b/core/transaction/txdeserialize_test.go @@ -15,7 +15,7 @@ func init() { functions.GetTransactionByBytes = GetTransactionByBytes functions.CreateTransaction = CreateTransaction functions.GetTransactionParameters = GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestDeserializeTransaction(t *testing.T) { diff --git a/core/transaction/unregistercrtransaction.go b/core/transaction/unregistercrtransaction.go index 9c0486960..ec144d48c 100644 --- a/core/transaction/unregistercrtransaction.go +++ b/core/transaction/unregistercrtransaction.go @@ -37,7 +37,7 @@ func (t *UnregisterCRTransaction) HeightVersionCheck() error { blockHeight := t.parameters.BlockHeight chainParams := t.parameters.Config - if blockHeight < chainParams.CRVotingStartHeight { + if blockHeight < chainParams.CRConfiguration.CRVotingStartHeight { return errors.New(fmt.Sprintf("not support %s transaction "+ "before CRVotingStartHeight", t.TxType().Name())) } diff --git a/core/transaction/updatecrtransaction.go b/core/transaction/updatecrtransaction.go index fa5bc3d12..74046d22a 100644 --- a/core/transaction/updatecrtransaction.go +++ b/core/transaction/updatecrtransaction.go @@ -63,7 +63,7 @@ func (t *UpdateCRTransaction) SpecialContextCheck() (elaerr.ELAError, bool) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid cid address")), true } - if t.parameters.BlockHeight >= t.parameters.Config.RegisterCRByDIDHeight && + if t.parameters.BlockHeight >= t.parameters.Config.CRConfiguration.RegisterCRByDIDHeight && t.PayloadVersion() == payload.CRInfoDIDVersion { // get DID program hash diff --git a/core/transaction/updateproducertransaction.go b/core/transaction/updateproducertransaction.go index e0ea32d9e..de583ec7a 100644 --- a/core/transaction/updateproducertransaction.go +++ b/core/transaction/updateproducertransaction.go @@ -119,7 +119,7 @@ func (t *UpdateProducerTransaction) SpecialContextCheck() (elaerr.ELAError, bool if producer.State() != state.Active { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("only active producer can update to DPoSV1V2")), true } - if t.parameters.BlockHeight+t.parameters.Config.DPoSV2DepositCoinMinLockTime >= info.StakeUntil { + if t.parameters.BlockHeight+t.parameters.Config.DPoSConfiguration.DPoSV2DepositCoinMinLockTime >= info.StakeUntil { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("v2 producer StakeUntil less than DPoSV2DepositCoinMinLockTime")), true } } @@ -231,7 +231,7 @@ func (t *UpdateProducerTransaction) additionalProducerInfoCheck(info *payload.Pr } } - for _, p := range t.parameters.Config.CRCArbiters { + for _, p := range t.parameters.Config.DPoSConfiguration.CRCArbiters { if p == common.BytesToHexString(info.NodePublicKey) { return errors.New("node public key can't equal with CR Arbiters") } diff --git a/core/transaction/votesrealwithdrawtx.go b/core/transaction/votesrealwithdrawtx.go index 47c920c77..9233de1d8 100644 --- a/core/transaction/votesrealwithdrawtx.go +++ b/core/transaction/votesrealwithdrawtx.go @@ -75,10 +75,10 @@ func (t *VotesRealWithdrawTransaction) SpecialContextCheck() (result elaerr.ELAE if !output.ProgramHash.IsEqual(txInfo.Recipient) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid real votes withdraw output address")), true } - if output.Value != txInfo.Amount-t.parameters.Config.RealWithdrawSingleFee { + if output.Value != txInfo.Amount-t.parameters.Config.CRConfiguration.RealWithdrawSingleFee { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("invalid real votes withdraw output "+ "amount:%s, need to be:%s", - output.Value, txInfo.Amount-t.parameters.Config.RealWithdrawSingleFee))), true + output.Value, txInfo.Amount-t.parameters.Config.CRConfiguration.RealWithdrawSingleFee))), true } if _, ok := txsMap[realReturnVotes.ReturnVotesTXHash]; ok { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("duplicated real votes withdraw transactions hash")), true @@ -95,10 +95,10 @@ func (t *VotesRealWithdrawTransaction) SpecialContextCheck() (result elaerr.ELAE for _, o := range t.Outputs() { outputAmount += o.Value } - if inputAmount-outputAmount != t.parameters.Config.RealWithdrawSingleFee*common.Fixed64(txsCount) { + if inputAmount-outputAmount != t.parameters.Config.CRConfiguration.RealWithdrawSingleFee*common.Fixed64(txsCount) { return elaerr.Simple(elaerr.ErrTxPayload, errors.New(fmt.Sprintf("invalid real votes withdraw transaction"+ " fee:%s, need to be:%s, txsCount:%d", inputAmount-outputAmount, - t.parameters.Config.RealWithdrawSingleFee*common.Fixed64(txsCount), txsCount))), true + t.parameters.Config.CRConfiguration.RealWithdrawSingleFee*common.Fixed64(txsCount), txsCount))), true } return nil, false diff --git a/core/transaction/voting.go b/core/transaction/voting.go index 22850cefd..bf4d2f7c0 100644 --- a/core/transaction/voting.go +++ b/core/transaction/voting.go @@ -221,7 +221,7 @@ func (t *VotingTransaction) SpecialContextCheck() (result elaerr.ELAError, end b if content.VotesInfo.LockTime > producer.Info().StakeUntil { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("new lock time > producer StakeUntil")), true } - if content.VotesInfo.LockTime-vote.BlockHeight > t.parameters.Config.DPoSV2MaxVotesLockTime { + if content.VotesInfo.LockTime-vote.BlockHeight > t.parameters.Config.DPoSConfiguration.DPoSV2MaxVotesLockTime { return elaerr.Simple(elaerr.ErrTxPayload, errors.New("invalid lock time > DPoSV2MaxVotesLockTime")), true } if !bytes.Equal(vote.Info[0].Candidate, content.VotesInfo.Candidate) { @@ -363,8 +363,8 @@ func (t *VotingTransaction) checkDPoSV2Content(content payload.VotesContent, } lockTime := cv.LockTime - t.parameters.BlockHeight if cv.LockTime <= t.parameters.BlockHeight || cv.LockTime > lockUntil || - lockTime < t.parameters.Config.DPoSV2MinVotesLockTime || - lockTime > t.parameters.Config.DPoSV2MaxVotesLockTime { + lockTime < t.parameters.Config.DPoSConfiguration.DPoSV2MinVotesLockTime || + lockTime > t.parameters.Config.DPoSConfiguration.DPoSV2MaxVotesLockTime { return errors.New("invalid DPoS 2.0 votes lock time") } diff --git a/core/transaction/withdrawfromsidechaintransaction.go b/core/transaction/withdrawfromsidechaintransaction.go index 540b912c6..d3eff7bce 100644 --- a/core/transaction/withdrawfromsidechaintransaction.go +++ b/core/transaction/withdrawfromsidechaintransaction.go @@ -9,19 +9,20 @@ import ( "bytes" "encoding/hex" "errors" - "github.com/elastos/Elastos.ELA/database" "math" "math/big" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/contract" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" + "github.com/elastos/Elastos.ELA/database" "github.com/elastos/Elastos.ELA/dpos/state" elaerr "github.com/elastos/Elastos.ELA/errors" ) @@ -42,8 +43,9 @@ func (t *WithdrawFromSideChainTransaction) CheckTransactionOutput() error { // check if output address is valid specialOutputCount := 0 + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, output := range t.Outputs() { - if output.AssetID != config.ELAAssetID { + if output.AssetID != *ELAAssetID { return errors.New("asset ID in output is invalid") } @@ -145,15 +147,15 @@ func (t *WithdrawFromSideChainTransaction) checkWithdrawFromSideChainTransaction return err } - if height >= t.parameters.Config.CRClaimDPOSNodeStartHeight { + if height >= t.parameters.Config.CRConfiguration.CRClaimDPOSNodeStartHeight { var arbiters []*state.ArbiterInfo var minCount uint32 - if height >= t.parameters.Config.DPOSNodeCrossChainHeight { + if height >= t.parameters.Config.DPoSConfiguration.DPOSNodeCrossChainHeight { arbiters = blockchain.DefaultLedger.Arbitrators.GetArbitrators() - minCount = uint32(t.parameters.Config.GeneralArbiters) + 1 + minCount = uint32(t.parameters.Config.DPoSConfiguration.NormalArbitratorsCount) + 1 } else { arbiters = blockchain.DefaultLedger.Arbitrators.GetCRCArbiters() - minCount = t.parameters.Config.CRAgreementCount + minCount = t.parameters.Config.CRConfiguration.CRAgreementCount } var arbitersCount int for _, c := range arbiters { @@ -243,12 +245,12 @@ func (t *WithdrawFromSideChainTransaction) checkWithdrawFromSideChainTransaction } var arbiters []*state.ArbiterInfo var minCount uint32 - if height >= t.parameters.Config.DPOSNodeCrossChainHeight { + if height >= t.parameters.Config.DPoSConfiguration.DPOSNodeCrossChainHeight { arbiters = blockchain.DefaultLedger.Arbitrators.GetArbitrators() - minCount = uint32(t.parameters.Config.GeneralArbiters) + 1 + minCount = uint32(t.parameters.Config.DPoSConfiguration.NormalArbitratorsCount) + 1 } else { arbiters = blockchain.DefaultLedger.Arbitrators.GetCRCArbiters() - minCount = t.parameters.Config.CRAgreementCount + minCount = t.parameters.Config.CRConfiguration.CRAgreementCount } var arbitersCount int for _, c := range arbiters { @@ -279,15 +281,15 @@ func (t *WithdrawFromSideChainTransaction) checkWithdrawFromSideChainTransaction currentHeight := t.parameters.BlockHeight if currentHeight <= config.Parameters.CRConfiguration.CRClaimDPOSNodeStartHeight { - if len(pld.Signers) < (int(t.parameters.Config.CRMemberCount)*2/3 + 1) { + if len(pld.Signers) < (int(t.parameters.Config.CRConfiguration.MemberCount)*2/3 + 1) { return errors.New("Signers number must be bigger than 2/3+1 CRMemberCount") } } else if currentHeight < config.Parameters.DPoSConfiguration.DPOSNodeCrossChainHeight { - if len(pld.Signers) < (int(t.parameters.Config.CRMemberCount) * 2 / 3) { + if len(pld.Signers) < (int(t.parameters.Config.CRConfiguration.MemberCount) * 2 / 3) { return errors.New("Signers number must be bigger than 2/3 CRMemberCount") } } else { - if len(pld.Signers) < (int(t.parameters.Config.CRMemberCount)*2/3 + 1) { + if len(pld.Signers) < (int(t.parameters.Config.CRConfiguration.MemberCount)*2/3 + 1) { return errors.New("Signers number must be bigger than 2/3+1 CRMemberCount") } } diff --git a/core/types/dposheader.go b/core/types/dposheader.go index 769db6eab..59bea6dd1 100644 --- a/core/types/dposheader.go +++ b/core/types/dposheader.go @@ -6,10 +6,10 @@ package types import ( - common2 "github.com/elastos/Elastos.ELA/core/types/common" "io" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" ) diff --git a/core/types/functions/function.go b/core/types/functions/function.go index 1bf5c693b..ffaf8dd95 100644 --- a/core/types/functions/function.go +++ b/core/types/functions/function.go @@ -6,9 +6,9 @@ package functions import ( - "github.com/elastos/Elastos.ELA/common" "io" + "github.com/elastos/Elastos.ELA/common" pg "github.com/elastos/Elastos.ELA/core/contract/program" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" diff --git a/core/types/interfaces/initpayload.go b/core/types/interfaces/initpayload.go index e7ff66be2..17ad811e2 100644 --- a/core/types/interfaces/initpayload.go +++ b/core/types/interfaces/initpayload.go @@ -7,6 +7,7 @@ package interfaces import ( "errors" + common "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" ) diff --git a/core/types/outputpayload/exchangevotes.go b/core/types/outputpayload/exchangevotes.go index 3ea5d188c..287afd204 100644 --- a/core/types/outputpayload/exchangevotes.go +++ b/core/types/outputpayload/exchangevotes.go @@ -8,10 +8,10 @@ package outputpayload import ( "errors" "fmt" - "github.com/elastos/Elastos.ELA/core/contract" "io" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract" ) const ExchangeVotesOutputVersion byte = 0x00 diff --git a/core/types/outputpayload/vote_test.go b/core/types/outputpayload/vote_test.go index 8b54671f8..646c41617 100644 --- a/core/types/outputpayload/vote_test.go +++ b/core/types/outputpayload/vote_test.go @@ -7,10 +7,10 @@ package outputpayload import ( "bytes" - "github.com/stretchr/testify/assert" "testing" "github.com/elastos/Elastos.ELA/common" + "github.com/stretchr/testify/assert" ) const ( diff --git a/core/types/payload/returnsidechaindepositcoin.go b/core/types/payload/returnsidechaindepositcoin.go index 75683f08c..260ec435e 100644 --- a/core/types/payload/returnsidechaindepositcoin.go +++ b/core/types/payload/returnsidechaindepositcoin.go @@ -6,8 +6,9 @@ package payload import ( - "github.com/elastos/Elastos.ELA/common" "io" + + "github.com/elastos/Elastos.ELA/common" ) const ReturnSideChainDepositCoinVersion byte = 0x00 diff --git a/cr/state/checkpoint.go b/cr/state/checkpoint.go index 8ad0c9299..a62a919c5 100644 --- a/cr/state/checkpoint.go +++ b/cr/state/checkpoint.go @@ -146,7 +146,7 @@ func (c *Checkpoint) OnInit() { } func (c *Checkpoint) StartHeight() uint32 { - return c.committee.Params.CRVotingStartHeight + return c.committee.Params.CRConfiguration.CRVotingStartHeight } func (c *Checkpoint) Serialize(w io.Writer) (err error) { diff --git a/cr/state/committee.go b/cr/state/committee.go index b12fee24d..80c68b132 100644 --- a/cr/state/committee.go +++ b/cr/state/committee.go @@ -18,6 +18,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" @@ -38,7 +39,7 @@ type Committee struct { KeyFrame mtx sync.RWMutex state *State - Params *config.Params + Params *config.Configuration manager *ProposalManager firstHistory *utils.History inactiveCRHistory *utils.History @@ -56,6 +57,7 @@ type Committee struct { outputs []*common2.OutputInfo) (interfaces.Transaction, error) getUTXO func(programHash *common.Uint168) ([]*common2.UTXO, error) getCurrentArbiters func() [][]byte + CkpManager *checkpoint.Manager } type CommitteeKeyFrame struct { @@ -149,7 +151,7 @@ func (c *Committee) GetCROnDutyStartHeight() uint32 { func (c *Committee) GetCROnDutyPeriod() uint32 { c.mtx.RLock() defer c.mtx.RUnlock() - return c.Params.CRDutyPeriod + return c.Params.CRConfiguration.DutyPeriod } func (c *Committee) GetCRVotingStartHeight() uint32 { @@ -161,7 +163,7 @@ func (c *Committee) GetCRVotingStartHeight() uint32 { func (c *Committee) GetCRVotingPeriod() uint32 { c.mtx.RLock() defer c.mtx.RUnlock() - return c.Params.CRVotingPeriod + return c.Params.CRConfiguration.VotingPeriod } func (c *Committee) IsProposalAllowed(height uint32) bool { @@ -416,7 +418,7 @@ func (c *Committee) updateCandidatesDepositCoin(height uint32) { canceledCandidates := c.state.GetCandidates(Canceled) for _, candidate := range canceledCandidates { - if height-candidate.CancelHeight == c.Params.CRDepositLockupBlocks { + if height-candidate.CancelHeight == c.Params.CRConfiguration.DepositLockupBlocks { updateDepositCoin(candidate.Info.CID, candidate) } } @@ -424,7 +426,7 @@ func (c *Committee) updateCandidatesDepositCoin(height uint32) { func (c *Committee) ProcessBlock(block *types.Block, confirm *payload.Confirm) { c.mtx.Lock() - if block.Height < c.Params.CRVotingStartHeight { + if block.Height < c.Params.CRConfiguration.CRVotingStartHeight { c.mtx.Unlock() return } @@ -459,7 +461,7 @@ func (c *Committee) ProcessBlock(block *types.Block, confirm *payload.Confirm) { c.updateCRInactiveStatus(c.inactiveCRHistory, block.Height) c.inactiveCRHistory.Commit(block.Height) - if block.Height >= c.Params.CRCProposalWithdrawPayloadV1Height && + if block.Height >= c.Params.CRConfiguration.CRCProposalWithdrawPayloadV1Height && len(c.manager.WithdrawableTxInfo) != 0 { c.createRealWithdrawTransaction(block.Height) } @@ -473,8 +475,8 @@ func (c *Committee) ProcessBlock(block *types.Block, confirm *payload.Confirm) { c.appropriationHistory.Commit(block.Height) } else { if c.CRAssetsAddressUTXOCount >= - c.Params.MaxCRAssetsAddressUTXOCount+c.Params.CoinbaseMaturity && - block.Height >= c.Params.CRAssetsRectifyTransactionHeight { + c.Params.CRConfiguration.MaxCRAssetsAddressUTXOCount+c.Params.PowConfiguration.CoinbaseMaturity && + block.Height >= c.Params.CRConfiguration.CRAssetsRectifyTransactionHeight { c.createRectifyCRAssetsTransaction(block.Height) } } @@ -504,12 +506,12 @@ func (c *Committee) checkAndSetMemberToInactive(history *utils.History, height u if len(m.DPOSPublicKey) == 0 && m.MemberState == MemberElected { history.Append(height, func() { m.MemberState = MemberInactive - if height >= c.Params.ChangeCommitteeNewCRHeight { + if height >= c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { c.state.UpdateCRInactivePenalty(m.Info.CID, height) } }, func() { m.MemberState = MemberElected - if height >= c.Params.ChangeCommitteeNewCRHeight { + if height >= c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { c.state.RevertUpdateCRInactivePenalty(m.Info.CID, height) } }) @@ -519,7 +521,7 @@ func (c *Committee) checkAndSetMemberToInactive(history *utils.History, height u func (c *Committee) updateCRInactiveStatus(history *utils.History, height uint32) { if height > c.Params.DPoSV2StartHeight { - if height < c.LastVotingStartHeight+c.Params.CRVotingPeriod+c.Params.CRClaimPeriod { + if height < c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod+c.Params.CRConfiguration.CRClaimPeriod { return } @@ -530,12 +532,12 @@ func (c *Committee) updateCRInactiveStatus(history *utils.History, height uint32 if c.state.CurrentSession == 0 { return } else if c.state.CurrentSession == 1 { - if height < c.Params.CRClaimDPOSNodeStartHeight+c.Params.CRClaimDPOSNodePeriod { + if height < c.Params.CRConfiguration.CRClaimDPOSNodeStartHeight+c.Params.CRConfiguration.CRClaimDPOSNodePeriod { return } c.checkAndSetMemberToInactive(history, height) } else { - if height < c.LastCommitteeHeight+c.Params.CRClaimDPOSNodePeriod { + if height < c.LastCommitteeHeight+c.Params.CRConfiguration.CRClaimDPOSNodePeriod { return } c.checkAndSetMemberToInactive(history, height) @@ -578,7 +580,7 @@ func (c *Committee) updateCRMembers( } if member.ImpeachmentVotes >= common.Fixed64(float64(circulation)* - c.Params.VoterRejectPercentage/100.0) { + c.Params.CRConfiguration.VoterRejectPercentage/100.0) { c.transferCRMemberState(member, height) newImpeachedCount++ impeachedCRMembersCID[member.Info.CID] = struct{}{} @@ -869,7 +871,7 @@ func (c *Committee) recordCurrentStageAmount(height uint32, lockedAmount common. c.appropriationHistory.Append(height, func() { c.CommitteeUsedAmount = c.CRCCommitteeUsedAmount c.AppropriationAmount = common.Fixed64(float64(c.CRCFoundationBalance- - lockedAmount) * c.Params.CRCAppropriatePercentage / 100.0) + lockedAmount) * c.Params.CRConfiguration.CRCAppropriatePercentage / 100.0) c.CRCCurrentStageAmount = c.CRCCommitteeBalance + c.AppropriationAmount log.Infof("current stage amount:%s,appropriation amount:%s", c.CRCCurrentStageAmount, c.AppropriationAmount) @@ -885,9 +887,11 @@ func (c *Committee) recordCurrentStageAmount(height uint32, lockedAmount common. } func (c *Committee) recordCRCRelatedAddressOutputs(block *types.Block) { + CRExpensesAddress, _ := common.Uint168FromAddress(c.Params.CRConfiguration.CRExpensesAddress) + CRAssetsAddress, _ := common.Uint168FromAddress(c.Params.CRConfiguration.CRAssetsAddress) for _, tx := range block.Transactions { for i, output := range tx.Outputs() { - if output.ProgramHash.IsEqual(c.Params.CRAssetsAddress) { + if output.ProgramHash.IsEqual(*CRAssetsAddress) { key := common2.NewOutPoint(tx.Hash(), uint16(i)).ReferKey() value := output.Value c.firstHistory.Append(block.Height, func() { @@ -895,7 +899,7 @@ func (c *Committee) recordCRCRelatedAddressOutputs(block *types.Block) { }, func() { delete(c.state.CRCFoundationOutputs, key) }) - } else if output.ProgramHash.IsEqual(c.Params.CRExpensesAddress) { + } else if output.ProgramHash.IsEqual(*CRExpensesAddress) { key := common2.NewOutPoint(tx.Hash(), uint16(i)).ReferKey() value := output.Value c.firstHistory.Append(block.Height, func() { @@ -938,11 +942,11 @@ func (c *Committee) recordLastVotingStartHeight(height uint32) { func (c *Committee) getNextVotingStartHeight(height uint32) uint32 { if height >= c.Params.DPoSV2StartHeight { - return c.LastCommitteeHeight + c.Params.CRDutyPeriod - - c.Params.CRVotingPeriod - c.Params.CRClaimPeriod - 1 + return c.LastCommitteeHeight + c.Params.CRConfiguration.DutyPeriod - + c.Params.CRConfiguration.VotingPeriod - c.Params.CRConfiguration.CRClaimPeriod - 1 } - return c.LastCommitteeHeight + c.Params.CRDutyPeriod - - c.Params.CRVotingPeriod - 1 + return c.LastCommitteeHeight + c.Params.CRConfiguration.DutyPeriod - + c.Params.CRConfiguration.VotingPeriod - 1 } func (c *Committee) tryStartVotingPeriod(height uint32) (inElection bool) { @@ -960,7 +964,7 @@ func (c *Committee) tryStartVotingPeriod(height uint32) (inElection bool) { } } if impeachedCount+newImpeachedCount > - c.Params.CRMemberCount-c.Params.CRAgreementCount { + c.Params.CRConfiguration.MemberCount-c.Params.CRConfiguration.CRAgreementCount { lastVotingStartHeight := c.LastVotingStartHeight inElectionPeriod := c.InElectionPeriod @@ -984,7 +988,7 @@ func (c *Committee) tryStartVotingPeriod(height uint32) (inElection bool) { if (v.MemberState == MemberElected || v.MemberState == MemberInactive || v.MemberState == MemberIllegal) && v.ImpeachmentVotes < common.Fixed64(float64(c.CirculationAmount)* - c.Params.VoterRejectPercentage/100.0) { + c.Params.CRConfiguration.VoterRejectPercentage/100.0) { c.terminateCRMember(v, height) } } @@ -1327,38 +1331,38 @@ func (c *Committee) Recover(checkpoint *Checkpoint) { } func (c *Committee) shouldEndVoting(height uint32) bool { - return height == c.LastVotingStartHeight+c.Params.CRVotingPeriod + return height == c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod } func (c *Committee) shouldChangeCommittee(height uint32) bool { if c.LastCommitteeHeight == 0 { - if height < c.Params.CRCommitteeStartHeight { + if height < c.Params.CRConfiguration.CRCommitteeStartHeight { return false - } else if height == c.Params.CRCommitteeStartHeight { + } else if height == c.Params.CRConfiguration.CRCommitteeStartHeight { return true } } if c.LastVotingStartHeight == 0 { - return height == c.LastCommitteeHeight+c.Params.CRDutyPeriod + return height == c.LastCommitteeHeight+c.Params.CRConfiguration.DutyPeriod } if height >= c.Params.DPoSV2StartHeight { - return height == c.LastCommitteeHeight+c.Params.CRDutyPeriod || - height == c.LastVotingStartHeight+c.Params.CRVotingPeriod+c.Params.CRClaimPeriod + return height == c.LastCommitteeHeight+c.Params.CRConfiguration.DutyPeriod || + height == c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod+c.Params.CRConfiguration.CRClaimPeriod } - return height == c.LastVotingStartHeight+c.Params.CRVotingPeriod + return height == c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod } func (c *Committee) shouldCleanHistory(height uint32) bool { if height >= c.Params.DPoSV2StartHeight { return c.LastVotingStartHeight == c.LastCommitteeHeight+ - c.Params.CRDutyPeriod-c.Params.CRVotingPeriod-c.Params.CRClaimPeriod + c.Params.CRConfiguration.DutyPeriod-c.Params.CRConfiguration.VotingPeriod-c.Params.CRConfiguration.CRClaimPeriod } return c.LastVotingStartHeight == c.LastCommitteeHeight+ - c.Params.CRDutyPeriod-c.Params.CRVotingPeriod + c.Params.CRConfiguration.DutyPeriod-c.Params.CRConfiguration.VotingPeriod } func (c *Committee) isInVotingPeriod(height uint32) bool { @@ -1366,34 +1370,34 @@ func (c *Committee) isInVotingPeriod(height uint32) bool { inVotingPeriod := func(committeeUpdateHeight uint32) bool { if height >= c.Params.DPoSV2StartHeight { return height >= c.LastVotingStartHeight && - height < c.LastVotingStartHeight+c.Params.CRVotingPeriod + height < c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod } - return height >= committeeUpdateHeight-c.Params.CRVotingPeriod && + return height >= committeeUpdateHeight-c.Params.CRConfiguration.VotingPeriod && height < committeeUpdateHeight } - if c.LastCommitteeHeight < c.Params.CRCommitteeStartHeight && - height <= c.Params.CRCommitteeStartHeight { - return height >= c.Params.CRVotingStartHeight && - height < c.Params.CRCommitteeStartHeight + if c.LastCommitteeHeight < c.Params.CRConfiguration.CRCommitteeStartHeight && + height <= c.Params.CRConfiguration.CRCommitteeStartHeight { + return height >= c.Params.CRConfiguration.CRVotingStartHeight && + height < c.Params.CRConfiguration.CRCommitteeStartHeight } else { if !c.InElectionPeriod { if c.LastVotingStartHeight == 0 { return true } - return height < c.LastVotingStartHeight+c.Params.CRVotingPeriod + return height < c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod } - return inVotingPeriod(c.LastCommitteeHeight + c.Params.CRDutyPeriod) + return inVotingPeriod(c.LastCommitteeHeight + c.Params.CRConfiguration.DutyPeriod) } } func (c *Committee) isInClaimPeriod(height uint32) bool { if height >= c.Params.DPoSV2StartHeight { - return height >= c.LastVotingStartHeight+c.Params.CRVotingPeriod && - height <= c.LastVotingStartHeight+c.Params.CRVotingPeriod+c.Params.CRClaimPeriod + return height >= c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod && + height <= c.LastVotingStartHeight+c.Params.CRConfiguration.VotingPeriod+c.Params.CRConfiguration.CRClaimPeriod } return height >= c.LastCommitteeHeight && - height <= c.LastCommitteeHeight+c.Params.CRClaimDPOSNodePeriod + height <= c.LastCommitteeHeight+c.Params.CRConfiguration.CRClaimDPOSNodePeriod } func (c *Committee) updateNextCommitteeMembers(height uint32) error { @@ -1408,8 +1412,9 @@ func (c *Committee) updateNextCommitteeMembers(height uint32) error { } } oriLastVotingStartHeight := c.LastVotingStartHeight - if activeCandidatesCount < c.Params.CRMemberCount { + if activeCandidatesCount < c.Params.CRConfiguration.MemberCount { c.committeeHistory.Append(height, func() { + c.LastVotingStartHeight = height }, func() { c.LastVotingStartHeight = oriLastVotingStartHeight @@ -1475,8 +1480,7 @@ func (c *Committee) changeCommitteeMembers(height uint32) error { activeCandidatesCount++ } } - - if activeCandidatesCount < c.Params.CRMemberCount { + if activeCandidatesCount < c.Params.CRConfiguration.MemberCount { c.committeeHistory.Append(height, func() { c.InElectionPeriod = false c.LastVotingStartHeight = height @@ -1508,8 +1512,8 @@ func (c *Committee) changeCommitteeMembers(height uint32) error { func (c *Committee) processNextMembers(height uint32, activeCandidates []*Candidate) map[common.Uint168]*CRMember { - newMembers := make(map[common.Uint168]*CRMember, c.Params.CRMemberCount) - for i := 0; i < int(c.Params.CRMemberCount); i++ { + newMembers := make(map[common.Uint168]*CRMember, c.Params.CRConfiguration.MemberCount) + for i := 0; i < int(c.Params.CRConfiguration.MemberCount); i++ { newMembers[activeCandidates[i].Info.DID] = c.generateMember(activeCandidates[i]) } @@ -1636,8 +1640,8 @@ func (c *Committee) processCurrentMembersHistory(height uint32, } } - newMembers := make(map[common.Uint168]*CRMember, c.Params.CRMemberCount) - for i := 0; i < int(c.Params.CRMemberCount); i++ { + newMembers := make(map[common.Uint168]*CRMember, c.Params.CRConfiguration.MemberCount) + for i := 0; i < int(c.Params.CRConfiguration.MemberCount); i++ { newMembers[activeCandidates[i].Info.DID] = c.generateMember(activeCandidates[i]) } @@ -1706,7 +1710,7 @@ func (c *Committee) processCurrentCandidates(height uint32, continue } // if canceled enough blocks, no need to update deposit coin again. - if ca.State == Canceled && height-ca.CancelHeight >= c.Params.CRDepositLockupBlocks { + if ca.State == Canceled && height-ca.CancelHeight >= c.Params.CRConfiguration.DepositLockupBlocks { continue } // if CR deposit coin is returned, no need to update deposit coin again. @@ -1745,13 +1749,13 @@ func (c *Committee) getMemberPenalty(height uint32, member *CRMember, impeached if impeached { electionCount = height - c.LastCommitteeHeight - member.PenaltyBlockCount } else { - electionCount = c.Params.CRDutyPeriod - member.PenaltyBlockCount + electionCount = c.Params.CRConfiguration.DutyPeriod - member.PenaltyBlockCount } if member.MemberState == MemberInactive { electionCount -= 1 } var electionRate float64 - electionRate = float64(electionCount) / float64(c.Params.CRDutyPeriod) + electionRate = float64(electionCount) / float64(c.Params.CRConfiguration.DutyPeriod) // Calculate penalty by vote proposal count. var voteCount int for _, v := range c.manager.ProposalSession[c.state.CurrentSession] { @@ -1779,7 +1783,7 @@ func (c *Committee) getMemberPenalty(height uint32, member *CRMember, impeached height, member.Info.NickName, currentPenalty, penalty, finalPenalty) log.Info("electionRate:", electionRate, "voteRate:", voteRate, "electionCount:", electionCount, "PenaltyBlockCount:", member.PenaltyBlockCount, - "dutyPeriod:", c.Params.CRDutyPeriod, "voteCount:", voteCount, + "dutyPeriod:", c.Params.CRConfiguration.DutyPeriod, "voteCount:", voteCount, "proposalsCount:", proposalsCount) return finalPenalty @@ -1994,7 +1998,7 @@ func (c *Committee) TryUpdateCRMemberInactivity(did common.Uint168, return } - if height < c.Params.ChangeCommitteeNewCRHeight { + if height < c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { if needReset { crMember.InactiveCountingHeight = 0 return @@ -2004,11 +2008,11 @@ func (c *Committee) TryUpdateCRMemberInactivity(did common.Uint168, crMember.InactiveCountingHeight = height } - if height-crMember.InactiveCountingHeight >= c.Params.MaxInactiveRounds { + if height-crMember.InactiveCountingHeight >= c.Params.DPoSConfiguration.MaxInactiveRounds { crMember.MemberState = MemberInactive log.Info("at Height", height, crMember.Info.NickName, "changed to inactive", "InactiveCountingHeight:", crMember.InactiveCountingHeight, - "MaxInactiveRounds:", c.Params.MaxInactiveRounds) + "MaxInactiveRounds:", c.Params.DPoSConfiguration.MaxInactiveRounds) crMember.InactiveCountingHeight = 0 } } else { @@ -2018,13 +2022,13 @@ func (c *Committee) TryUpdateCRMemberInactivity(did common.Uint168, } crMember.InactiveCount++ - if crMember.InactiveCount >= c.Params.MaxInactiveRounds && + if crMember.InactiveCount >= c.Params.DPoSConfiguration.MaxInactiveRounds && crMember.MemberState == MemberElected { log.Info("at Height", height, crMember.Info.NickName, "changed to inactive", "InactiveCount:", crMember.InactiveCount, - "MaxInactiveRounds:", c.Params.MaxInactiveRounds) + "MaxInactiveRounds:", c.Params.DPoSConfiguration.MaxInactiveRounds) crMember.MemberState = MemberInactive - if height >= c.Params.ChangeCommitteeNewCRHeight { + if height >= c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { c.state.UpdateCRInactivePenalty(crMember.Info.CID, height) } crMember.InactiveCount = 0 @@ -2054,11 +2058,11 @@ func (c *Committee) TryRevertCRMemberInactivity(did common.Uint168, return } - if height < c.Params.ChangeCommitteeNewCRHeight { + if height < c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { crMember.MemberState = oriState crMember.InactiveCountingHeight = oriInactiveCount } else { - if oriInactiveCount < c.Params.MaxInactiveRounds && + if oriInactiveCount < c.Params.DPoSConfiguration.MaxInactiveRounds && crMember.MemberState == MemberInactive { c.state.RevertUpdateCRInactivePenalty(crMember.Info.CID, height) } @@ -2104,10 +2108,11 @@ func (c *Committee) Snapshot() *CommitteeKeyFrame { return keyFrame } -func NewCommittee(params *config.Params) *Committee { +func NewCommittee(params *config.Configuration, ckpManager *checkpoint.Manager) *Committee { committee := &Committee{ state: NewState(params), Params: params, + CkpManager: ckpManager, KeyFrame: *NewKeyFrame(), manager: NewProposalManager(params), firstHistory: utils.NewHistory(maxHistoryCapacity), @@ -2115,8 +2120,8 @@ func NewCommittee(params *config.Params) *Committee { committeeHistory: utils.NewHistory(maxHistoryCapacity), appropriationHistory: utils.NewHistory(maxHistoryCapacity), } - committee.manager.InitSecretaryGeneralPublicKey(params.SecretaryGeneral) + committee.manager.InitSecretaryGeneralPublicKey(params.CRConfiguration.SecretaryGeneral) committee.state.SetManager(committee.manager) - params.CkpManager.Register(NewCheckpoint(committee)) + committee.CkpManager.Register(NewCheckpoint(committee)) return committee } diff --git a/cr/state/committeeaction.go b/cr/state/committeeaction.go index ae85e2a95..eee3feac0 100644 --- a/cr/state/committeeaction.go +++ b/cr/state/committeeaction.go @@ -139,12 +139,12 @@ func (c *Committee) inactiveMembersByWithdrawKeys(height uint32, c.state.History.Append(height, func() { member.MemberState = MemberInactive log.Infof("[checkWithdrawAndInactiveCR] Set %s to inactive", member.Info.NickName) - if height >= c.Params.ChangeCommitteeNewCRHeight { + if height >= c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { c.state.UpdateCRInactivePenalty(member.Info.CID, height) } }, func() { member.MemberState = MemberElected - if height >= c.Params.ChangeCommitteeNewCRHeight { + if height >= c.Params.CRConfiguration.ChangeCommitteeNewCRHeight { c.state.RevertUpdateCRInactivePenalty(member.Info.CID, height) } }) @@ -507,6 +507,9 @@ func (c *Committee) processCancelImpeachment(height uint32, member []byte, // processCRCRelatedAmount takes a transaction, if the transaction takes a previous // output to CRC related address then try to subtract the vote. func (c *Committee) processCRCAddressRelatedTx(tx interfaces.Transaction, height uint32) { + CRAssetsAddress, _ := common.Uint168FromAddress(c.Params.CRConfiguration.CRAssetsAddress) + CRExpensesAddress, _ := common.Uint168FromAddress(c.Params.CRConfiguration.CRExpensesAddress) + DestroyELAAddress, _ := common.Uint168FromAddress(c.Params.DestroyELAAddress) if tx.IsCRCProposalTx() { proposal := tx.Payload().(*payload.CRCProposal) var budget common.Fixed64 @@ -540,7 +543,7 @@ func (c *Committee) processCRCAddressRelatedTx(tx interfaces.Transaction, height for _, output := range tx.Outputs() { amount := output.Value - if output.ProgramHash.IsEqual(c.Params.CRAssetsAddress) { + if output.ProgramHash.IsEqual(*CRAssetsAddress) { c.state.History.Append(height, func() { c.CRAssetsAddressUTXOCount++ c.CRCFoundationBalance += amount @@ -548,13 +551,13 @@ func (c *Committee) processCRCAddressRelatedTx(tx interfaces.Transaction, height c.CRAssetsAddressUTXOCount-- c.CRCFoundationBalance -= amount }) - } else if output.ProgramHash.IsEqual(c.Params.CRExpensesAddress) { + } else if output.ProgramHash.IsEqual(*CRExpensesAddress) { c.state.History.Append(height, func() { c.CRCCommitteeBalance += amount }, func() { c.CRCCommitteeBalance -= amount }) - } else if output.ProgramHash.IsEqual(c.Params.DestroyELAAddress) { + } else if output.ProgramHash.IsEqual(*DestroyELAAddress) { c.state.History.Append(height, func() { c.DestroyedAmount += amount }, func() { diff --git a/cr/state/keyframe.go b/cr/state/keyframe.go index 90b834d84..2db0ac025 100644 --- a/cr/state/keyframe.go +++ b/cr/state/keyframe.go @@ -7,10 +7,10 @@ package state import ( "bytes" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "io" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils" diff --git a/cr/state/proposalmanager.go b/cr/state/proposalmanager.go index fd23162a5..e344e8c44 100644 --- a/cr/state/proposalmanager.go +++ b/cr/state/proposalmanager.go @@ -7,12 +7,12 @@ package state import ( "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" - "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils" @@ -75,7 +75,7 @@ func (status ProposalStatus) String() string { // ProposalManager used to manage all proposals existing in block chain. type ProposalManager struct { ProposalKeyFrame - params *config.Params + params *config.Configuration history *utils.History } @@ -91,7 +91,7 @@ func (p *ProposalManager) tryCancelReservedCustomID(height uint32) { } } -//only init use +// only init use func (p *ProposalManager) InitSecretaryGeneralPublicKey(publicKey string) { p.SecretaryGeneralPublicKey = publicKey } @@ -354,7 +354,7 @@ func (p *ProposalManager) transferRegisteredState(proposalState *ProposalState, } oriVoteStartHeight := proposalState.VoteStartHeight - if agreedCount >= p.params.CRAgreementCount { + if agreedCount >= p.params.CRConfiguration.CRAgreementCount { status = CRAgreed p.history.Append(height, func() { proposalState.Status = CRAgreed @@ -457,7 +457,7 @@ func (p *ProposalManager) dealProposal(proposalState *ProposalState, unusedAmoun func (p *ProposalManager) transferCRAgreedState(proposalState *ProposalState, height uint32, circulation common.Fixed64) (status ProposalStatus) { if proposalState.VotersRejectAmount >= common.Fixed64(float64(circulation)* - p.params.VoterRejectPercentage/100.0) { + p.params.CRConfiguration.VoterRejectPercentage/100.0) { status = VoterCanceled oriBudgetsStatus := make(map[uint8]BudgetStatus) for k, v := range proposalState.BudgetsStatus { @@ -520,11 +520,12 @@ func isSpecialProposal(proposalType payload.CRCProposalType) bool { } // shouldEndCRCVote returns if current Height should end CRC vote about -// the specified proposal. +// +// the specified proposal. func (p *ProposalManager) shouldEndCRCVote(RegisterHeight uint32, height uint32) bool { //proposal.RegisterHeight - return RegisterHeight+p.params.ProposalCRVotingPeriod <= height + return RegisterHeight+p.params.CRConfiguration.ProposalCRVotingPeriod <= height } func (p *ProposalManager) addRegisterSideChainInfo(proposalState *ProposalState, height uint32) { @@ -580,12 +581,12 @@ func (p *ProposalManager) removeRegisterSideChainInfo(proposalState *ProposalSta // about the specified proposal. func (p *ProposalManager) shouldEndPublicVote(VoteStartHeight uint32, height uint32) bool { - return VoteStartHeight+p.params.ProposalPublicVotingPeriod <= + return VoteStartHeight+p.params.CRConfiguration.ProposalPublicVotingPeriod <= height } func (p *ProposalManager) isProposalFull(did common.Uint168) bool { - return p.getProposalCount(did) >= int(p.params.MaxCommitteeProposalCount) + return p.getProposalCount(did) >= int(p.params.CRConfiguration.MaxCommitteeProposalCount) } func (p *ProposalManager) getProposalCount(did common.Uint168) int { @@ -916,7 +917,7 @@ func (p *ProposalManager) proposalTracking(tx interfaces.Transaction, return } -func NewProposalManager(params *config.Params) *ProposalManager { +func NewProposalManager(params *config.Configuration) *ProposalManager { return &ProposalManager{ ProposalKeyFrame: *NewProposalKeyFrame(), params: params, diff --git a/cr/state/state.go b/cr/state/state.go index 399390c49..cb0d46c34 100644 --- a/cr/state/state.go +++ b/cr/state/state.go @@ -7,6 +7,7 @@ package state import ( "errors" + "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" @@ -42,7 +43,7 @@ type State struct { GetTxReference func(tx interfaces.Transaction) ( map[*common2.Input]common2.Output, error) - params *config.Params + params *config.Configuration History *utils.History } @@ -62,7 +63,7 @@ func (s *State) UpdateCRInactivePenalty(cid common.Uint168, height uint32) { if !ok { return } - depositInfo.Penalty += s.params.InactivePenalty + depositInfo.Penalty += s.params.DPoSConfiguration.InactivePenalty } func (s *State) RevertUpdateCRInactivePenalty(cid common.Uint168, height uint32) { @@ -70,7 +71,7 @@ func (s *State) RevertUpdateCRInactivePenalty(cid common.Uint168, height uint32) if !ok { return } - var penalty = s.params.InactivePenalty + var penalty = s.params.DPoSConfiguration.InactivePenalty if depositInfo.Penalty < penalty { depositInfo.Penalty = common.Fixed64(0) } else { @@ -397,7 +398,7 @@ func (s *State) returnDeposit(tx interfaces.Transaction, height uint32) { s.DepositInfo[*cid].DepositAmount if candidate.State == Canceled && - height-candidate.CancelHeight > s.params.CRDepositLockupBlocks && + height-candidate.CancelHeight > s.params.CRConfiguration.DepositLockupBlocks && balance <= s.params.MinTransactionFee { returnCandidateAction(candidate, candidate.State) } @@ -621,7 +622,7 @@ func (s *State) getCandidateFromMap(cmap map[common.Uint168]*Candidate, return result } -func NewState(chainParams *config.Params) *State { +func NewState(chainParams *config.Configuration) *State { return &State{ StateKeyFrame: *NewStateKeyFrame(), params: chainParams, diff --git a/crypto/common.go b/crypto/common.go index 099485226..7e8f47967 100644 --- a/crypto/common.go +++ b/crypto/common.go @@ -7,6 +7,7 @@ package crypto import ( "errors" + "github.com/elastos/Elastos.ELA/common" ) diff --git a/dpos/account/account.go b/dpos/account/account.go index b49a87867..630268ad1 100644 --- a/dpos/account/account.go +++ b/dpos/account/account.go @@ -8,8 +8,8 @@ package account import ( "bytes" - "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/account" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" ) diff --git a/dpos/arbitrator.go b/dpos/arbitrator.go index 157e6191a..eb6e9cac7 100644 --- a/dpos/arbitrator.go +++ b/dpos/arbitrator.go @@ -38,7 +38,7 @@ type Config struct { Server elanet.Server TxMemPool *mempool.TxPool BlockMemPool *mempool.BlockPool - ChainParams *config.Params + ChainParams *config.Configuration Broadcast func(msg p2p.Message) AnnounceAddr func() NodeVersion string @@ -201,10 +201,10 @@ func (a *Arbitrator) OnBlockReceived(b *types.Block, confirmed bool) { if !a.cfg.Server.IsCurrent() { return } - if b.Height >= a.cfg.ChainParams.RevertToPOWStartHeight { + if b.Height >= a.cfg.ChainParams.DPoSConfiguration.RevertToPOWStartHeight { lastBlockTimestamp := int64(a.cfg.Arbitrators.GetLastBlockTimestamp()) localTimestamp := a.cfg.Chain.TimeSource.AdjustedTime().Unix() - if localTimestamp-lastBlockTimestamp >= a.cfg.ChainParams.StopConfirmBlockTime { + if localTimestamp-lastBlockTimestamp >= a.cfg.ChainParams.DPoSConfiguration.StopConfirmBlockTime { return } } @@ -279,7 +279,7 @@ func NewArbitrator(account account.Account, cfg Config) (*Arbitrator, error) { TimeSource: medianTime, }) - consensus := manager.NewConsensus(dposManager, cfg.ChainParams.ToleranceDuration, dposHandlerSwitch) + consensus := manager.NewConsensus(dposManager, cfg.ChainParams.DPoSConfiguration.SignTolerance, dposHandlerSwitch) proposalDispatcher, illegalMonitor := manager.NewDispatcherAndIllegalMonitor( manager.ProposalDispatcherConfig{ EventMonitor: eventMonitor, diff --git a/dpos/log/eventmonitor.go b/dpos/log/eventmonitor.go index aafad8f6f..913c2229d 100644 --- a/dpos/log/eventmonitor.go +++ b/dpos/log/eventmonitor.go @@ -6,10 +6,10 @@ package log import ( - common2 "github.com/elastos/Elastos.ELA/core/types/common" "time" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" ) diff --git a/dpos/manager/dposmanager.go b/dpos/manager/dposmanager.go index 01c845702..a68fcc344 100644 --- a/dpos/manager/dposmanager.go +++ b/dpos/manager/dposmanager.go @@ -107,7 +107,7 @@ type AbnormalRecovering interface { type DPOSManagerConfig struct { PublicKey []byte Arbitrators state.Arbitrators - ChainParams *config.Params + ChainParams *config.Configuration TimeSource dtime.MedianTimeSource Server elanet.Server } @@ -127,7 +127,7 @@ type DPOSManager struct { arbitrators state.Arbitrators blockPool *mempool.BlockPool txPool *mempool.TxPool - chainParams *config.Params + chainParams *config.Configuration timeSource dtime.MedianTimeSource server elanet.Server broadcast func(p2p.Message) diff --git a/dpos/manager/proposaldispatcher.go b/dpos/manager/proposaldispatcher.go index 1150acf39..04a379e3d 100644 --- a/dpos/manager/proposaldispatcher.go +++ b/dpos/manager/proposaldispatcher.go @@ -35,7 +35,7 @@ type ProposalDispatcherConfig struct { Network DPOSNetwork Manager *DPOSManager Account account.Account - ChainParams *config.Params + ChainParams *config.Configuration TimeSource dtime.MedianTimeSource } diff --git a/dpos/network.go b/dpos/network.go index 727ed3192..fb571989d 100644 --- a/dpos/network.go +++ b/dpos/network.go @@ -32,7 +32,7 @@ import ( const dataPathDPoS = "elastos/data/dpos" type NetworkConfig struct { - ChainParams *config.Params + ChainParams *config.Configuration Account account.Account MedianTime dtime.MedianTimeSource Listener manager.NetworkEventListener @@ -380,9 +380,9 @@ func NewDposNetwork(cfg NetworkConfig) (*network, error) { DataDir: dataPathDPoS, PID: pid, EnableHub: true, - Localhost: cfg.ChainParams.DPoSIPAddress, - MagicNumber: cfg.ChainParams.DPoSMagic, - DefaultPort: cfg.ChainParams.DPoSDefaultPort, + Localhost: cfg.ChainParams.DPoSConfiguration.IPAddress, + MagicNumber: cfg.ChainParams.DPoSConfiguration.DPoSMagic, + DefaultPort: cfg.ChainParams.DPoSConfiguration.DPoSPort, TimeSource: cfg.MedianTime, MaxNodePerHost: cfg.ChainParams.MaxNodePerHost, CreateMessage: createMessage, diff --git a/dpos/p2p/msg/getblocks.go b/dpos/p2p/msg/getblocks.go index d081a9130..d2590da7c 100644 --- a/dpos/p2p/msg/getblocks.go +++ b/dpos/p2p/msg/getblocks.go @@ -6,8 +6,9 @@ package msg import ( - "github.com/elastos/Elastos.ELA/common" "io" + + "github.com/elastos/Elastos.ELA/common" ) type GetBlocks struct { diff --git a/dpos/p2p/msg/responseblocks.go b/dpos/p2p/msg/responseblocks.go index a441753a6..2cd7b2782 100644 --- a/dpos/p2p/msg/responseblocks.go +++ b/dpos/p2p/msg/responseblocks.go @@ -8,9 +8,8 @@ package msg import ( "io" - "github.com/elastos/Elastos.ELA/core/types" - "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/types" ) //todo move to config diff --git a/dpos/p2p/peer/peer_test.go b/dpos/p2p/peer/peer_test.go index f8b3ec80e..2deb2fcb4 100644 --- a/dpos/p2p/peer/peer_test.go +++ b/dpos/p2p/peer/peer_test.go @@ -10,7 +10,6 @@ import ( "crypto/rand" "errors" "fmt" - peer2 "github.com/elastos/Elastos.ELA/p2p/peer" "io" "net" "testing" @@ -22,6 +21,7 @@ import ( "github.com/elastos/Elastos.ELA/dpos/p2p/peer" "github.com/elastos/Elastos.ELA/p2p" pmsg "github.com/elastos/Elastos.ELA/p2p/msg" + peer2 "github.com/elastos/Elastos.ELA/p2p/peer" ) func createMessage(hdr p2p.Header, r net.Conn) (message p2p.Message, err error) { diff --git a/dpos/p2p/server_test.go b/dpos/p2p/server_test.go index b0ce4f994..4edac1ef2 100644 --- a/dpos/p2p/server_test.go +++ b/dpos/p2p/server_test.go @@ -7,7 +7,6 @@ package p2p import ( "fmt" - peer2 "github.com/elastos/Elastos.ELA/p2p/peer" "io" "math/rand" "net" @@ -19,6 +18,7 @@ import ( "github.com/elastos/Elastos.ELA/dpos/p2p/msg" "github.com/elastos/Elastos.ELA/dpos/p2p/peer" "github.com/elastos/Elastos.ELA/p2p" + peer2 "github.com/elastos/Elastos.ELA/p2p/peer" "github.com/elastos/Elastos.ELA/utils/test" "github.com/stretchr/testify/assert" diff --git a/dpos/state/arbitrators.go b/dpos/state/arbitrators.go index 66d9031a4..a3d596c2c 100644 --- a/dpos/state/arbitrators.go +++ b/dpos/state/arbitrators.go @@ -18,6 +18,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/types" @@ -68,11 +69,12 @@ type ArbiterInfo struct { type Arbiters struct { *State *degradation - ChainParams *config.Params + ChainParams *config.Configuration CRCommittee *state.Committee bestHeight func() uint32 bestBlockHash func() *common.Uint256 getBlockByHeight func(uint32) (*types.Block, error) + CkpManager *checkpoint.Manager mtx sync.Mutex started bool @@ -358,13 +360,13 @@ func (a *Arbiters) RollbackTo(height uint32) error { func (a *Arbiters) GetDutyIndexByHeight(height uint32) (index int) { a.mtx.Lock() - if height >= a.ChainParams.DPOSNodeCrossChainHeight { + if height >= a.ChainParams.DPoSConfiguration.DPOSNodeCrossChainHeight { if len(a.CurrentArbitrators) == 0 { index = 0 } else { index = a.DutyIndex % len(a.CurrentArbitrators) } - } else if height >= a.ChainParams.CRClaimDPOSNodeStartHeight { + } else if height >= a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { if len(a.CurrentCRCArbitersMap) == 0 { index = 0 } else { @@ -498,7 +500,7 @@ func (a *Arbiters) normalChange(height uint32) error { } func (a *Arbiters) notifyNextTurnDPOSInfoTx(blockHeight, versionHeight uint32, forceChange bool) { - if blockHeight+uint32(a.ChainParams.GeneralArbiters+len(a.ChainParams.CRCArbiters)) >= a.DPoSV2ActiveHeight { + if blockHeight+uint32(a.ChainParams.DPoSConfiguration.NormalArbitratorsCount+len(a.ChainParams.DPoSConfiguration.CRCArbiters)) >= a.DPoSV2ActiveHeight { nextTurnDPOSInfoTx := a.createNextTurnDPOSInfoTransactionV1(blockHeight, forceChange) go events.Notify(events.ETAppendTxToTxPool, nextTurnDPOSInfoTx) @@ -843,7 +845,7 @@ func (a *Arbiters) accumulateReward(block *types.Block, confirm *payload.Confirm var accumulative common.Fixed64 accumulative = a.accumulativeReward var dposReward common.Fixed64 - if block.Height < a.ChainParams.CRVotingStartHeight || !a.forceChanged { + if block.Height < a.ChainParams.CRConfiguration.CRVotingStartHeight || !a.forceChanged { dposReward = a.getBlockDPOSReward(block) accumulative += dposReward } @@ -942,11 +944,11 @@ func (a *Arbiters) distributeDPOSReward(height uint32, reward common.Fixed64) (roundReward map[common.Uint168]common.Fixed64, change common.Fixed64, err error) { var realDPOSReward common.Fixed64 - if height >= a.ChainParams.ChangeCommitteeNewCRHeight+2*uint32(len(a.CurrentArbitrators)) { + if height >= a.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight+2*uint32(len(a.CurrentArbitrators)) { roundReward, realDPOSReward, err = a.distributeWithNormalArbitratorsV3(height, reward) - } else if height >= a.ChainParams.CRClaimDPOSNodeStartHeight+2*uint32(len(a.CurrentArbitrators)) { + } else if height >= a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight+2*uint32(len(a.CurrentArbitrators)) { roundReward, realDPOSReward, err = a.distributeWithNormalArbitratorsV2(height, reward) - } else if height >= a.ChainParams.CRCommitteeStartHeight+2*uint32(len(a.CurrentArbitrators)) { + } else if height >= a.ChainParams.CRConfiguration.CRCommitteeStartHeight+2*uint32(len(a.CurrentArbitrators)) { roundReward, realDPOSReward, err = a.distributeWithNormalArbitratorsV1(height, reward) } else { roundReward, realDPOSReward, err = a.distributeWithNormalArbitratorsV0(height, reward) @@ -959,8 +961,8 @@ func (a *Arbiters) distributeDPOSReward(height uint32, change = reward - realDPOSReward if change < 0 { log.Error("reward:", reward, "realDPOSReward:", realDPOSReward, "height:", height, - "b", a.ChainParams.CRClaimDPOSNodeStartHeight+2*uint32(len(a.CurrentArbitrators)), - "c", a.ChainParams.CRCommitteeStartHeight+2*uint32(len(a.CurrentArbitrators))) + "b", a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight+2*uint32(len(a.CurrentArbitrators)), + "c", a.ChainParams.CRConfiguration.CRCommitteeStartHeight+2*uint32(len(a.CurrentArbitrators))) return nil, 0, errors.New("real dpos reward more than reward limit") } @@ -978,16 +980,16 @@ func (a *Arbiters) distributeWithNormalArbitratorsV3(height uint32, reward commo totalBlockConfirmReward := float64(reward) * 0.25 totalTopProducersReward := float64(reward) - totalBlockConfirmReward // Consider that there is no only CR consensus. - arbitersCount := len(a.ChainParams.CRCArbiters) + a.ChainParams.GeneralArbiters + arbitersCount := len(a.ChainParams.DPoSConfiguration.CRCArbiters) + a.ChainParams.DPoSConfiguration.NormalArbitratorsCount individualBlockConfirmReward := common.Fixed64( math.Floor(totalBlockConfirmReward / float64(arbitersCount))) totalVotesInRound := a.CurrentReward.TotalVotesInRound log.Debugf("distributeWithNormalArbitratorsV3 TotalVotesInRound %f", a.CurrentReward.TotalVotesInRound) - + DestroyELAAddress, _ := common.Uint168FromAddress(a.ChainParams.DestroyELAAddress) if a.ConsensusAlgorithm == POW || len(a.CurrentArbitrators) == 0 || - len(a.ChainParams.CRCArbiters) == len(a.CurrentArbitrators) { + len(a.ChainParams.DPoSConfiguration.CRCArbiters) == len(a.CurrentArbitrators) { // if no normal DPOS node, need to destroy reward. - roundReward[a.ChainParams.DestroyELAAddress] = reward + roundReward[*DestroyELAAddress] = reward return roundReward, reward, nil } log.Debugf("totalTopProducersReward totalTopProducersReward %f", totalTopProducersReward) @@ -995,6 +997,7 @@ func (a *Arbiters) distributeWithNormalArbitratorsV3(height uint32, reward commo rewardPerVote := totalTopProducersReward / float64(totalVotesInRound) realDPOSReward := common.Fixed64(0) + for _, arbiter := range a.CurrentArbitrators { ownerHash := arbiter.GetOwnerProgramHash() rewardHash := ownerHash @@ -1004,7 +1007,7 @@ func (a *Arbiters) distributeWithNormalArbitratorsV3(height uint32, reward commo log.Debugf("1233 r =individualBlockConfirmReward %s", individualBlockConfirmReward.String()) m, ok := arbiter.(*crcArbiter) if !ok || m.crMember.MemberState != state.MemberElected { - rewardHash = a.ChainParams.DestroyELAAddress + rewardHash = *DestroyELAAddress } else if len(m.crMember.DPOSPublicKey) == 0 { nodePK := arbiter.GetNodePublicKey() ownerPK := a.getProducerKey(nodePK) @@ -1027,7 +1030,7 @@ func (a *Arbiters) distributeWithNormalArbitratorsV3(height uint32, reward commo pk := arbiter.GetOwnerPublicKey() programHash, err := contract.PublicKeyToStandardProgramHash(pk) if err != nil { - rewardHash = a.ChainParams.DestroyELAAddress + rewardHash = *DestroyELAAddress } else { rewardHash = *programHash } @@ -1058,7 +1061,7 @@ func (a *Arbiters) distributeWithNormalArbitratorsV3(height uint32, reward commo } // Abnormal CR`s reward need to be destroyed. for i := len(a.CurrentArbitrators); i < arbitersCount; i++ { - roundReward[a.ChainParams.DestroyELAAddress] += individualBlockConfirmReward + roundReward[*DestroyELAAddress] += individualBlockConfirmReward } return roundReward, realDPOSReward, nil } @@ -1069,20 +1072,20 @@ func (a *Arbiters) distributeWithNormalArbitratorsV2(height uint32, reward commo // return nil, 0, errors.New("not found arbiters when " + // "distributeWithNormalArbitratorsV2") //} - + DestroyELAAddress, _ := common.Uint168FromAddress(a.ChainParams.DestroyELAAddress) roundReward := map[common.Uint168]common.Fixed64{} totalBlockConfirmReward := float64(reward) * 0.25 totalTopProducersReward := float64(reward) - totalBlockConfirmReward // Consider that there is no only CR consensus. - arbitersCount := len(a.ChainParams.CRCArbiters) + a.ChainParams.GeneralArbiters + arbitersCount := len(a.ChainParams.DPoSConfiguration.CRCArbiters) + a.ChainParams.DPoSConfiguration.NormalArbitratorsCount individualBlockConfirmReward := common.Fixed64( math.Floor(totalBlockConfirmReward / float64(arbitersCount))) totalVotesInRound := a.CurrentReward.TotalVotesInRound if len(a.CurrentArbitrators) == 0 || - len(a.ChainParams.CRCArbiters) == len(a.CurrentArbitrators) { + len(a.ChainParams.DPoSConfiguration.CRCArbiters) == len(a.CurrentArbitrators) { //if len(a.ChainParams.CRCArbiters) == len(a.CurrentArbitrators) { // if no normal DPOS node, need to destroy reward. - roundReward[a.ChainParams.DestroyELAAddress] = reward + roundReward[*DestroyELAAddress] = reward return roundReward, reward, nil } rewardPerVote := totalTopProducersReward / float64(totalVotesInRound) @@ -1096,12 +1099,12 @@ func (a *Arbiters) distributeWithNormalArbitratorsV2(height uint32, reward commo r = individualBlockConfirmReward m, ok := arbiter.(*crcArbiter) if !ok || m.crMember.MemberState != state.MemberElected || len(m.crMember.DPOSPublicKey) == 0 { - rewardHash = a.ChainParams.DestroyELAAddress + rewardHash = *DestroyELAAddress } else { pk := arbiter.GetOwnerPublicKey() programHash, err := contract.PublicKeyToStandardProgramHash(pk) if err != nil { - rewardHash = a.ChainParams.DestroyELAAddress + rewardHash = *DestroyELAAddress } else { rewardHash = *programHash } @@ -1126,7 +1129,7 @@ func (a *Arbiters) distributeWithNormalArbitratorsV2(height uint32, reward commo } // Abnormal CR`s reward need to be destroyed. for i := len(a.CurrentArbitrators); i < arbitersCount; i++ { - roundReward[a.ChainParams.DestroyELAAddress] += individualBlockConfirmReward + roundReward[*DestroyELAAddress] += individualBlockConfirmReward } return roundReward, realDPOSReward, nil } @@ -1137,15 +1140,16 @@ func (a *Arbiters) distributeWithNormalArbitratorsV1(height uint32, reward commo return nil, 0, errors.New("not found arbiters when " + "distributeWithNormalArbitratorsV1") } - + DestroyELAAddress, _ := common.Uint168FromAddress(a.ChainParams.DestroyELAAddress) + CRCAddress, _ := common.Uint168FromAddress(a.ChainParams.CRConfiguration.CRCAddress) roundReward := map[common.Uint168]common.Fixed64{} totalBlockConfirmReward := float64(reward) * 0.25 totalTopProducersReward := float64(reward) - totalBlockConfirmReward individualBlockConfirmReward := common.Fixed64( math.Floor(totalBlockConfirmReward / float64(len(a.CurrentArbitrators)))) totalVotesInRound := a.CurrentReward.TotalVotesInRound - if len(a.ChainParams.CRCArbiters) == len(a.CurrentArbitrators) { - roundReward[a.ChainParams.CRCAddress] = reward + if len(a.ChainParams.DPoSConfiguration.CRCArbiters) == len(a.CurrentArbitrators) { + roundReward[*CRCAddress] = reward return roundReward, reward, nil } rewardPerVote := totalTopProducersReward / float64(totalVotesInRound) @@ -1158,12 +1162,12 @@ func (a *Arbiters) distributeWithNormalArbitratorsV1(height uint32, reward commo r = individualBlockConfirmReward m, ok := arbiter.(*crcArbiter) if !ok || m.crMember.MemberState != state.MemberElected { - rewardHash = a.ChainParams.DestroyELAAddress + rewardHash = *DestroyELAAddress } else { pk := arbiter.GetOwnerPublicKey() programHash, err := contract.PublicKeyToStandardProgramHash(pk) if err != nil { - rewardHash = a.ChainParams.DestroyELAAddress + rewardHash = *DestroyELAAddress } else { rewardHash = *programHash } @@ -1198,7 +1202,7 @@ func (a *Arbiters) GetCurrentNeedConnectArbiters() []peer.PID { func (a *Arbiters) getCurrentNeedConnectArbiters() []peer.PID { height := a.History.Height() + 1 - if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.PreConnectOffset { + if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.DPoSConfiguration.PreConnectOffset { return nil } @@ -1227,7 +1231,7 @@ func (a *Arbiters) GetNextNeedConnectArbiters() []peer.PID { func (a *Arbiters) getNextNeedConnectArbiters() []peer.PID { height := a.History.Height() + 1 - if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.PreConnectOffset { + if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.DPoSConfiguration.PreConnectOffset { return nil } @@ -1256,7 +1260,7 @@ func (a *Arbiters) GetNeedConnectCRArbiters() []peer.PID { func (a *Arbiters) getNeedConnectCRArbiters() []peer.PID { height := a.History.Height() + 1 - if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.PreConnectOffset { + if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.DPoSConfiguration.PreConnectOffset { return nil } @@ -1298,7 +1302,7 @@ func (a *Arbiters) GetNeedConnectArbiters() []peer.PID { func (a *Arbiters) getNeedConnectArbiters() []peer.PID { height := a.History.Height() + 1 - if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.PreConnectOffset { + if height < a.ChainParams.CRCOnlyDPOSHeight-a.ChainParams.DPoSConfiguration.PreConnectOffset { return nil } @@ -1324,7 +1328,7 @@ func (a *Arbiters) getNeedConnectArbiters() []peer.PID { } if height != a.ChainParams.CRCOnlyDPOSHeight- - a.ChainParams.PreConnectOffset { + a.ChainParams.DPoSConfiguration.PreConnectOffset { for _, v := range a.CurrentArbitrators { key := common.BytesToHexString(v.GetNodePublicKey()) var pid peer.PID @@ -1651,7 +1655,7 @@ func (a *Arbiters) GetOnDutyCrossChainArbitrator() []byte { height := a.bestHeight() if height < a.ChainParams.CRCOnlyDPOSHeight-1 { arbiter = a.GetOnDutyArbitrator() - } else if height < a.ChainParams.CRClaimDPOSNodeStartHeight { + } else if height < a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { a.mtx.Lock() crcArbiters := a.getCRCArbiters() sort.Slice(crcArbiters, func(i, j int) bool { @@ -1660,7 +1664,7 @@ func (a *Arbiters) GetOnDutyCrossChainArbitrator() []byte { ondutyIndex := int(height-a.ChainParams.CRCOnlyDPOSHeight+1) % len(crcArbiters) arbiter = crcArbiters[ondutyIndex].NodePublicKey a.mtx.Unlock() - } else if height < a.ChainParams.DPOSNodeCrossChainHeight { + } else if height < a.ChainParams.DPoSConfiguration.DPOSNodeCrossChainHeight { a.mtx.Lock() crcArbiters := a.getCRCArbiters() sort.Slice(crcArbiters, func(i, j int) bool { @@ -1692,7 +1696,7 @@ func (a *Arbiters) GetCrossChainArbiters() []*ArbiterInfo { if bestHeight < a.ChainParams.CRCOnlyDPOSHeight-1 { return a.GetArbitrators() } - if bestHeight < a.ChainParams.DPOSNodeCrossChainHeight { + if bestHeight < a.ChainParams.DPoSConfiguration.DPOSNodeCrossChainHeight { crcArbiters := a.GetCRCArbiters() sort.Slice(crcArbiters, func(i, j int) bool { return bytes.Compare(crcArbiters[i].NodePublicKey, crcArbiters[j].NodePublicKey) < 0 @@ -1705,10 +1709,10 @@ func (a *Arbiters) GetCrossChainArbiters() []*ArbiterInfo { func (a *Arbiters) GetCrossChainArbitersCount() int { if a.bestHeight() < a.ChainParams.CRCOnlyDPOSHeight-1 { - return len(a.ChainParams.OriginArbiters) + return len(a.ChainParams.DPoSConfiguration.OriginArbiters) } - return len(a.ChainParams.CRCArbiters) + return len(a.ChainParams.DPoSConfiguration.CRCArbiters) } func (a *Arbiters) GetCrossChainArbitersMajorityCount() int { @@ -1738,7 +1742,7 @@ func (a *Arbiters) GetArbitersCount() int { a.mtx.Lock() result := len(a.CurrentArbitrators) if result == 0 { - result = a.ChainParams.GeneralArbiters + len(a.ChainParams.CRCArbiters) + result = a.ChainParams.DPoSConfiguration.NormalArbitratorsCount + len(a.ChainParams.DPoSConfiguration.CRCArbiters) } a.mtx.Unlock() return result @@ -1757,7 +1761,7 @@ func (a *Arbiters) GetArbitersMajorityCount() int { if len(a.CurrentArbitrators) != 0 { currentArbitratorsCount = len(a.CurrentArbitrators) } else { - currentArbitratorsCount = len(a.ChainParams.CRCArbiters) + a.ChainParams.GeneralArbiters + currentArbitratorsCount = len(a.ChainParams.DPoSConfiguration.CRCArbiters) + a.ChainParams.DPoSConfiguration.NormalArbitratorsCount } minSignCount := int(float64(currentArbitratorsCount) * MajoritySignRatioNumerator / MajoritySignRatioDenominator) @@ -1791,12 +1795,12 @@ func (a *Arbiters) getChangeType(height uint32) (ChangeType, uint32) { // H2 - PreConnectOffset -> [updateNext, H2]: update next arbiters and let normal arbiters prepare to connect // H2 -> [normalChange, H2]: should change to new election (arbiters will have both CRC and normal arbiters) if height == a.ChainParams.CRCOnlyDPOSHeight- - a.ChainParams.PreConnectOffset { + a.ChainParams.DPoSConfiguration.PreConnectOffset { return updateNext, a.ChainParams.CRCOnlyDPOSHeight } else if height == a.ChainParams.CRCOnlyDPOSHeight { return normalChange, a.ChainParams.CRCOnlyDPOSHeight } else if height == a.ChainParams.PublicDPOSHeight- - a.ChainParams.PreConnectOffset { + a.ChainParams.DPoSConfiguration.PreConnectOffset { return updateNext, a.ChainParams.PublicDPOSHeight } else if height == a.ChainParams.PublicDPOSHeight { return normalChange, a.ChainParams.PublicDPOSHeight @@ -1808,8 +1812,8 @@ func (a *Arbiters) getChangeType(height uint32) (ChangeType, uint32) { return normalChange, height } - if height > a.ChainParams.RevertToPOWStartHeight && - a.DutyIndex == len(a.ChainParams.CRCArbiters)+a.ChainParams.GeneralArbiters-1 { + if height > a.ChainParams.DPoSConfiguration.RevertToPOWStartHeight && + a.DutyIndex == len(a.ChainParams.DPoSConfiguration.CRCArbiters)+a.ChainParams.DPoSConfiguration.NormalArbitratorsCount-1 { return normalChange, height } @@ -1899,7 +1903,7 @@ func (a *Arbiters) createNextTurnDPOSInfoTransactionV0(blockHeight uint32, force if forceChange { workingHeight = blockHeight } else { - workingHeight = blockHeight + uint32(a.ChainParams.GeneralArbiters+len(a.ChainParams.CRCArbiters)) + workingHeight = blockHeight + uint32(a.ChainParams.DPoSConfiguration.NormalArbitratorsCount+len(a.ChainParams.DPoSConfiguration.CRCArbiters)) } nextTurnDPOSInfo.WorkingHeight = workingHeight for _, v := range a.nextArbitrators { @@ -1939,7 +1943,7 @@ func (a *Arbiters) createNextTurnDPOSInfoTransactionV1(blockHeight uint32, force if forceChange { workingHeight = blockHeight } else { - workingHeight = blockHeight + uint32(a.ChainParams.GeneralArbiters+len(a.ChainParams.CRCArbiters)) + workingHeight = blockHeight + uint32(a.ChainParams.DPoSConfiguration.NormalArbitratorsCount+len(a.ChainParams.DPoSConfiguration.CRCArbiters)) } nextTurnDPOSInfo.WorkingHeight = workingHeight for _, v := range a.nextCRCArbiters { @@ -1988,7 +1992,7 @@ func (a *Arbiters) updateNextTurnInfo(height uint32, producers []ArbiterMember, sort.Slice(a.nextArbitrators, func(i, j int) bool { return bytes.Compare(a.nextArbitrators[i].GetNodePublicKey(), a.nextArbitrators[j].GetNodePublicKey()) < 0 }) - if height >= a.ChainParams.CRClaimDPOSNodeStartHeight { + if height >= a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { //need sent a NextTurnDPOSInfo tx into mempool sort.Slice(nextCRCArbiters, func(i, j int) bool { return bytes.Compare(nextCRCArbiters[i].GetNodePublicKey(), nextCRCArbiters[j].GetNodePublicKey()) < 0 @@ -2036,7 +2040,7 @@ func (a *Arbiters) getSortedProducersDposV2() []*Producer { func (a *Arbiters) getSortedProducersWithRandom(height uint32, unclaimedCount int) ([]*Producer, error) { votedProducers := a.getSortedProducers() - if height < a.ChainParams.NoCRCDPOSNodeHeight { + if height < a.ChainParams.DPoSConfiguration.NoCRCDPOSNodeHeight { return votedProducers, nil } @@ -2044,14 +2048,14 @@ func (a *Arbiters) getSortedProducersWithRandom(height uint32, unclaimedCount in // 23(may be 35) or the state is not active, need to get a candidate as // DPOS node at random. if a.LastRandomCandidateHeight != 0 && - height-a.LastRandomCandidateHeight < a.ChainParams.RandomCandidatePeriod { + height-a.LastRandomCandidateHeight < a.ChainParams.DPoSConfiguration.RandomCandidatePeriod { for i, p := range votedProducers { if common.BytesToHexString(p.info.OwnerPublicKey) == a.LastRandomCandidateOwner { - if i < unclaimedCount+a.ChainParams.GeneralArbiters-1 || p.state != Active { + if i < unclaimedCount+a.ChainParams.DPoSConfiguration.NormalArbitratorsCount-1 || p.state != Active { // need get again at random. break } - normalCount := a.ChainParams.GeneralArbiters - 1 + normalCount := a.ChainParams.DPoSConfiguration.NormalArbitratorsCount - 1 selectedCandidateIndex := i newProducers := make([]*Producer, 0, len(votedProducers)) @@ -2071,7 +2075,7 @@ func (a *Arbiters) getSortedProducersWithRandom(height uint32, unclaimedCount in return nil, err } - normalCount := a.ChainParams.GeneralArbiters - 1 + normalCount := a.ChainParams.DPoSConfiguration.NormalArbitratorsCount - 1 selectedCandidateIndex := unclaimedCount + normalCount + candidateIndex candidateProducer := votedProducers[selectedCandidateIndex] @@ -2119,7 +2123,7 @@ func (a *Arbiters) getRandomDposV2Producers(height uint32, unclaimedCount int, c producerKeys = append(producerKeys, hex.EncodeToString(vp.info.OwnerPublicKey)) } sortedProducer := make([]string, 0, len(producerKeys)) - count := a.ChainParams.GeneralArbiters + len(a.ChainParams.CRCArbiters) + count := a.ChainParams.DPoSConfiguration.NormalArbitratorsCount + len(a.ChainParams.DPoSConfiguration.CRCArbiters) if len(producerKeys) > count { for i := 0; i < count; i++ { @@ -2150,12 +2154,12 @@ func (a *Arbiters) getCandidateIndexAtRandom(height uint32, unclaimedCount, vote return 0, errors.New("invalid block hash") } rand.Seed(seed) - normalCount := a.ChainParams.GeneralArbiters - 1 + normalCount := a.ChainParams.DPoSConfiguration.NormalArbitratorsCount - 1 count := votedProducersCount - unclaimedCount - normalCount if count < 1 { return 0, errors.New("producers is not enough") } - candidatesCount := minInt(count, a.ChainParams.CandidateArbiters+1) + candidatesCount := minInt(count, a.ChainParams.DPoSConfiguration.CandidatesCount+1) return rand.Intn(candidatesCount), nil } @@ -2163,12 +2167,12 @@ func (a *Arbiters) isDposV2Active() bool { if a.DPoSV2ActiveHeight != math.MaxUint32 { return true } - return len(a.DposV2EffectedProducers) >= a.ChainParams.GeneralArbiters*3/2 + return len(a.DposV2EffectedProducers) >= a.ChainParams.DPoSConfiguration.NormalArbitratorsCount*3/2 } func (a *Arbiters) UpdateNextArbitrators(versionHeight, height uint32) error { - if height >= a.ChainParams.CRClaimDPOSNodeStartHeight { + if height >= a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { oriNeedNextTurnDPOSInfo := a.NeedNextTurnDPOSInfo a.History.Append(height, func() { a.NeedNextTurnDPOSInfo = true @@ -2187,7 +2191,7 @@ func (a *Arbiters) UpdateNextArbitrators(versionHeight, height uint32) error { if a.DPoSV2ActiveHeight == math.MaxUint32 && a.isDposV2Active() { oriHeight := height a.History.Append(height, func() { - a.DPoSV2ActiveHeight = height + a.ChainParams.CRMemberCount + uint32(a.ChainParams.GeneralArbiters) + a.DPoSV2ActiveHeight = height + a.ChainParams.CRConfiguration.MemberCount + uint32(a.ChainParams.DPoSConfiguration.NormalArbitratorsCount) }, func() { a.DPoSV2ActiveHeight = oriHeight }) @@ -2200,7 +2204,7 @@ func (a *Arbiters) UpdateNextArbitrators(versionHeight, height uint32) error { if !a.IsInactiveMode() && !a.IsUnderstaffedMode() { - count := a.ChainParams.GeneralArbiters + count := a.ChainParams.DPoSConfiguration.NormalArbitratorsCount var votedProducers []*Producer var crAndVotedProducersStr []string if a.isDposV2Active() { @@ -2217,13 +2221,13 @@ func (a *Arbiters) UpdateNextArbitrators(versionHeight, height uint32) error { var producers []ArbiterMember var err error if a.isDposV2Active() { - producers, err = a.GetDposV2NormalArbitratorsDesc(count+int(a.ChainParams.CRMemberCount), crAndVotedProducersStr, choosingCRArbiters) + producers, err = a.GetDposV2NormalArbitratorsDesc(count+int(a.ChainParams.CRConfiguration.MemberCount), crAndVotedProducersStr, choosingCRArbiters) } else { producers, err = a.GetNormalArbitratorsDesc(versionHeight, count, votedProducers, unclaimed) } if err != nil { - if height > a.ChainParams.ChangeCommitteeNewCRHeight { + if height > a.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { return err } if err := a.tryHandleError(versionHeight, err); err != nil { @@ -2242,8 +2246,8 @@ func (a *Arbiters) UpdateNextArbitrators(versionHeight, height uint32) error { }) } else { if !a.isDposV2Active() { - if height >= a.ChainParams.NoCRCDPOSNodeHeight { - count := len(a.ChainParams.CRCArbiters) + a.ChainParams.GeneralArbiters + if height >= a.ChainParams.DPoSConfiguration.NoCRCDPOSNodeHeight { + count := len(a.ChainParams.DPoSConfiguration.CRCArbiters) + a.ChainParams.DPoSConfiguration.NormalArbitratorsCount var newSelected bool for _, p := range votedProducers { producer := p @@ -2294,7 +2298,7 @@ func (a *Arbiters) UpdateNextArbitrators(versionHeight, height uint32) error { candidates, err = a.GetCandidatesDesc(versionHeight, count+unclaimed, votedProducers) } else { - candidates, err = a.GetDposV2CandidatesDesc(count+int(a.ChainParams.CRMemberCount), + candidates, err = a.GetDposV2CandidatesDesc(count+int(a.ChainParams.CRConfiguration.MemberCount), crAndVotedProducersStr, choosingCRArbiters) } if err != nil { @@ -2328,9 +2332,9 @@ func (a *Arbiters) resetNextArbiterByCRC(versionHeight uint32, height uint32) (i var needReset bool crcArbiters := map[common.Uint168]ArbiterMember{} if a.CRCommittee != nil && a.CRCommittee.IsInElectionPeriod() { - if versionHeight >= a.ChainParams.CRClaimDPOSNodeStartHeight { + if versionHeight >= a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { var err error - if versionHeight < a.ChainParams.ChangeCommitteeNewCRHeight { + if versionHeight < a.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { if crcArbiters, err = a.getCRCArbitersV1(height); err != nil { return unclaimed, nil, err } @@ -2346,7 +2350,7 @@ func (a *Arbiters) resetNextArbiterByCRC(versionHeight uint32, height uint32) (i } } needReset = true - } else if versionHeight >= a.ChainParams.ChangeCommitteeNewCRHeight { + } else if versionHeight >= a.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { var votedProducers []*Producer if a.isDposV2Active() { votedProducers = a.State.GetDposV2ActiveProducers() @@ -2354,7 +2358,7 @@ func (a *Arbiters) resetNextArbiterByCRC(versionHeight uint32, height uint32) (i votedProducers = a.State.GetVotedProducers() } - if len(votedProducers) < len(a.ChainParams.CRCArbiters) { + if len(votedProducers) < len(a.ChainParams.DPoSConfiguration.CRCArbiters) { return unclaimed, nil, errors.New("votedProducers less than CRCArbiters") } @@ -2376,7 +2380,7 @@ func (a *Arbiters) resetNextArbiterByCRC(versionHeight uint32, height uint32) (i }) } - for i := 0; i < len(a.ChainParams.CRCArbiters); i++ { + for i := 0; i < len(a.ChainParams.DPoSConfiguration.CRCArbiters); i++ { producer := votedProducers[i] ar, err := NewDPoSArbiter(producer) if err != nil { @@ -2384,11 +2388,11 @@ func (a *Arbiters) resetNextArbiterByCRC(versionHeight uint32, height uint32) (i } crcArbiters[ar.GetOwnerProgramHash()] = ar } - unclaimed = len(a.ChainParams.CRCArbiters) + unclaimed = len(a.ChainParams.DPoSConfiguration.CRCArbiters) needReset = true - } else if versionHeight >= a.ChainParams.CRCommitteeStartHeight { - for _, pk := range a.ChainParams.CRCArbiters { + } else if versionHeight >= a.ChainParams.CRConfiguration.CRCommitteeStartHeight { + for _, pk := range a.ChainParams.DPoSConfiguration.CRCArbiters { pubKey, err := hex.DecodeString(pk) if err != nil { return unclaimed, nil, err @@ -2442,7 +2446,7 @@ func (a *Arbiters) resetNextArbiterByCRC(versionHeight uint32, height uint32) (i func (a *Arbiters) getCRCArbitersV2(height uint32) (map[common.Uint168]ArbiterMember, int, error) { crMembers := a.CRCommittee.GetAllMembersCopy() - if len(crMembers) != len(a.ChainParams.CRCArbiters) { + if len(crMembers) != len(a.ChainParams.DPoSConfiguration.CRCArbiters) { return nil, 0, errors.New("CRC members count mismatch with CRC arbiters") } @@ -2454,7 +2458,7 @@ func (a *Arbiters) getCRCArbitersV2(height uint32) (map[common.Uint168]ArbiterMe } } arbitersPublicKeysMap := make(map[string]struct{}) - for _, ar := range a.ChainParams.CRCArbiters { + for _, ar := range a.ChainParams.DPoSConfiguration.CRCArbiters { arbitersPublicKeysMap[ar] = struct{}{} } @@ -2468,17 +2472,17 @@ func (a *Arbiters) getCRCArbitersV2(height uint32) (map[common.Uint168]ArbiterMe sort.Slice(unclaimedArbiterKeys, func(i, j int) bool { return strings.Compare(unclaimedArbiterKeys[i], unclaimedArbiterKeys[j]) < 0 }) - producers, err := a.getProducers(int(a.ChainParams.CRMemberCount), height) + producers, err := a.getProducers(int(a.ChainParams.CRConfiguration.MemberCount), height) if err != nil { return nil, 0, err } var unclaimedCount int crcArbiters := map[common.Uint168]ArbiterMember{} - claimHeight := a.ChainParams.CRClaimDPOSNodeStartHeight + claimHeight := a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight for _, cr := range crMembers { var pk []byte if len(cr.DPOSPublicKey) == 0 { - if height >= a.ChainParams.CRDPoSNodeHotFixHeight { + if height >= a.ChainParams.DPoSConfiguration.CRDPoSNodeHotFixHeight { //if cr.MemberState != state.MemberElected { var err error pk, err = common.HexStringToBytes(unclaimedArbiterKeys[0]) @@ -2523,7 +2527,7 @@ func (a *Arbiters) getCRCArbitersV2(height uint32) (map[common.Uint168]ArbiterMe func (a *Arbiters) getCRCArbitersV1(height uint32) (map[common.Uint168]ArbiterMember, error) { crMembers := a.CRCommittee.GetAllMembersCopy() - if len(crMembers) != len(a.ChainParams.CRCArbiters) { + if len(crMembers) != len(a.ChainParams.DPoSConfiguration.CRCArbiters) { return nil, errors.New("CRC members count mismatch with CRC arbiters") } @@ -2535,7 +2539,7 @@ func (a *Arbiters) getCRCArbitersV1(height uint32) (map[common.Uint168]ArbiterMe } } arbitersPublicKeysMap := make(map[string]struct{}) - for _, ar := range a.ChainParams.CRCArbiters { + for _, ar := range a.ChainParams.DPoSConfiguration.CRCArbiters { arbitersPublicKeysMap[ar] = struct{}{} } @@ -2550,7 +2554,7 @@ func (a *Arbiters) getCRCArbitersV1(height uint32) (map[common.Uint168]ArbiterMe return strings.Compare(unclaimedArbiterKeys[i], unclaimedArbiterKeys[j]) < 0 }) crcArbiters := map[common.Uint168]ArbiterMember{} - claimHeight := a.ChainParams.CRClaimDPOSNodeStartHeight + claimHeight := a.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight for _, cr := range crMembers { var pk []byte if len(cr.DPOSPublicKey) == 0 { @@ -2580,12 +2584,12 @@ func (a *Arbiters) getCRCArbitersV1(height uint32) (map[common.Uint168]ArbiterMe func (a *Arbiters) getCRCArbitersV0() (map[common.Uint168]ArbiterMember, error) { crMembers := a.CRCommittee.GetAllMembersCopy() - if len(crMembers) != len(a.ChainParams.CRCArbiters) { + if len(crMembers) != len(a.ChainParams.DPoSConfiguration.CRCArbiters) { return nil, errors.New("CRC members count mismatch with CRC arbiters") } crcArbiters := map[common.Uint168]ArbiterMember{} - for i, v := range a.ChainParams.CRCArbiters { + for i, v := range a.ChainParams.DPoSConfiguration.CRCArbiters { pk, err := common.HexStringToBytes(v) if err != nil { return nil, err @@ -2610,7 +2614,7 @@ func (a *Arbiters) GetCandidatesDesc(height uint32, startIndex int, result := make([]ArbiterMember, 0) for i := startIndex; i < len(producers) && i < startIndex+a. - ChainParams.CandidateArbiters; i++ { + ChainParams.DPoSConfiguration.CandidatesCount; i++ { ar, err := NewDPoSArbiter(producers[i]) if err != nil { return nil, err @@ -2632,7 +2636,7 @@ func (a *Arbiters) GetDposV2CandidatesDesc(startIndex int, result := make([]ArbiterMember, 0) for i := startIndex; i < len(producers) && i < startIndex+a. - ChainParams.CandidateArbiters; i++ { + ChainParams.DPoSConfiguration.CandidatesCount; i++ { ownkey, _ := hex.DecodeString(producers[i]) hash, _ := contract.PublicKeyToStandardProgramHash(ownkey) crc, exist := choosingArbiters[*hash] @@ -2693,7 +2697,7 @@ func (a *Arbiters) snapshotVotesStates(height uint32) error { nextReward.OwnerVotesInRound = make(map[common.Uint168]common.Fixed64, 0) nextReward.TotalVotesInRound = 0 for _, ar := range a.nextArbitrators { - if height > a.ChainParams.ChangeCommitteeNewCRHeight { + if height > a.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { if ar.GetType() == CRC && (!ar.IsNormal() || (len(ar.(*crcArbiter).crMember.DPOSPublicKey) != 0 && ar.IsNormal())) { continue @@ -2922,9 +2926,9 @@ func getArbitersInfoWithoutOnduty(title string, return info, params } -func (a *Arbiters) initArbitrators(chainParams *config.Params) error { - originArbiters := make([]ArbiterMember, len(chainParams.OriginArbiters)) - for i, arbiter := range chainParams.OriginArbiters { +func (a *Arbiters) initArbitrators(chainParams *config.Configuration) error { + originArbiters := make([]ArbiterMember, len(chainParams.DPoSConfiguration.OriginArbiters)) + for i, arbiter := range chainParams.DPoSConfiguration.OriginArbiters { b, err := common.HexStringToBytes(arbiter) if err != nil { return err @@ -2938,7 +2942,7 @@ func (a *Arbiters) initArbitrators(chainParams *config.Params) error { } crcArbiters := make(map[common.Uint168]ArbiterMember) - for _, pk := range chainParams.CRCArbiters { + for _, pk := range chainParams.DPoSConfiguration.CRCArbiters { pubKey, err := hex.DecodeString(pk) if err != nil { return err @@ -2972,18 +2976,19 @@ func (a *Arbiters) initArbitrators(chainParams *config.Params) error { return nil } -func NewArbitrators(chainParams *config.Params, committee *state.Committee, +func NewArbitrators(chainParams *config.Configuration, committee *state.Committee, getProducerDepositAmount func(common.Uint168) (common.Fixed64, error), tryUpdateCRMemberInactivity func(did common.Uint168, needReset bool, height uint32), tryRevertCRMemberInactivityfunc func(did common.Uint168, oriState state.MemberState, oriInactiveCount uint32, height uint32), tryUpdateCRMemberIllegal func(did common.Uint168, height uint32, illegalPenalty common.Fixed64), tryRevertCRMemberIllegal func(did common.Uint168, oriState state.MemberState, height uint32, illegalPenalty common.Fixed64), updateCRInactivePenalty func(cid common.Uint168, height uint32), - revertUpdateCRInactivePenalty func(cid common.Uint168, height uint32)) ( - *Arbiters, error) { + revertUpdateCRInactivePenalty func(cid common.Uint168, height uint32), + ckpManager *checkpoint.Manager) (*Arbiters, error) { a := &Arbiters{ ChainParams: chainParams, CRCommittee: committee, + CkpManager: ckpManager, nextCandidates: make([]ArbiterMember, 0), accumulativeReward: common.Fixed64(0), finalRoundChange: common.Fixed64(0), @@ -3009,7 +3014,6 @@ func NewArbitrators(chainParams *config.Params, committee *state.Committee, tryUpdateCRMemberIllegal, tryRevertCRMemberIllegal, updateCRInactivePenalty, revertUpdateCRInactivePenalty) - - chainParams.CkpManager.Register(NewCheckpoint(a)) + a.CkpManager.Register(NewCheckpoint(a)) return a, nil } diff --git a/dpos/state/arbitratorsmock.go b/dpos/state/arbitratorsmock.go index 8b2758b54..54910de34 100644 --- a/dpos/state/arbitratorsmock.go +++ b/dpos/state/arbitratorsmock.go @@ -7,10 +7,10 @@ package state import ( "bytes" - "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/dpos/p2p/peer" ) diff --git a/dpos/state/checkpoint.go b/dpos/state/checkpoint.go index 71cc7010c..28b7c99fc 100644 --- a/dpos/state/checkpoint.go +++ b/dpos/state/checkpoint.go @@ -62,7 +62,7 @@ type CheckPoint struct { func (c *CheckPoint) StartHeight() uint32 { return uint32(math.Min(float64(c.arbitrators.ChainParams.VoteStartHeight), float64(c.arbitrators.ChainParams.CRCOnlyDPOSHeight- - c.arbitrators.ChainParams.PreConnectOffset))) + c.arbitrators.ChainParams.DPoSConfiguration.PreConnectOffset))) } func (c *CheckPoint) OnBlockSaved(block *types.DposBlock) { diff --git a/dpos/state/dposarbiter_test.go b/dpos/state/dposarbiter_test.go index 2ac501a79..7e871e2d5 100644 --- a/dpos/state/dposarbiter_test.go +++ b/dpos/state/dposarbiter_test.go @@ -7,13 +7,14 @@ package state import ( "bytes" + "math/rand" + "testing" + "github.com/elastos/Elastos.ELA/common" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" - "math/rand" - "testing" "github.com/stretchr/testify/assert" ) diff --git a/dpos/state/heightversion.go b/dpos/state/heightversion.go index 8f3e409ca..ec020a5c3 100644 --- a/dpos/state/heightversion.go +++ b/dpos/state/heightversion.go @@ -8,16 +8,16 @@ package state import ( "encoding/hex" "errors" - "github.com/elastos/Elastos.ELA/core/contract" "math" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract" ) // 0 - H1 func (a *Arbiters) getNormalArbitratorsDescV0() ([]ArbiterMember, error) { arbitersByte := make([]ArbiterMember, 0) - for _, arbiter := range a.State.ChainParams.OriginArbiters { + for _, arbiter := range a.State.ChainParams.DPoSConfiguration.OriginArbiters { arbiterByte, err := common.HexStringToBytes(arbiter) if err != nil { return nil, err @@ -118,19 +118,20 @@ func (a *Arbiters) distributeWithNormalArbitratorsV0( return nil, 0, errors.New("not found arbiters when distributeWithNormalArbitratorsV0") } + CRCAddress, _ := common.Uint168FromAddress(a.ChainParams.CRConfiguration.CRCAddress) roundReward := map[common.Uint168]common.Fixed64{} totalBlockConfirmReward := float64(reward) * 0.25 totalTopProducersReward := float64(reward) - totalBlockConfirmReward individualBlockConfirmReward := common.Fixed64( math.Floor(totalBlockConfirmReward / float64(len(a.CurrentArbitrators)))) totalVotesInRound := a.CurrentReward.TotalVotesInRound - if len(a.ChainParams.CRCArbiters) == len(a.CurrentArbitrators) { - roundReward[a.ChainParams.CRCAddress] = reward + if len(a.ChainParams.DPoSConfiguration.CRCArbiters) == len(a.CurrentArbitrators) { + roundReward[*CRCAddress] = reward return roundReward, reward, nil } rewardPerVote := totalTopProducersReward / float64(totalVotesInRound) - roundReward[a.ChainParams.CRCAddress] = 0 + roundReward[*CRCAddress] = 0 realDPOSReward := common.Fixed64(0) for _, arbiter := range a.CurrentArbitrators { ownerHash := arbiter.GetOwnerProgramHash() @@ -140,7 +141,7 @@ func (a *Arbiters) distributeWithNormalArbitratorsV0( r := individualBlockConfirmReward + individualProducerReward if _, ok := a.CurrentCRCArbitersMap[ownerHash]; ok { r = individualBlockConfirmReward - roundReward[a.ChainParams.CRCAddress] += r + roundReward[*CRCAddress] += r } else { roundReward[ownerHash] = r } diff --git a/dpos/state/originarbiter.go b/dpos/state/originarbiter.go index c0483cf48..1622f50b6 100644 --- a/dpos/state/originarbiter.go +++ b/dpos/state/originarbiter.go @@ -6,11 +6,11 @@ package state import ( - "github.com/elastos/Elastos.ELA/crypto" "io" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" + "github.com/elastos/Elastos.ELA/crypto" ) type originArbiter struct { diff --git a/dpos/state/state.go b/dpos/state/state.go index 8883f5100..101f2d850 100644 --- a/dpos/state/state.go +++ b/dpos/state/state.go @@ -520,7 +520,7 @@ type State struct { tryUpdateCRMemberIllegal func(did common.Uint168, height uint32, illegalPenalty common.Fixed64) tryRevertCRMemberIllegal func(did common.Uint168, oriState state.MemberState, height uint32, illegalPenalty common.Fixed64) - ChainParams *config.Params + ChainParams *config.Configuration mtx sync.RWMutex History *utils.History @@ -546,8 +546,8 @@ func (s *State) dposV2Started() bool { func (s *State) isDposV2Active() bool { log.Errorf("isDposV2Active len(a.DposV2EffectedProducers) %d GeneralArbiters %d", len(s.DposV2EffectedProducers), - s.ChainParams.GeneralArbiters) - return len(s.DposV2EffectedProducers) >= s.ChainParams.GeneralArbiters*3/2 + s.ChainParams.DPoSConfiguration.NormalArbitratorsCount) + return len(s.DposV2EffectedProducers) >= s.ChainParams.DPoSConfiguration.NormalArbitratorsCount*3/2 } func (s *State) GetRealWithdrawTransactions() map[common.Uint256]common2.OutputInfo { @@ -715,7 +715,7 @@ func (s *State) GetAllProducersPublicKey() []string { for nodePK, _ := range s.NextCRNodeOwnerKeys { nodePublicKeys = append(nodePublicKeys, nodePK) } - for _, nodePK := range s.ChainParams.CRCArbiters { + for _, nodePK := range s.ChainParams.DPoSConfiguration.CRCArbiters { nodePublicKeys = append(nodePublicKeys, nodePK) } return nodePublicKeys @@ -1036,7 +1036,7 @@ func (s *State) IsAbleToRecoverFromInactiveMode() bool { // IsAbleToRecoverFromInactiveMode returns if there are enough active arbiters func (s *State) IsAbleToRecoverFromUnderstaffedState() bool { s.mtx.RLock() - result := len(s.ActivityProducers) >= s.ChainParams.GeneralArbiters + result := len(s.ActivityProducers) >= s.ChainParams.DPoSConfiguration.NormalArbitratorsCount s.mtx.RUnlock() return result } @@ -1209,9 +1209,9 @@ func (s *State) ProcessBlock(block *types.Block, confirm *payload.Confirm, dutyI if confirm != nil { if block.Height > s.DPoSV2ActiveHeight { s.countArbitratorsInactivityV3(block.Height, confirm, dutyIndex) - } else if block.Height >= s.ChainParams.ChangeCommitteeNewCRHeight { + } else if block.Height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { s.countArbitratorsInactivityV2(block.Height, confirm) - } else if block.Height >= s.ChainParams.CRClaimDPOSNodeStartHeight { + } else if block.Height >= s.ChainParams.CRConfiguration.CRClaimDPOSNodeStartHeight { s.countArbitratorsInactivityV1(block.Height, confirm) } else { s.countArbitratorsInactivityV0(block.Height, confirm) @@ -1414,7 +1414,7 @@ func (s *State) updateProducersDepositCoin(height uint32) { canceledProducers := s.getCanceledProducers() for _, producer := range canceledProducers { - if height-producer.CancelHeight() == s.ChainParams.CRDepositLockupBlocks { + if height-producer.CancelHeight() == s.ChainParams.CRConfiguration.DepositLockupBlocks { updateDepositCoin(producer) } } @@ -2658,9 +2658,9 @@ func (s *State) RemoveSpecialTx(hash common.Uint256) { func (s *State) getIllegalPenaltyByHeight(height uint32) common.Fixed64 { var illegalPenalty common.Fixed64 if height >= s.DPoSV2ActiveHeight { - illegalPenalty = s.ChainParams.DPoSV2IllegalPenalty - } else if height >= s.ChainParams.ChangeCommitteeNewCRHeight { - illegalPenalty = s.ChainParams.IllegalPenalty + illegalPenalty = s.ChainParams.DPoSConfiguration.DPoSV2IllegalPenalty + } else if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { + illegalPenalty = s.ChainParams.DPoSConfiguration.IllegalPenalty } return illegalPenalty @@ -2728,7 +2728,7 @@ func (s *State) processIllegalEvidence(payloadData interfaces.Payload, producer.illegalHeight = height s.IllegalProducers[key] = producer producer.activateRequestHeight = math.MaxUint32 - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { producer.penalty += illegalPenalty } delete(s.ActivityProducers, key) @@ -2752,7 +2752,7 @@ func (s *State) processIllegalEvidence(payloadData interfaces.Payload, producer.illegalHeight = height s.IllegalProducers[key] = producer producer.activateRequestHeight = math.MaxUint32 - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { producer.penalty += illegalPenalty } delete(s.InactiveProducers, key) @@ -2773,7 +2773,7 @@ func (s *State) processIllegalEvidence(payloadData interfaces.Payload, s.History.Append(height, func() { producer.illegalHeight = height producer.activateRequestHeight = math.MaxUint32 - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { producer.penalty += illegalPenalty } }, func() { @@ -2791,7 +2791,7 @@ func (s *State) processIllegalEvidence(payloadData interfaces.Payload, producer.state = Illegal producer.illegalHeight = height s.IllegalProducers[key] = producer - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { producer.penalty += illegalPenalty } delete(s.CanceledProducers, key) @@ -2834,14 +2834,14 @@ func (s *State) setInactiveProducer(producer *Producer, key string, s.InactiveProducers[key] = producer delete(s.ActivityProducers, key) - var penalty = s.ChainParams.InactivePenalty + var penalty = s.ChainParams.DPoSConfiguration.InactivePenalty if height < s.VersionStartHeight || height >= s.VersionEndHeight { if !emergency { - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { producer.penalty += penalty } } else { - producer.penalty += s.ChainParams.EmergencyInactivePenalty + producer.penalty += s.ChainParams.DPoSConfiguration.EmergencyInactivePenalty } } @@ -2856,10 +2856,10 @@ func (s *State) revertSettingInactiveProducer(producer *Producer, key string, s.ActivityProducers[key] = producer delete(s.InactiveProducers, key) - var penalty = s.ChainParams.InactivePenalty + var penalty = s.ChainParams.DPoSConfiguration.InactivePenalty if height < s.VersionStartHeight || height >= s.VersionEndHeight { if emergency { - penalty = s.ChainParams.EmergencyInactivePenalty + penalty = s.ChainParams.DPoSConfiguration.EmergencyInactivePenalty } if producer.penalty < penalty { @@ -2879,9 +2879,9 @@ func (s *State) countArbitratorsInactivityV3(height uint32, return } - lastPosition := dutyIndex == s.ChainParams.GeneralArbiters+len(s.ChainParams.CRCArbiters)-1 + lastPosition := dutyIndex == s.ChainParams.DPoSConfiguration.NormalArbitratorsCount+len(s.ChainParams.DPoSConfiguration.CRCArbiters)-1 - isDPOSAsCR := height > s.ChainParams.ChangeCommitteeNewCRHeight + isDPOSAsCR := height > s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight // changingArbiters indicates the arbiters that should reset inactive // counting state. With the value of true means the producer is on duty or @@ -2985,7 +2985,7 @@ func (s *State) updateCRMemberInactiveCountV2(lastPosition, needReset, workedInR member.InactiveCountV2 += 1 if member.InactiveCountV2 >= 3 { member.MemberState = state.MemberInactive - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { s.updateCRInactivePenalty(member.Info.CID, height) } member.InactiveCountV2 = 0 @@ -2993,7 +2993,7 @@ func (s *State) updateCRMemberInactiveCountV2(lastPosition, needReset, workedInR }, func() { if member.MemberState == state.MemberInactive && member.InactiveCountV2 >= 3 { member.MemberState = state.MemberElected - if height >= s.ChainParams.ChangeCommitteeNewCRHeight { + if height >= s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight { s.revertUpdateCRInactivePenalty(member.Info.CID, height) } } @@ -3044,7 +3044,7 @@ func (s *State) countArbitratorsInactivityV2(height uint32, return } - isDPOSAsCR := height > s.ChainParams.ChangeCommitteeNewCRHeight + isDPOSAsCR := height > s.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight // changingArbiters indicates the arbiters that should reset inactive // counting state. With the value of true means the producer is on duty or @@ -3280,12 +3280,12 @@ func (s *State) tryUpdateInactivityV2(key string, producer *Producer, if producer.selected { producer.randomCandidateInactiveCount++ - if producer.randomCandidateInactiveCount >= s.ChainParams.MaxInactiveRoundsOfRandomNode { + if producer.randomCandidateInactiveCount >= s.ChainParams.DPoSConfiguration.MaxInactiveRoundsOfRandomNode { s.setInactiveProducer(producer, key, height, false) } } else { producer.inactiveCount++ - if producer.inactiveCount >= s.ChainParams.MaxInactiveRounds { + if producer.inactiveCount >= s.ChainParams.DPoSConfiguration.MaxInactiveRounds { s.setInactiveProducer(producer, key, height, false) producer.inactiveCount = 0 } @@ -3304,7 +3304,7 @@ func (s *State) tryUpdateInactivity(key string, producer *Producer, producer.inactiveCountingHeight = height } - if height-producer.inactiveCountingHeight >= s.ChainParams.MaxInactiveRounds { + if height-producer.inactiveCountingHeight >= s.ChainParams.DPoSConfiguration.MaxInactiveRounds { s.setInactiveProducer(producer, key, height, false) producer.inactiveCountingHeight = 0 } @@ -3367,7 +3367,7 @@ func (s *State) GetLastIrreversibleHeight() uint32 { } func (s *State) tryUpdateLastIrreversibleHeight(height uint32) { - if height < s.ChainParams.RevertToPOWStartHeight { + if height < s.ChainParams.DPoSConfiguration.RevertToPOWStartHeight { return } @@ -3416,7 +3416,7 @@ func (s *State) tryUpdateLastIrreversibleHeight(height uint32) { } } -//is this Height Irreversible +// is this Height Irreversible func (s *State) IsIrreversible(curBlockHeight uint32, detachNodesLen int) bool { s.mtx.RLock() defer s.mtx.RUnlock() @@ -3428,7 +3428,7 @@ func (s *State) IsIrreversible(curBlockHeight uint32, detachNodesLen int) bool { if curBlockHeight-uint32(detachNodesLen) <= s.LastIrreversibleHeight { return true } - if curBlockHeight >= s.ChainParams.RevertToPOWStartHeight { + if curBlockHeight >= s.ChainParams.DPoSConfiguration.RevertToPOWStartHeight { if s.ConsensusAlgorithm == DPOS { if detachNodesLen >= IrreversibleHeight { return true @@ -3460,7 +3460,7 @@ func (s *State) handleEvents(event *events.Event) { } // NewState returns a new State instance. -func NewState(chainParams *config.Params, getArbiters func() []*ArbiterInfo, +func NewState(chainParams *config.Configuration, getArbiters func() []*ArbiterInfo, getCRMembers func() []*state.CRMember, getNextCRMembers func() []*state.CRMember, isInElectionPeriod func() bool, diff --git a/dpos/state/state_test.go b/dpos/state/state_test.go index dafb083cb..a2ed07d61 100644 --- a/dpos/state/state_test.go +++ b/dpos/state/state_test.go @@ -4,13 +4,13 @@ import ( "bytes" "encoding/hex" "fmt" - "github.com/elastos/Elastos.ELA/core/contract" - "github.com/elastos/Elastos.ELA/crypto" - "github.com/stretchr/testify/assert" "testing" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/types/payload" + "github.com/elastos/Elastos.ELA/crypto" + "github.com/stretchr/testify/assert" ) func TestProducer_ActivateRequestHeight(t *testing.T) { diff --git a/elanet/bloom/filter.go b/elanet/bloom/filter.go index 2542dbecf..841133100 100644 --- a/elanet/bloom/filter.go +++ b/elanet/bloom/filter.go @@ -6,12 +6,12 @@ package bloom import ( - "github.com/elastos/Elastos.ELA/core/types/interfaces" "math" "sync" "github.com/elastos/Elastos.ELA/common" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/p2p/msg" ) diff --git a/elanet/bloom/merkleblock.go b/elanet/bloom/merkleblock.go index b7aee1f27..0ca190944 100644 --- a/elanet/bloom/merkleblock.go +++ b/elanet/bloom/merkleblock.go @@ -8,10 +8,10 @@ package bloom import ( "errors" "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/p2p/msg" ) diff --git a/elanet/bloom/merklebranch.go b/elanet/bloom/merklebranch.go index 9e7fe7764..a5e6fa286 100644 --- a/elanet/bloom/merklebranch.go +++ b/elanet/bloom/merklebranch.go @@ -8,9 +8,9 @@ package bloom import ( "errors" "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/p2p/msg" ) diff --git a/elanet/bloom/merklebranch_test.go b/elanet/bloom/merklebranch_test.go index f2189b9b8..19852455e 100644 --- a/elanet/bloom/merklebranch_test.go +++ b/elanet/bloom/merklebranch_test.go @@ -8,12 +8,12 @@ package bloom import ( "crypto/rand" "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "os" "testing" "github.com/elastos/Elastos.ELA/auxpow" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/p2p/msg" ) diff --git a/elanet/dns/main/main.go b/elanet/dns/main/main.go index 9426f9898..70c48f113 100644 --- a/elanet/dns/main/main.go +++ b/elanet/dns/main/main.go @@ -92,16 +92,17 @@ func main() { // If port parameter specified use the given port number. if port != 0 { - params.DefaultPort = uint16(port) + params.NodePort = uint16(port) } // If port parameter specified use the given port number. if newversionheight != 0 { - params.NewP2PProtocolVersionHeight = uint64(newversionheight) + params.CRConfiguration.NewP2PProtocolVersionHeight = uint64(newversionheight) } // Create the DNS instance. - dnsService, err := dns.New(dataDir, params.Magic, params.DefaultPort, params.NewP2PProtocolVersionHeight, nodePrefix+Version) + dnsService, err := dns.New(dataDir, params.Magic, params.NodePort, + params.CRConfiguration.NewP2PProtocolVersionHeight, nodePrefix+Version) if err != nil { fmt.Fprint(os.Stderr, err.Error()) os.Exit(1) diff --git a/elanet/interface.go b/elanet/interface.go index 114a68270..8b059f511 100644 --- a/elanet/interface.go +++ b/elanet/interface.go @@ -1,7 +1,7 @@ // Copyright (c) 2017-2020 The Elastos Foundation // Use of this source code is governed by an MIT // license that can be found in the LICENSE file. -// +// package elanet @@ -21,7 +21,7 @@ type Config struct { Chain *blockchain.BlockChain // ChainParams is the initial parameters to start the blockchain. - ChainParams *config.Params + ChainParams *config.Configuration // PermanentPeers are the peers need to be connected permanently. PermanentPeers []string @@ -47,7 +47,7 @@ type Server interface { Services() pact.ServiceFlag // NewPeer adds a new peer that has already been connected to the NetServer. - NewPeer(p svr.IPeer)(bool) + NewPeer(p svr.IPeer) bool // DonePeer removes a peer that has already been connected to the NetServer by ip. DonePeer(p svr.IPeer) diff --git a/elanet/netsync/interface.go b/elanet/netsync/interface.go index 0745e8c73..877e30569 100644 --- a/elanet/netsync/interface.go +++ b/elanet/netsync/interface.go @@ -23,7 +23,7 @@ type PeerNotifier interface { type Config struct { PeerNotifier PeerNotifier Chain *blockchain.BlockChain - ChainParams *config.Params + ChainParams *config.Configuration TxMemPool *mempool.TxPool BlockMemPool *mempool.BlockPool diff --git a/elanet/netsync/manager.go b/elanet/netsync/manager.go index d84b6b18f..29e856c0f 100644 --- a/elanet/netsync/manager.go +++ b/elanet/netsync/manager.go @@ -120,7 +120,7 @@ type SyncManager struct { started int32 shutdown int32 chain *blockchain.BlockChain - chainParams *config.Params + chainParams *config.Configuration txMemPool *mempool.TxPool blockMemPool *mempool.BlockPool msgChan chan interface{} diff --git a/elanet/server.go b/elanet/server.go index 418e48400..42b196b16 100644 --- a/elanet/server.go +++ b/elanet/server.go @@ -9,7 +9,6 @@ import ( "bytes" "errors" "fmt" - peer2 "github.com/elastos/Elastos.ELA/p2p/peer" "net" "sync/atomic" "time" @@ -35,6 +34,7 @@ import ( "github.com/elastos/Elastos.ELA/mempool" "github.com/elastos/Elastos.ELA/p2p" "github.com/elastos/Elastos.ELA/p2p/msg" + peer2 "github.com/elastos/Elastos.ELA/p2p/peer" svr "github.com/elastos/Elastos.ELA/p2p/server" ) @@ -80,7 +80,7 @@ type NetServer struct { svr.IServer SyncManager *netsync.SyncManager chain *blockchain.BlockChain - ChainParams *config.Params + ChainParams *config.Configuration txMemPool *mempool.TxPool blockMemPool *mempool.BlockPool Routes *routes.Routes @@ -1006,20 +1006,20 @@ func NewServer(dataDir string, cfg *Config, nodeVersion string) (*NetServer, err // If no listeners added, create default listener. if len(params.ListenAddrs) == 0 { - params.ListenAddrs = []string{fmt.Sprint(":", params.DefaultPort)} + params.ListenAddrs = []string{fmt.Sprint(":", params.NodePort)} } var pver = pact.DPOSStartVersion - if cfg.Chain.GetHeight() >= uint32(params.NewP2PProtocolVersionHeight) { + if cfg.Chain.GetHeight() >= uint32(params.CRConfiguration.NewP2PProtocolVersionHeight) { pver = pact.CRProposalVersion } svrCfg := svr.NewDefaultConfig( params.Magic, pver, uint64(services), - params.DefaultPort, params.DNSSeeds, params.ListenAddrs, + params.NodePort, params.DNSSeeds, params.ListenAddrs, nil, nil, createMessage, func() uint64 { return uint64(cfg.Chain.GetHeight()) }, - params.NewP2PProtocolVersionHeight, nodeVersion, + params.CRConfiguration.NewP2PProtocolVersionHeight, nodeVersion, ) svrCfg.DataDir = dataDir svrCfg.NAFilter = &naFilter{} diff --git a/go.mod b/go.mod index 5291ffb39..3d0c2e3e7 100644 --- a/go.mod +++ b/go.mod @@ -4,20 +4,20 @@ go 1.16 require ( github.com/btcsuite/btcd v0.22.0-beta - github.com/fatih/color v1.13.0 // indirect + github.com/fungolang/screw v1.0.1 github.com/go-echarts/statsview v0.3.4 github.com/gorilla/websocket v1.4.2 github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c github.com/itchyny/base58-go v0.1.0 github.com/mattn/go-runewidth v0.0.13 // indirect github.com/rs/cors v1.8.0 - github.com/stretchr/testify v1.6.0 + github.com/spf13/viper v1.12.0 + github.com/stretchr/testify v1.7.1 github.com/syndtr/goleveldb v1.0.0 github.com/tidwall/gjson v1.9.3 github.com/urfave/cli v1.22.5 github.com/yuin/gopher-lua v0.0.0-20210529063254-f4c35e4016d9 - golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 - golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect - golang.org/x/sys v0.0.0-20220307203707-22a9840ba4d7 // indirect + golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 gopkg.in/cheggaaa/pb.v1 v1.0.28 + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/log.go b/log.go index 4e5276eb2..ddc5d1cd5 100644 --- a/log.go +++ b/log.go @@ -11,7 +11,7 @@ import ( "path/filepath" "time" - "github.com/elastos/Elastos.ELA/common/config/settings" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/transaction" crstate "github.com/elastos/Elastos.ELA/cr/state" @@ -25,7 +25,6 @@ import ( "github.com/elastos/Elastos.ELA/p2p/connmgr" "github.com/elastos/Elastos.ELA/utils/elalog" - "github.com/urfave/cli" "gopkg.in/cheggaaa/pb.v1" ) @@ -172,24 +171,26 @@ var ( ) // The default amount of logging is none. -func setupLog(c *cli.Context, s *settings.Settings) { - flagDataDir := c.String("datadir") +func setupLog(s *config.Configuration) { + flagDataDir := config.DataDir + if s.DataDir != "" { + flagDataDir = s.DataDir + } path := filepath.Join(flagDataDir, nodeLogPath) - - logger = log.NewDefault(path, uint8(s.Params().PrintLevel), - s.Config().MaxPerLogSize, s.Config().MaxLogsSize) + logger = log.NewDefault(path, uint8(s.PrintLevel), + s.MaxPerLogSize, s.MaxLogsSize) pgBar = newProgress(logger.Writer()) admrlog := wrap(logger, elalog.LevelOff) cmgrlog := wrap(logger, elalog.LevelOff) hublog := wrap(logger, elalog.LevelOff) - synclog := wrap(logger, elalog.Level(s.Params().PrintLevel)) - peerlog := wrap(logger, elalog.Level(s.Params().PrintLevel)) - routlog := wrap(logger, elalog.Level(s.Params().PrintLevel)) - elanlog := wrap(logger, elalog.Level(s.Params().PrintLevel)) - statlog := wrap(logger, elalog.Level(s.Params().PrintLevel)) - crstatlog := wrap(logger, elalog.Level(s.Params().PrintLevel)) - txslog := wrap(logger, elalog.Level(s.Params().PrintLevel)) + synclog := wrap(logger, elalog.Level(s.PrintLevel)) + peerlog := wrap(logger, elalog.Level(s.PrintLevel)) + routlog := wrap(logger, elalog.Level(s.PrintLevel)) + elanlog := wrap(logger, elalog.Level(s.PrintLevel)) + statlog := wrap(logger, elalog.Level(s.PrintLevel)) + crstatlog := wrap(logger, elalog.Level(s.PrintLevel)) + txslog := wrap(logger, elalog.Level(s.PrintLevel)) addrmgr.UseLogger(admrlog) connmgr.UseLogger(cmgrlog) diff --git a/main.go b/main.go index 3db17a22a..30c843cf1 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ package main import ( "bytes" "fmt" + "net" "os" "path/filepath" "runtime" @@ -16,11 +17,11 @@ import ( "time" "github.com/elastos/Elastos.ELA/blockchain" - cmdcom "github.com/elastos/Elastos.ELA/cmd/common" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/config/settings" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/types" crstate "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/dpos" @@ -43,14 +44,14 @@ import ( "github.com/elastos/Elastos.ELA/utils/elalog" "github.com/elastos/Elastos.ELA/utils/signal" - "github.com/urfave/cli" + "github.com/fungolang/screw" ) const ( // dataPath indicates the path storing the chain data. dataPath = "data" - // logPath indicates the path storing the node log. + // nodeLogPath indicates the path storing the node log. nodeLogPath = "logs/node" // checkpointPath indicates the path storing the checkpoint data. @@ -61,193 +62,143 @@ const ( ) var ( - // Build version generated when build program. + // Version generated when build program. Version string - // The go source code version at build. + // GoVersion version at build. GoVersion string - // printStateInterval is the interval to print out peer-to-peer network - // state. + // The interval to print out peer-to-peer network state. printStateInterval = time.Minute ) func main() { - if err := setupNode().Run(os.Args); err != nil { - cmdcom.PrintErrorMsg(err.Error()) - os.Exit(1) - } -} + // Initialization + screw.SetAbout("Copyright (c) 2017-" + + fmt.Sprint(time.Now().Year()) + " The Elastos Foundation") + screw.SetVersion(nodePrefix + Version + GoVersion) -func setupNode() *cli.App { - appSettings := settings.NewSettings() - - app := cli.NewApp() - app.Name = "ela" - app.Version = Version - app.HelpName = "ela" - app.Usage = "ela node for elastos blockchain" - app.UsageText = "ela [options] [args]" - app.Flags = []cli.Flag{ - cmdcom.ConfigFileFlag, - cmdcom.DataDirFlag, - cmdcom.AccountPasswordFlag, - cmdcom.TestNetFlag, - cmdcom.RegTestFlag, - cmdcom.InfoPortFlag, - cmdcom.RestPortFlag, - cmdcom.WsPortFlag, - cmdcom.InstantBlockFlag, - cmdcom.RPCPortFlag, - cmdcom.RPCIpFlag, - cmdcom.RPCUrlFlag, - } - app.Flags = append(app.Flags, appSettings.Flags()...) - app.Action = func(c *cli.Context) { - setupLog(c, appSettings) - startNode(c, appSettings) - } - app.Before = func(c *cli.Context) error { - appSettings.SetContext(c) - appSettings.SetupConfig() - appSettings.InitParamsValue() - - // Use all processor cores. - runtime.GOMAXPROCS(runtime.NumCPU()) - - // Block and transaction processing can cause bursty allocations. This - // limits the garbage collector from excessively overallocating during - // bursts. This value was arrived at with the help of profiling live - // usage. - if appSettings.Params().NodeProfileStrategy == - config.MemoryFirst.String() { - debug.SetGCPercent(10) - } + // Setting config + setting := settings.NewSettings() + config := setting.SetupConfig() - return nil + // Use all processor cores. + runtime.GOMAXPROCS(runtime.NumCPU()) + + // This value was arrived at with the help of profiling live usage. + if config.MemoryFirst { + debug.SetGCPercent(10) } - return app + // Init logger + setupLog(config) + + // Start Node + startNode(config) } -func startNode(c *cli.Context, st *settings.Settings) { - // Enable profiling server if requested. - if st.Config().ProfilePort != 0 { - go utils.StartPProf(st.Config().ProfilePort, - st.Config().ProfileHost) +func startNode(cfg *config.Configuration) { + log.Infof("Node version: %s, %s, %s", Version, GoVersion, cfg.ActiveNet) + log.Debug("Main: ", cfg.ActiveNet, cfg.Magic, + cfg.DNSSeeds, cfg.FoundationAddress, cfg.ActiveNet, + cfg.DNSSeeds, cfg.NodePort, cfg.HttpInfoPort, + cfg.HttpRestPort, cfg.HttpWsPort, cfg.HttpJsonPort, + cfg.CheckPointConfiguration) + + if cfg.ProfilePort != 0 { + go utils.StartPProf(cfg.ProfilePort, cfg.ProfileHost) } - flagDataDir := c.String("datadir") + flagDataDir := config.DataDir + if cfg.DataDir != "" { + flagDataDir = cfg.DataDir + } dataDir := filepath.Join(flagDataDir, dataPath) - st.Params().CkpManager.SetDataPath( - filepath.Join(dataDir, checkpointPath)) - var act account.Account - if st.Config().DPoSConfiguration.EnableArbiter { - password, err := cmdcom.GetFlagPassword(c) + ckpManager := checkpoint.NewManager(cfg) + ckpManager.SetDataPath(filepath.Join(dataDir, checkpointPath)) + + var acc account.Account + if cfg.DPoSConfiguration.EnableArbiter { + password, err := utils.GetPassword() if err != nil { printErrorAndExit(err) } - act, err = account.Open(password, st.Params().WalletPath) + acc, err = account.Open(password, cfg.WalletPath) if err != nil { printErrorAndExit(err) } } - - log.Infof("Node version: %s", Version) - log.Info(GoVersion) - var interrupt = signal.NewInterrupt() // fixme remove singleton Ledger ledger := blockchain.Ledger{} // Initializes the foundation address - blockchain.FoundationAddress = st.Params().Foundation - chainStore, err := blockchain.NewChainStore(dataDir, st.Params()) + foundation, _ := common.Uint168FromAddress(cfg.FoundationAddress) + blockchain.FoundationAddress = *foundation + chainStore, err := blockchain.NewChainStore(dataDir, cfg) if err != nil { printErrorAndExit(err) } defer chainStore.Close() ledger.Store = chainStore // fixme - txMemPool := mempool.NewTxPool(st.Params()) - blockMemPool := mempool.NewBlockPool(st.Params()) + txMemPool := mempool.NewTxPool(cfg, ckpManager) + blockMemPool := mempool.NewBlockPool(cfg) blockMemPool.Store = chainStore blockchain.DefaultLedger = &ledger // fixme - committee := crstate.NewCommittee(st.Params()) + committee := crstate.NewCommittee(cfg, ckpManager) ledger.Committee = committee - arbiters, err := state.NewArbitrators(st.Params(), committee, - func(programHash common.Uint168) (common.Fixed64, - error) { - amount := common.Fixed64(0) - utxos, err := blockchain.DefaultLedger.Store. - GetFFLDB().GetUTXO(&programHash) - if err != nil { - return amount, err - } - for _, utxo := range utxos { - amount += utxo.Value - } - return amount, nil - }, + arbiters, err := state.NewArbitrators(cfg, committee, ledger.GetAmount, committee.TryUpdateCRMemberInactivity, committee.TryRevertCRMemberInactivity, committee.TryUpdateCRMemberIllegal, committee.TryRevertCRMemberIllegal, committee.UpdateCRInactivePenalty, committee.RevertUpdateCRInactivePenalty, + ckpManager, ) if err != nil { printErrorAndExit(err) } ledger.Arbitrators = arbiters // fixme - chain, err := blockchain.New(chainStore, st.Params(), arbiters.State, committee) + chain, err := blockchain.New(chainStore, cfg, + arbiters.State, committee, ckpManager) if err != nil { printErrorAndExit(err) } - if err := chain.Init(interrupt.C); err != nil { + if err = chain.Init(interrupt.C); err != nil { printErrorAndExit(err) } - if err := chain.MigrateOldDB(interrupt.C, pgBar.Start, - pgBar.Increase, dataDir, st.Params()); err != nil { + if err = chain.MigrateOldDB(interrupt.C, pgBar.Start, + pgBar.Increase, dataDir, cfg); err != nil { printErrorAndExit(err) } pgBar.Stop() + ledger.Blockchain = chain // fixme blockMemPool.Chain = chain arbiters.RegisterFunction(chain.GetHeight, chain.GetBestBlockHash, - func(height uint32) (*types.Block, error) { - hash, err := chain.GetBlockHash(height) - if err != nil { - return nil, err - } - block, err := chainStore.GetFFLDB().GetBlock(hash) - if err != nil { - return nil, err - } - blockchain.CalculateTxsFee(block.Block) - return block.Block, nil - }, chain.UTXOCache.GetTxReference) + chain.GetBlock, chain.UTXOCache.GetTxReference) routesCfg := &routes.Config{TimeSource: chain.TimeSource} - if act != nil { - routesCfg.PID = act.PublicKeyBytes() - routesCfg.Addr = fmt.Sprintf("%s:%d", - st.Params().DPoSIPAddress, - st.Params().DPoSDefaultPort) - routesCfg.Sign = act.Sign + if acc != nil { + routesCfg.PID = acc.PublicKeyBytes() + routesCfg.Addr = net.JoinHostPort(cfg.DPoSConfiguration.IPAddress, + strconv.FormatUint(uint64(cfg.DPoSConfiguration.DPoSPort), 10)) + routesCfg.Sign = acc.Sign } route := routes.New(routesCfg) netServer, err := elanet.NewServer(dataDir, &elanet.Config{ Chain: chain, - ChainParams: st.Params(), - PermanentPeers: st.Params().PermanentPeers, + ChainParams: cfg, + PermanentPeers: cfg.PermanentPeers, TxMemPool: txMemPool, BlockMemPool: blockMemPool, Routes: route, @@ -270,15 +221,12 @@ func startNode(c *cli.Context, st *settings.Settings) { CreateVotesRealWithdrawTransaction: chain.CreateVotesRealWithdrawTransaction, }) - var arbitrator *dpos.Arbitrator - if act != nil { - dlog.Init(flagDataDir, uint8(st.Config().PrintLevel), - st.Config().MaxPerLogSize, st.Config().MaxLogsSize) - - arbitrator, err = dpos.NewArbitrator(act, dpos.Config{ + if acc != nil { + dlog.Init(flagDataDir, uint8(cfg.PrintLevel), cfg.MaxPerLogSize, cfg.MaxLogsSize) + arbitrator, err := dpos.NewArbitrator(acc, dpos.Config{ EnableEventLog: true, Chain: chain, - ChainParams: st.Params(), + ChainParams: cfg, Arbitrators: arbiters, Server: netServer, TxMemPool: txMemPool, @@ -315,18 +263,17 @@ func startNode(c *cli.Context, st *settings.Settings) { }) servers.Compile = Version - servers.Config = st.Config() - servers.ChainParams = st.Params() + servers.ChainParams = cfg servers.Chain = chain servers.Store = chainStore servers.TxMemPool = txMemPool servers.Server = netServer servers.Arbiters = arbiters servers.Pow = pow.NewService(&pow.Config{ - PayToAddr: st.Config().PowConfiguration.PayToAddr, - MinerInfo: st.Config().PowConfiguration.MinerInfo, + PayToAddr: cfg.PowConfiguration.PayToAddr, + MinerInfo: cfg.PowConfiguration.MinerInfo, Chain: chain, - ChainParams: st.Params(), + ChainParams: cfg, TxMemPool: txMemPool, BlkMemPool: blockMemPool, BroadcastBlock: func(block *types.Block) { @@ -336,7 +283,7 @@ func startNode(c *cli.Context, st *settings.Settings) { Arbitrators: arbiters, }) - st.Params().CkpManager.SetNeedSave(true) + ckpManager.SetNeedSave(true) // initialize producer state after arbiters has initialized. if err = chain.InitCheckpoint(interrupt.C, pgBar.Start, pgBar.Increase); err != nil { @@ -345,7 +292,7 @@ func startNode(c *cli.Context, st *settings.Settings) { pgBar.Stop() // todo remove me - if chain.GetHeight() > st.Params().DPoSV2StartHeight { + if chain.GetHeight() > cfg.DPoSV2StartHeight { msg2.SetPayloadVersion(msg2.DPoSV2Version) } @@ -362,16 +309,16 @@ func startNode(c *cli.Context, st *settings.Settings) { defer netServer.Stop() log.Info("Start services") - if st.Config().EnableRPC { + if cfg.EnableRPC { go httpjsonrpc.StartRPCServer() } - if st.Config().HttpRestStart { + if cfg.HttpRestStart { go httprestful.StartServer() } - if st.Config().HttpWsStart { + if cfg.HttpWsStart { go httpwebsocket.Start() } - if st.Config().HttpInfoStart { + if cfg.HttpInfoStart { go httpnodeinfo.StartServer() } @@ -382,7 +329,7 @@ func startNode(c *cli.Context, st *settings.Settings) { return } log.Info("Start consensus") - if st.Config().PowConfiguration.AutoMining { + if cfg.PowConfiguration.AutoMining { log.Info("Start POW Services") go servers.Pow.Start() } diff --git a/mempool/blockpool.go b/mempool/blockpool.go index e75092645..e16b85bf2 100644 --- a/mempool/blockpool.go +++ b/mempool/blockpool.go @@ -34,7 +34,7 @@ type BlockPool struct { sync.RWMutex blocks map[common.Uint256]*types.Block confirms map[common.Uint256]*payload.Confirm - chainParams *config.Params + chainParams *config.Configuration } func (bm *BlockPool) AppendConfirm(confirm *payload.Confirm) (bool, @@ -50,7 +50,7 @@ func (bm *BlockPool) AddDposBlock(dposBlock *types.DposBlock) (bool, bool, error return bm.Chain.ProcessBlock(dposBlock.Block, dposBlock.Confirm) } - if dposBlock.Block.Height > bm.chainParams.RevertToPOWStartHeight && !dposBlock.HaveConfirm { + if dposBlock.Block.Height > bm.chainParams.DPoSConfiguration.RevertToPOWStartHeight && !dposBlock.HaveConfirm { for _, tx := range dposBlock.Transactions { if tx.IsRevertToPOW() { return bm.Chain.ProcessBlock(dposBlock.Block, dposBlock.Confirm) @@ -60,11 +60,12 @@ func (bm *BlockPool) AddDposBlock(dposBlock *types.DposBlock) (bool, bool, error // main version >=H1 if dposBlock.Block.Height >= bm.chainParams.CRCOnlyDPOSHeight { - if dposBlock.Block.Height >= bm.chainParams.CRCommitteeStartHeight { + if dposBlock.Block.Height >= bm.chainParams.CRConfiguration.CRCommitteeStartHeight { + DestroyELAAddress, _ := common.Uint168FromAddress(bm.chainParams.DestroyELAAddress) if len(dposBlock.Block.Transactions) > 0 && len(dposBlock.Block.Transactions[0].Outputs()) >= 1 && dposBlock.Block.Transactions[0].Outputs()[0].ProgramHash. - IsEqual(bm.chainParams.DestroyELAAddress) { + IsEqual(*DestroyELAAddress) { return bm.Chain.ProcessBlock(dposBlock.Block, dposBlock.Confirm) } } @@ -290,7 +291,7 @@ func (bm *BlockPool) CleanFinalConfirmedBlock(height uint32) { } } -func NewBlockPool(params *config.Params) *BlockPool { +func NewBlockPool(params *config.Configuration) *BlockPool { return &BlockPool{ blocks: make(map[common.Uint256]*types.Block), confirms: make(map[common.Uint256]*payload.Confirm), diff --git a/mempool/conflictmanager.go b/mempool/conflictmanager.go index a8056d1e9..0d495ea44 100644 --- a/mempool/conflictmanager.go +++ b/mempool/conflictmanager.go @@ -7,9 +7,9 @@ package mempool import ( "fmt" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" - "github.com/elastos/Elastos.ELA/errors" ) @@ -36,19 +36,19 @@ const ( slotCloseProposalTargetProposalHash = "CloseProposalTargetProposalHash" slotChangeProposalOwnerTargetProposalHash = "ChangeProposalOwnerTargetProposalHash" slotChangeCustomIDFee = "ChangeCustomIDFee" - slotReserveCustomID = "ReserveCustomID" - slotSpecialTxHash = "SpecialTxHash" - slotSidechainTxHashes = "SidechainTxHashes" - slotSidechainReturnDepositTxHashes = "SidechainReturnDepositTxHashes" - slotCustomIDProposalResult = "CustomIDProposalResult" - slotTxInputsReferKeys = "TxInputsReferKeys" - slotCRCouncilMemberNodePublicKey = "CRCouncilMemberNodePublicKey" - slotCRCouncilMemberDID = "CRCouncilMemberDID" - slotCRCSecretaryGeneral = "CRCSecretaryGeneral" - slotRevertToDPOSHash = "RevertToDPOSHash" - slotVotesRealWithdraw = "VotesRealWithdraw" - slotExchangeVotes = "ExchangeVotes" - slotDposV2ClaimReward = "DposV2ClaimReward" + slotReserveCustomID = "ReserveCustomID" + slotSpecialTxHash = "SpecialTxHash" + slotSidechainTxHashes = "SidechainTxHashes" + slotSidechainReturnDepositTxHashes = "SidechainReturnDepositTxHashes" + slotCustomIDProposalResult = "CustomIDProposalResult" + slotTxInputsReferKeys = "TxInputsReferKeys" + slotCRCouncilMemberNodePublicKey = "CRCouncilMemberNodePublicKey" + slotCRCouncilMemberDID = "CRCouncilMemberDID" + slotCRCSecretaryGeneral = "CRCSecretaryGeneral" + slotRevertToDPOSHash = "RevertToDPOSHash" + slotVotesRealWithdraw = "VotesRealWithdraw" + slotExchangeVotes = "ExchangeVotes" + slotDposV2ClaimReward = "DposV2ClaimReward" ) type conflict struct { diff --git a/mempool/conflictmanager_test.go b/mempool/conflictmanager_test.go index 3512d67c6..1d19a970b 100644 --- a/mempool/conflictmanager_test.go +++ b/mempool/conflictmanager_test.go @@ -10,16 +10,15 @@ import ( mrand "math/rand" "testing" - transaction2 "github.com/elastos/Elastos.ELA/core/transaction" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/core/types/interfaces" - "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" + transaction2 "github.com/elastos/Elastos.ELA/core/transaction" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/stretchr/testify/assert" diff --git a/mempool/conflictslot.go b/mempool/conflictslot.go index 173f0d620..431e28fa7 100644 --- a/mempool/conflictslot.go +++ b/mempool/conflictslot.go @@ -8,9 +8,9 @@ package mempool import ( "fmt" - "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/common" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/errors" ) @@ -50,6 +50,7 @@ const ( ) // conflictSlot hold a set of transactions references that may conflict with +// // incoming transactions, those transactions will process with same rule to // generate key by which to detect the conflict. type conflictSlot struct { diff --git a/mempool/txfeeorderedlist_bench_test.go b/mempool/txfeeorderedlist_bench_test.go index 6c6c32c44..5ab32fdd6 100644 --- a/mempool/txfeeorderedlist_bench_test.go +++ b/mempool/txfeeorderedlist_bench_test.go @@ -9,11 +9,10 @@ import ( "math/rand" "testing" - "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract/program" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/payload" ) diff --git a/mempool/txpool.go b/mempool/txpool.go index 4848a1456..57fe74376 100644 --- a/mempool/txpool.go +++ b/mempool/txpool.go @@ -15,6 +15,7 @@ import ( . "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" . "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/interfaces" @@ -29,16 +30,17 @@ const broadcastCrossChainTransactionInterval = 30 type TxPool struct { conflictManager *txPoolCheckpoint - chainParams *config.Params + chainParams *config.Configuration //proposal of txpool used amout proposalsUsedAmount Fixed64 crossChainHeightList map[Uint256]uint32 + CkpManager *checkpoint.Manager sync.RWMutex } -//append transaction to txnpool when check ok, and broadcast the transaction. -//1.check 2.check with ledger(db) 3.check with pool +// append transaction to txnpool when check ok, and broadcast the transaction. +// 1.check 2.check with ledger(db) 3.check with pool func (mp *TxPool) AppendToTxPool(tx interfaces.Transaction) elaerr.ELAError { mp.Lock() defer mp.Unlock() @@ -51,8 +53,8 @@ func (mp *TxPool) AppendToTxPool(tx interfaces.Transaction) elaerr.ELAError { return nil } -//append transaction to txnpool when check ok. -//1.check 2.check with ledger(db) 3.check with pool +// append transaction to txnpool when check ok. +// 1.check 2.check with ledger(db) 3.check with pool func (mp *TxPool) AppendToTxPoolWithoutEvent(tx interfaces.Transaction) elaerr.ELAError { mp.Lock() defer mp.Unlock() @@ -175,7 +177,7 @@ func (mp *TxPool) GetTxsInPool() []interfaces.Transaction { return txs } -//clean the transaction Pool with committed block. +// clean the transaction Pool with committed block. func (mp *TxPool) CleanSubmittedTransactions(block *Block) { mp.Lock() mp.cleanTransactions(block.Transactions) @@ -413,14 +415,14 @@ func (mp *TxPool) cleanVoteAndUpdateCR(cid Uint168) error { return nil } -//get the transaction by hash +// get the transaction by hash func (mp *TxPool) GetTransaction(hash Uint256) interfaces.Transaction { mp.RLock() defer mp.RUnlock() return mp.txnList[hash] } -//verify transaction with txnpool +// verify transaction with txnpool func (mp *TxPool) verifyTransactionWithTxnPool( txn interfaces.Transaction) elaerr.ELAError { if txn.IsSideChainPowTx() { @@ -431,7 +433,7 @@ func (mp *TxPool) verifyTransactionWithTxnPool( return mp.VerifyTx(txn) } -//remove from associated map +// remove from associated map func (mp *TxPool) removeTransaction(tx interfaces.Transaction) { //1.remove from txnList if _, ok := mp.txnList[tx.Hash()]; ok { @@ -588,10 +590,11 @@ func (mp *TxPool) onPopBack(hash Uint256) { } -func NewTxPool(params *config.Params) *TxPool { +func NewTxPool(params *config.Configuration, ckpManager *checkpoint.Manager) *TxPool { rtn := &TxPool{ conflictManager: newConflictManager(), chainParams: params, + CkpManager: ckpManager, proposalsUsedAmount: 0, crossChainHeightList: make(map[Uint256]uint32), } @@ -603,6 +606,6 @@ func NewTxPool(params *config.Params) *TxPool { } } }) - params.CkpManager.Register(rtn.txPoolCheckpoint) + rtn.CkpManager.Register(rtn.txPoolCheckpoint) return rtn } diff --git a/mempool/txpool_test.go b/mempool/txpool_test.go index 4ab7e1d37..31a110ea3 100644 --- a/mempool/txpool_test.go +++ b/mempool/txpool_test.go @@ -19,6 +19,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" transaction2 "github.com/elastos/Elastos.ELA/core/transaction" @@ -47,7 +48,7 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } type UtxoCacheDB struct { @@ -81,8 +82,10 @@ func TestTxPoolInit(t *testing.T) { log.NewDefault(test.NodeLogPath, 0, 0, 0) dplog.Init("elastos", 0, 0, 0) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) params := &config.DefaultParams - blockchain.FoundationAddress = params.Foundation + FoundationAddress, _ := common.Uint168FromAddress(params.FoundationAddress) + blockchain.FoundationAddress = *FoundationAddress chainStore, err := blockchain.NewChainStore(test.DataPath, params) if err != nil { t.Fatal("open LedgerStore err:", err) @@ -106,7 +109,8 @@ func TestTxPoolInit(t *testing.T) { chain, err := blockchain.New(chainStore, params, state.NewState(params, nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil, nil), nil) + nil, nil, nil, nil, nil), nil, + ckpManager) if err != nil { t.Fatal(err, "BlockChain generate failed") } @@ -120,7 +124,7 @@ func TestTxPoolInit(t *testing.T) { Arbitrators: arbitrators, } - txPool = NewTxPool(&config.DefaultParams) + txPool = NewTxPool(&config.DefaultParams, ckpManager) } func TestTxPool_VerifyDuplicateSidechainTx(t *testing.T) { @@ -698,6 +702,7 @@ func TestTxPool_AppendToTxnPool(t *testing.T) { } func TestTxPool_CleanSubmittedTransactions(t *testing.T) { + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) appendTx := func(tx interfaces.Transaction) elaerr.ELAError { if err := txPool.AppendTx(tx); err != nil { return err @@ -706,7 +711,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { return nil } - txPool = NewTxPool(&config.DefaultParams) + txPool = NewTxPool(&config.DefaultParams, ckpManager) /*------------------------------------------------------------*/ /* check double spend but not duplicate txs */ //two mock transactions, they are double-spent to each other. @@ -839,7 +844,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { rand.Read(sideBlockHash5[:]) fmt.Println("sideBlockHash5:", sideBlockHash5) - txPool = NewTxPool(&config.DefaultParams) + txPool = NewTxPool(&config.DefaultParams, ckpManager) //two mock transactions again, they have some identical sidechain hashes tx3Prev := functions.CreateTransaction( 0, @@ -1034,7 +1039,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { /*------------------------------------------------------------*/ /* check double spend and duplicate txs */ - txPool = NewTxPool(&config.DefaultParams) + txPool = NewTxPool(&config.DefaultParams, ckpManager) assert.NoError(t, appendTx(tx4)) diff --git a/mempool/txpoolcheckpoint.go b/mempool/txpoolcheckpoint.go index db9af5f7e..868fb136c 100644 --- a/mempool/txpoolcheckpoint.go +++ b/mempool/txpoolcheckpoint.go @@ -7,13 +7,13 @@ package mempool import ( "bytes" - "github.com/elastos/Elastos.ELA/core/types/functions" "io" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/elanet/pact" ) diff --git a/p2p/header.go b/p2p/header.go index c2c33ef48..cbd92c22f 100644 --- a/p2p/header.go +++ b/p2p/header.go @@ -11,9 +11,9 @@ import ( "encoding/hex" "errors" "fmt" - "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/common/log" ) type Header struct { diff --git a/p2p/peer/peer.go b/p2p/peer/peer.go index f51c48734..fa545fb9c 100644 --- a/p2p/peer/peer.go +++ b/p2p/peer/peer.go @@ -11,7 +11,6 @@ import ( "encoding/binary" "errors" "fmt" - "github.com/elastos/Elastos.ELA/core/types/functions" "io" "math/rand" "net" @@ -21,6 +20,7 @@ import ( "time" "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/elanet/pact" elaerr "github.com/elastos/Elastos.ELA/errors" "github.com/elastos/Elastos.ELA/p2p" diff --git a/pow/revertlistener.go b/pow/revertlistener.go index 77b015db3..1afc75677 100644 --- a/pow/revertlistener.go +++ b/pow/revertlistener.go @@ -21,7 +21,7 @@ func (pow *Service) ListenForRevert() { go func() { for { time.Sleep(CheckRevertToPOWInterval) - if pow.chain.BestChain.Height < pow.chainParams.RevertToPOWStartHeight { + if pow.chain.BestChain.Height < pow.chainParams.DPoSConfiguration.RevertToPOWStartHeight { continue } if pow.arbiters.IsInPOWMode() { @@ -29,7 +29,7 @@ func (pow *Service) ListenForRevert() { } lastBlockTimestamp := int64(pow.arbiters.GetLastBlockTimestamp()) localTimestamp := pow.chain.TimeSource.AdjustedTime().Unix() - if localTimestamp-lastBlockTimestamp < pow.chainParams.RevertToPOWNoBlockTime { + if localTimestamp-lastBlockTimestamp < pow.chainParams.DPoSConfiguration.RevertToPOWNoBlockTime { continue } diff --git a/pow/service.go b/pow/service.go index b3eb7e1ec..453dccac8 100644 --- a/pow/service.go +++ b/pow/service.go @@ -9,9 +9,6 @@ import ( "encoding/binary" "errors" "fmt" - pg "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/core/types/payload" "math" "math/rand" "sort" @@ -23,10 +20,14 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" + pg "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/outputpayload" + "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/dpos/state" "github.com/elastos/Elastos.ELA/elanet/pact" @@ -44,7 +45,7 @@ type Config struct { PayToAddr string MinerInfo string Chain *blockchain.BlockChain - ChainParams *config.Params + ChainParams *config.Configuration TxMemPool *mempool.TxPool BlkMemPool *mempool.BlockPool BroadcastBlock func(block *types.Block) @@ -84,7 +85,7 @@ type Service struct { PayToAddr string MinerInfo string chain *blockchain.BlockChain - chainParams *config.Params + chainParams *config.Configuration txMemPool *mempool.TxPool blkMemPool *mempool.BlockPool broadcast func(block *types.Block) @@ -116,9 +117,9 @@ func (pow *Service) GetDefaultTxVersion(height uint32) common2.TransactionVersio func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (interfaces.Transaction, error) { - crRewardAddr := pow.chainParams.Foundation - if height >= pow.chainParams.CRCommitteeStartHeight { - crRewardAddr = pow.chainParams.CRAssetsAddress + crRewardAddr := pow.chainParams.FoundationAddress + if height >= pow.chainParams.CRConfiguration.CRCommitteeStartHeight { + crRewardAddr = pow.chainParams.CRConfiguration.CRAssetsAddress } minerProgramHash, err := common.Uint168FromAddress(minerAddr) @@ -129,7 +130,8 @@ func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (interface nonce := make([]byte, 8) binary.BigEndian.PutUint64(nonce, rand.Uint64()) txAttr := common2.NewAttribute(common2.Nonce, nonce) - + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) + CRRewardAddr, _ := common.Uint168FromAddress(crRewardAddr) tx := functions.CreateTransaction( pow.GetDefaultTxVersion(height), common2.CoinBase, @@ -149,14 +151,14 @@ func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (interface }, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 0, - ProgramHash: crRewardAddr, + ProgramHash: *CRRewardAddr, Type: common2.OTNone, Payload: &outputpayload.DefaultOutput{}, }, { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 0, ProgramHash: *minerProgramHash, Type: common2.OTNone, @@ -172,23 +174,26 @@ func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (interface func (pow *Service) AssignCoinbaseTxRewards(block *types.Block, totalReward common.Fixed64) error { activeHeight := pow.arbiters.GetDPoSV2ActiveHeight() + DestroyELAAddress, _ := common.Uint168FromAddress(pow.chainParams.DestroyELAAddress) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) if activeHeight != math.MaxUint32 && block.Height > activeHeight+1 { rewardCyberRepublic := common.Fixed64(math.Ceil(float64(totalReward) * 0.3)) rewardDposArbiter := common.Fixed64(math.Ceil(float64(totalReward) * 0.35)) rewardMergeMiner := common.Fixed64(totalReward) - rewardCyberRepublic - rewardDposArbiter block.Transactions[0].Outputs()[0].Value = rewardCyberRepublic block.Transactions[0].Outputs()[1].Value = rewardMergeMiner - dposRewardAddr := pow.chainParams.DPoSV2RewardAccumulateAddress + dposRewardAddr, _ := common.Uint168FromAddress(pow.chainParams.DPoSConfiguration.DPoSV2RewardAccumulateAddress) + if pow.arbiters.IsInPOWMode() { - dposRewardAddr = pow.chainParams.DestroyELAAddress - block.Transactions[0].Outputs()[0].ProgramHash = pow.chainParams.DestroyELAAddress + + block.Transactions[0].Outputs()[0].ProgramHash = *DestroyELAAddress } if rewardDposArbiter > common.Fixed64(0) { output := append(block.Transactions[0].Outputs(), &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: rewardDposArbiter, - ProgramHash: dposRewardAddr, + ProgramHash: *dposRewardAddr, Payload: &outputpayload.DefaultOutput{}, }) block.Transactions[0].SetOutputs(output) @@ -216,7 +221,7 @@ func (pow *Service) AssignCoinbaseTxRewards(block *types.Block, totalReward comm block.Transactions[0].Outputs()[0].Value = rewardCyberRepublic block.Transactions[0].Outputs()[1].Value = rewardMergeMiner if pow.arbiters.IsInPOWMode() { - block.Transactions[0].Outputs()[0].ProgramHash = pow.chainParams.DestroyELAAddress + block.Transactions[0].Outputs()[0].ProgramHash = *DestroyELAAddress } return nil } @@ -229,7 +234,7 @@ func (pow *Service) AssignCoinbaseTxRewards(block *types.Block, totalReward comm block.Transactions[0].Outputs()[0].Value = rewardCyberRepublic block.Transactions[0].Outputs()[1].Value = rewardMergeMiner block.Transactions[0].SetOutputs(append(block.Transactions[0].Outputs(), &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: rewardDposArbiter, ProgramHash: blockchain.FoundationAddress, })) @@ -238,10 +243,10 @@ func (pow *Service) AssignCoinbaseTxRewards(block *types.Block, totalReward comm func (pow *Service) distributeDPOSReward(coinBaseTx interfaces.Transaction, rewards map[common.Uint168]common.Fixed64) (common.Fixed64, error) { - + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for ownerHash, reward := range rewards { coinBaseTx.SetOutputs(append(coinBaseTx.Outputs(), &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: reward, ProgramHash: ownerHash, Type: common2.OTNone, @@ -264,7 +269,7 @@ func (pow *Service) GenerateBlock(minerAddr string, Previous: *pow.chain.BestChain.Hash, MerkleRoot: common.EmptyHash, Timestamp: uint32(pow.chain.MedianAdjustedTime().Unix()), - Bits: pow.chainParams.PowLimitBits, + Bits: pow.chainParams.PowConfiguration.PowLimitBits, Height: nextBlockHeight, Nonce: 0, } diff --git a/pow/service_test.go b/pow/service_test.go index ed3f3f961..9af5de43d 100644 --- a/pow/service_test.go +++ b/pow/service_test.go @@ -7,22 +7,23 @@ package pow import ( "fmt" - transaction2 "github.com/elastos/Elastos.ELA/core/transaction" + "math" "path/filepath" "testing" - "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/core/types/interfaces" - "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" + "github.com/elastos/Elastos.ELA/core/contract/program" + transaction2 "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/dpos/state" "github.com/elastos/Elastos.ELA/utils/test" @@ -42,11 +43,10 @@ func TestService_Init(t *testing.T) { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - - // Initialize default parameters - config.DefaultParams = config.GetDefaultParams() params := &config.DefaultParams + // Initialize default parameters + ckpManager := checkpoint.NewManager(params) chainStore, err := blockchain.NewChainStore(filepath.Join(test.DataPath, "service"), params) if err != nil { t.Error(err) @@ -59,7 +59,7 @@ func TestService_Init(t *testing.T) { "03e281f89d85b3a7de177c240c4961cb5b1f2106f09daa42d15874a38bbeae85dd", "0393e823c2087ed30871cbea9fa5121fa932550821e9f3b17acef0e581971efab0", } - params.CRCArbiters = []string{ + params.DPoSConfiguration.CRCArbiters = []string{ "023a133480176214f88848c6eaa684a54b316849df2b8570b57f3a917f19bbc77a", "030a26f8b4ab0ea219eb461d1e454ce5f0bd0d289a6a64ffc0743dab7bd5be0be9", "0288e79636e41edce04d4fa95d8f62fed73a76164f8631ccc42f5425f960e4a0c7", @@ -79,7 +79,8 @@ func TestService_Init(t *testing.T) { chain, err := blockchain.New(chainStore, params, state.NewState(params, nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil, nil), nil) + nil, nil, nil, nil, nil), nil, + ckpManager) if err != nil { t.Error(err) } diff --git a/servers/interfaces.go b/servers/interfaces.go index d3d23c9c9..0c2e06311 100644 --- a/servers/interfaces.go +++ b/servers/interfaces.go @@ -20,6 +20,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/contract" pg "github.com/elastos/Elastos.ELA/core/contract/program" . "github.com/elastos/Elastos.ELA/core/types" @@ -44,8 +45,7 @@ import ( var ( Compile string - Config *config.Configuration - ChainParams *config.Params + ChainParams *config.Configuration Chain *blockchain.BlockChain Store blockchain.IChainStore TxMemPool *mempool.TxPool @@ -212,7 +212,7 @@ func GetNodeState(param Params) map[string]interface{} { } height := Chain.GetHeight() ver := pact.DPOSStartVersion - if height > uint32(ChainParams.NewP2PProtocolVersionHeight) { + if height > uint32(ChainParams.CRConfiguration.NewP2PProtocolVersionHeight) { ver = pact.CRProposalVersion } return ResponsePack(Success, ServerInfo{ @@ -220,10 +220,10 @@ func GetNodeState(param Params) map[string]interface{} { Height: height, Version: ver, Services: Server.Services().String(), - Port: Config.NodePort, - RPCPort: uint16(Config.HttpJsonPort), - RestPort: uint16(Config.HttpRestPort), - WSPort: uint16(Config.HttpWsPort), + Port: ChainParams.NodePort, + RPCPort: uint16(ChainParams.HttpJsonPort), + RestPort: uint16(ChainParams.HttpRestPort), + WSPort: uint16(ChainParams.HttpWsPort), Neighbors: states, }) } @@ -470,8 +470,8 @@ func GetArbiterPeersInfo(params Params) map[string]interface{} { return ResponsePack(Success, result) } -//if have params stakeAddress get stakeAddress all dposv2 votes -//else get all dposv2 votes +// if have params stakeAddress get stakeAddress all dposv2 votes +// else get all dposv2 votes func GetAllDetailedDPoSV2Votes(params Params) map[string]interface{} { start, _ := params.Int("start") if start < 0 { @@ -552,7 +552,7 @@ func GetAllDetailedDPoSV2Votes(params Params) map[string]interface{} { return ResponsePack(Success, dvi) } -//GetProducerInfo +// GetProducerInfo func GetProducerInfo(params Params) map[string]interface{} { publicKey, ok := params.String("publickey") if !ok { @@ -591,7 +591,7 @@ func GetProducerInfo(params Params) map[string]interface{} { return ResponsePack(Success, producerInfo) } -//by s address. +// by s address. func GetVoteRights(params Params) map[string]interface{} { addresses, ok := params.ArrayString("stakeaddresses") if !ok { @@ -877,7 +877,7 @@ func GetMiningInfo(param Params) map[string]interface{} { Difficulty: Chain.CalcCurrentDifficulty(block.Bits), NetWorkHashPS: Chain.GetNetworkHashPS().String(), PooledTx: uint32(len(TxMemPool.GetTxsInPool())), - Chain: Config.ActiveNet, + Chain: ChainParams.ActiveNet, } return ResponsePack(Success, miningInfo) @@ -1250,7 +1250,7 @@ func GetArbitratorGroupByHeight(param Params) map[string]interface{} { } result := ArbitratorGroupInfo{} - if height < ChainParams.DPOSNodeCrossChainHeight { + if height < ChainParams.DPoSConfiguration.DPOSNodeCrossChainHeight { crcArbiters := Arbiters.GetCRCArbiters() sort.Slice(crcArbiters, func(i, j int) bool { return bytes.Compare(crcArbiters[i].NodePublicKey, crcArbiters[j].NodePublicKey) < 0 @@ -1294,7 +1294,7 @@ func GetAssetByHash(param Params) map[string]interface{} { asset := payload.RegisterAsset{ Asset: payload.Asset{ Name: "ELA", - Precision: config.ELAPrecision, + Precision: core.ELAPrecision, AssetType: 0x00, }, Amount: 0 * 100000000, @@ -1464,6 +1464,7 @@ func GetUTXOsByAmount(param Params) map[string]interface{} { } totalAmount := common.Fixed64(0) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, utxo := range utxos { if totalAmount >= *amount { break @@ -1481,14 +1482,14 @@ func GetUTXOsByAmount(param Params) map[string]interface{} { tx.Outputs()[utxo.Index].Type == common2.OTVote { continue } - if tx.TxType() == common2.CoinBase && bestHeight-height < config.DefaultParams.CoinbaseMaturity { + if tx.TxType() == common2.CoinBase && bestHeight-height < ChainParams.PowConfiguration.CoinbaseMaturity { continue } totalAmount += utxo.Value result = append(result, UTXOInfo{ TxType: byte(tx.TxType()), TxID: common.ToReversedString(utxo.TxID), - AssetID: common.ToReversedString(config.ELAAssetID), + AssetID: common.ToReversedString(*ELAAssetID), VOut: utxo.Index, Amount: utxo.Value.String(), Address: address, @@ -1559,6 +1560,7 @@ func ListUnspent(param Params) map[string]interface{} { return ResponsePack(InvalidParams, "invalid utxotype") } } + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, address := range addresses { programHash, err := common.Uint168FromAddress(address) if err != nil { @@ -1587,7 +1589,7 @@ func ListUnspent(param Params) map[string]interface{} { result = append(result, UTXOInfo{ TxType: byte(tx.TxType()), TxID: common.ToReversedString(utxo.TxID), - AssetID: common.ToReversedString(config.ELAAssetID), + AssetID: common.ToReversedString(*ELAAssetID), VOut: utxo.Index, Amount: utxo.Value.String(), Address: address, @@ -1850,6 +1852,7 @@ func GetUnspends(param Params) map[string]interface{} { if err != nil { return ResponsePack(InvalidParams, "list unspent failed, "+err.Error()) } + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) for _, u := range utxos { var unspendsInfo []UTXOUnspentInfo unspendsInfo = append(unspendsInfo, UTXOUnspentInfo{ @@ -1858,7 +1861,7 @@ func GetUnspends(param Params) map[string]interface{} { u.Value.String()}) results = append(results, Result{ - common.ToReversedString(config.ELAAssetID), + common.ToReversedString(*ELAAssetID), "ELA", unspendsInfo}) } @@ -1895,7 +1898,7 @@ func GetUnspendOutput(param Params) map[string]interface{} { return ResponsePack(Success, UTXOoutputs) } -//BaseTransaction +// BaseTransaction func GetTransactionByHash(param Params) map[string]interface{} { str, ok := param.String("hash") if !ok { @@ -1985,7 +1988,7 @@ func GetExistSideChainReturnDepositTransactions(param Params) map[string]interfa return ResponsePack(Success, resultTxHashes) } -//single producer info +// single producer info type RPCProducerInfo struct { OwnerPublicKey string `json:"ownerpublickey"` NodePublicKey string `json:"nodepublickey"` @@ -2005,14 +2008,14 @@ type RPCProducerInfo struct { Index uint64 `json:"index"` } -//a group producer info include TotalVotes and producer count +// a group producer info include TotalVotes and producer count type RPCProducersInfo struct { ProducerInfoSlice []RPCProducerInfo `json:"producers"` TotalVotes string `json:"totalvotes"` TotalCounts uint64 `json:"totalcounts"` } -//single cr candidate info +// single cr candidate info type RPCCRCandidateInfo struct { Code string `json:"code"` CID string `json:"cid"` @@ -2028,7 +2031,7 @@ type RPCCRCandidateInfo struct { Index uint64 `json:"index"` } -//a group cr candidate info include TotalVotes and candidate count +// a group cr candidate info include TotalVotes and candidate count type RPCCRCandidatesInfo struct { CRCandidateInfoSlice []RPCCRCandidateInfo `json:"crcandidatesinfo"` TotalVotes string `json:"totalvotes"` @@ -2052,7 +2055,7 @@ type RPCCRRelatedStage struct { VotingEndHeight uint32 `json:"votingendheight"` } -//single cr member info +// single cr member info type RPCCRMemberInfo struct { Code string `json:"code"` CID string `json:"cid"` @@ -2069,7 +2072,7 @@ type RPCCRMemberInfo struct { Index uint64 `json:"index"` } -//a group cr member info include cr member count +// a group cr member info include cr member count type RPCCRMembersInfo struct { CRMemberInfoSlice []RPCCRMemberInfo `json:"crmembersinfo"` TotalCounts uint64 `json:"totalcounts"` @@ -2388,7 +2391,7 @@ func GetCRRelatedStage(param Params) map[string]interface{} { return ResponsePack(Success, result) } -//list cr candidates according to ( state , start and limit) +// list cr candidates according to ( state , start and limit) func ListCRCandidates(param Params) map[string]interface{} { start, _ := param.Int("start") if start < 0 { @@ -2477,7 +2480,7 @@ func ListCRCandidates(param Params) map[string]interface{} { return ResponsePack(Success, result) } -//list current crs according to (state) +// list current crs according to (state) func ListCurrentCRs(param Params) map[string]interface{} { cm := Chain.GetCRCommittee() var crMembers []*crstate.CRMember @@ -2525,7 +2528,7 @@ func ListCurrentCRs(param Params) map[string]interface{} { return ResponsePack(Success, result) } -//list next crs according to (state) +// list next crs according to (state) func ListNextCRs(param Params) map[string]interface{} { cm := Chain.GetCRCommittee() var crMembers []*crstate.CRMember diff --git a/test/unit/arbitrators_test.go b/test/unit/arbitrators_test.go index ebd5d46fc..2c01bae08 100644 --- a/test/unit/arbitrators_test.go +++ b/test/unit/arbitrators_test.go @@ -8,17 +8,18 @@ package unit import ( "bytes" "encoding/hex" - state2 "github.com/elastos/Elastos.ELA/dpos/state" "math/rand" "strconv" "testing" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/cr/state" "github.com/elastos/Elastos.ELA/crypto" + state2 "github.com/elastos/Elastos.ELA/dpos/state" "github.com/stretchr/testify/assert" ) @@ -99,9 +100,11 @@ func TestArbitrators_GetSnapshot(t *testing.T) { var bestHeight uint32 params := config.GetDefaultParams() - arbitrators, _ := state2.NewArbitrators(¶ms, + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + arbitrators, _ := state2.NewArbitrators(params, + nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil, nil) + nil, nil, ckpManager) arbitrators.RegisterFunction(func() uint32 { return bestHeight }, func() *common.Uint256 { return &common.Uint256{} }, nil, nil) diff --git a/test/unit/arbitratorsrollback_test.go b/test/unit/arbitratorsrollback_test.go index 6c562af27..b6780b994 100644 --- a/test/unit/arbitratorsrollback_test.go +++ b/test/unit/arbitratorsrollback_test.go @@ -11,6 +11,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" @@ -36,7 +37,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func initArbiters() { @@ -53,20 +54,21 @@ func initArbiters() { a, _ := common.HexStringToBytes(v) abtList = append(abtList, a) } - + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) activeNetParams := &config.DefaultParams - activeNetParams.CRCArbiters = []string{ + activeNetParams.DPoSConfiguration.CRCArbiters = []string{ "03e435ccd6073813917c2d841a0815d21301ec3286bc1412bb5b099178c68a10b6", "038a1829b4b2bee784a99bebabbfecfec53f33dadeeeff21b460f8b4fc7c2ca771", } bestHeight := uint32(0) abt, _ = state.NewArbitrators(activeNetParams, nil, nil, - nil, nil, nil, nil, nil, nil) + nil, nil, nil, + nil, nil, nil, ckpManager) abt.RegisterFunction(func() uint32 { return bestHeight }, func() *common.Uint256 { return &common.Uint256{} }, nil, nil) - abt.State = state.NewState(activeNetParams, nil, nil,nil, + abt.State = state.NewState(activeNetParams, nil, nil, nil, func() bool { return false }, nil, nil, nil, nil, nil, nil, nil) @@ -581,7 +583,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { assert.Equal(t, common.Fixed64(5000*1e8), abt.GetProducer(abtList[0]).DepositAmount()) - currentHeight += abt.ChainParams.CRDepositLockupBlocks + currentHeight += abt.ChainParams.CRConfiguration.DepositLockupBlocks abt.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}, Transactions: []interfaces.Transaction{cancelProducerTx}}, nil) @@ -599,7 +601,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { arbiterStateA := abt.Snapshot() // process - currentHeight = abt.ChainParams.CRVotingStartHeight + currentHeight = abt.ChainParams.CRConfiguration.CRVotingStartHeight abt.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}, Transactions: []interfaces.Transaction{returnDepositTx}}, nil) @@ -665,12 +667,12 @@ func TestArbitrators_RollbackLastBlockOfARound(t *testing.T) { Transactions: []interfaces.Transaction{voteProducerTx}}, nil) // set general arbiters count - abt.ChainParams.GeneralArbiters = 2 + abt.ChainParams.DPoSConfiguration.NormalArbitratorsCount = 2 arbiterStateA := abt.Snapshot() // update next arbiters currentHeight = abt.ChainParams.PublicDPOSHeight - - abt.ChainParams.PreConnectOffset - 1 + abt.ChainParams.DPoSConfiguration.PreConnectOffset - 1 abt.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) arbiterStateB := abt.Snapshot() @@ -778,12 +780,12 @@ func TestArbitrators_NextTurnDposInfoTX(t *testing.T) { Transactions: []interfaces.Transaction{voteProducerTx}}, nil) // set general arbiters count - abt.ChainParams.GeneralArbiters = 2 + abt.ChainParams.DPoSConfiguration.NormalArbitratorsCount = 2 //arbiterStateA := abt.Snapshot() // update next arbiters currentHeight = abt.ChainParams.PublicDPOSHeight - - abt.ChainParams.PreConnectOffset - 1 + abt.ChainParams.DPoSConfiguration.PreConnectOffset - 1 //here generate next turn dpos info tx abt.ProcessBlock(&types.Block{ @@ -859,11 +861,11 @@ func TestArbitrators_RollbackRewardBlock(t *testing.T) { Transactions: []interfaces.Transaction{voteProducerTx}}, nil) // set general arbiters count - abt.ChainParams.GeneralArbiters = 2 + abt.ChainParams.DPoSConfiguration.NormalArbitratorsCount = 2 // preConnect currentHeight = abt.ChainParams.PublicDPOSHeight - - abt.ChainParams.PreConnectOffset - 1 + abt.ChainParams.DPoSConfiguration.PreConnectOffset - 1 abt.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) @@ -1009,7 +1011,7 @@ func TestArbitrators_RollbackMultipleTransactions(t *testing.T) { arbiterStateA := abt.Snapshot() // process - currentHeight = abt.ChainParams.CRVotingStartHeight + currentHeight = abt.ChainParams.CRConfiguration.CRVotingStartHeight abt.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}, Transactions: []interfaces.Transaction{ diff --git a/test/unit/blockvalidator_test.go b/test/unit/blockvalidator_test.go index c7df50c71..e19c2de0a 100644 --- a/test/unit/blockvalidator_test.go +++ b/test/unit/blockvalidator_test.go @@ -19,6 +19,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" transaction2 "github.com/elastos/Elastos.ELA/core/transaction" @@ -59,13 +60,15 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestCheckBlockSanity(t *testing.T) { log.NewDefault(test.NodeLogPath, 0, 0, 0) - params := config.GetDefaultParams() - blockchain.FoundationAddress = params.Foundation + params := *config.GetDefaultParams() + FoundationAddress, _ := common.Uint168FromAddress(params.FoundationAddress) + blockchain.FoundationAddress = *FoundationAddress + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) chainStore, err := blockchain.NewChainStore(filepath.Join(test.DataPath, "sanity"), ¶ms) if err != nil { t.Error(err.Error()) @@ -75,7 +78,8 @@ func TestCheckBlockSanity(t *testing.T) { chain, _ := blockchain.New(chainStore, ¶ms, state.NewState(¶ms, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil), nil) + nil, nil, nil), nil, + ckpManager) //chain.Init(nil) if blockchain.DefaultLedger == nil { blockchain.DefaultLedger = &blockchain.Ledger{ @@ -602,7 +606,6 @@ func getCID(code []byte) *common.Uint168 { return ct1.ToProgramHash() } - func TestSchnorr(t *testing.T) { rawTxStr := "09020001001332323837373031313533373638303434393437013D4321277C999B4428BE031857DCB55ADAF04F706EAFBB9ACDC25C595DA3900101000000000001B037DB964A231458D2D6FFD5EA18944C4F90E63D547C5D3B9874DF66A4EAD0A3B763A900000000000000000021BE47F0B3851EDD38D3FD08A9F3ADA677E8913E62000000000001414056303BD38A49DAF60DC7F6AEFDD8D620FC4D6C197C4EE0176A4C74EE5CCF5E21790084DFE37A1C79A702DA5D25E40C6482D5A0590BAD2239C5C6E414CEA4F49D2351210364CB605A75B15705E3D4F881493491BF4851430E11E350C7E8FF873829978674" data, err := common.HexStringToBytes(rawTxStr) @@ -673,4 +676,4 @@ func checkSchnorrSignatures(program program.Program, data [32]byte) (bool, error copy(signature[:], program.Parameter[:64]) return crypto.SchnorrVerify(publicKey, data, signature) -} \ No newline at end of file +} diff --git a/test/unit/candidate_test.go b/test/unit/candidate_test.go index 4e4fdc79e..1e5675452 100644 --- a/test/unit/candidate_test.go +++ b/test/unit/candidate_test.go @@ -28,7 +28,7 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestCandidate_Deserialize(t *testing.T) { diff --git a/test/unit/chainstore_test.go b/test/unit/chainstore_test.go index 34d651095..dc27a5bb0 100644 --- a/test/unit/chainstore_test.go +++ b/test/unit/chainstore_test.go @@ -7,10 +7,12 @@ package unit import ( "testing" + "time" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core" "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/stretchr/testify/assert" @@ -23,14 +25,38 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() +} + +func TestGenesisBlock(t *testing.T) { + mainNetFoundation := "8VYXVxKKSAxkmRrfmGpQR2Kc66XhG6m3ta" + + block := core.GenesisBlock(mainNetFoundation) + assert.Equal(t, len(block.Transactions), 2) + genesisHash := block.Hash().String() + assert.Equal(t, "8d7014f2f941caa1972c8033b2f0a860ec8d4938b12bae2c62512852a558f405", genesisHash) + + testNetFoundation := "8ZNizBf4KhhPjeJRGpox6rPcHE5Np6tFx3" + genesisHash = core.GenesisBlock(testNetFoundation).Hash().String() + assert.Equal(t, "b3314f465ea5556d570bcc473d59a0855b4405a25b1ea0c957c81b2920be1864", genesisHash) + + date := time.Date(2017, time.December, 22, 10, + 0, 0, 0, time.UTC).Unix() + dateUnix := time.Unix(time.Date(2017, time.December, 22, 10, + 0, 0, 0, time.UTC).Unix(), 0).Unix() + + dateTime, err := time.Parse(time.RFC3339, "2017-12-22T10:00:00Z") + assert.NoError(t, err) + assert.Equal(t, date, dateUnix) + assert.Equal(t, date, dateTime.Unix()) } func TestCheckAssetPrecision(t *testing.T) { tx := buildTx() + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) // valid precision for _, output := range tx.Outputs() { - output.AssetID = config.ELAAssetID + output.AssetID = *ELAAssetID output.ProgramHash = common.Uint168{} output.Value = 123456789876 } @@ -38,7 +64,7 @@ func TestCheckAssetPrecision(t *testing.T) { assert.NoError(t, err) for _, output := range tx.Outputs() { - output.AssetID = config.ELAAssetID + output.AssetID = *ELAAssetID output.ProgramHash = common.Uint168{} output.Value = 0 } diff --git a/test/unit/committee_test.go b/test/unit/committee_test.go index c0aa0ae8b..e0388cec4 100644 --- a/test/unit/committee_test.go +++ b/test/unit/committee_test.go @@ -12,6 +12,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract/program" transaction2 "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" @@ -28,13 +29,12 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestSortTransactions(t *testing.T) { - types := []common2.TxType{common2.CoinBase, common2.TransferAsset, common2.TransferAsset, - common2.CRCProposalTracking, common2.CRCProposalWithdraw, common2.CRCProposalWithdraw, - common2.TransferAsset, common2.CRCProposalWithdraw, + types := []common2.TxType{common2.CoinBase, common2.TransferAsset, + common2.CRCProposalTracking, common2.CRCProposalWithdraw, } var txs []interfaces.Transaction for _, t := range types { @@ -54,16 +54,14 @@ func TestSortTransactions(t *testing.T) { state.SortTransactions(txs[1:]) assert.Equal(t, txs[0].TxType().Name(), "CoinBase") assert.Equal(t, txs[1].TxType().Name(), "CRCProposalWithdraw") - assert.Equal(t, txs[2].TxType().Name(), "CRCProposalWithdraw") - assert.Equal(t, txs[3].TxType().Name(), "CRCProposalWithdraw") - assert.Equal(t, txs[4].TxType().Name(), "TransferAsset") - assert.Equal(t, txs[5].TxType().Name(), "TransferAsset") - assert.Equal(t, txs[6].TxType().Name(), "CRCProposalTracking") - assert.Equal(t, txs[7].TxType().Name(), "TransferAsset") + assert.Equal(t, txs[2].TxType().Name(), "CRCProposalTracking") + assert.Equal(t, txs[3].TxType().Name(), "TransferAsset") } func TestNewCRCommittee(t *testing.T) { - committee := state.NewCommittee(&config.DefaultParams) + ckpManager := checkpoint.NewManager(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, + ckpManager) assert.Equal(t, uint32(0), committee.LastCommitteeHeight) assert.Equal(t, 0, len(committee.GetMembersCodes())) @@ -71,7 +69,8 @@ func TestNewCRCommittee(t *testing.T) { } func TestCommittee_ProcessBlock(t *testing.T) { - committee := state.NewCommittee(&config.DefaultParams) + ckpManager := checkpoint.NewManager(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) round1, expectCandidates1, votes1 := generateCandidateSuite() round2, expectCandidates2, votes2 := generateCandidateSuite() committee.GetState().StateKeyFrame = *round1 @@ -79,7 +78,7 @@ func TestCommittee_ProcessBlock(t *testing.T) { // < CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{ - Height: config.DefaultParams.CRCommitteeStartHeight - 1, + Height: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight - 1, }, }, nil) assert.Equal(t, 0, len(committee.GetMembersCodes())) @@ -88,7 +87,7 @@ func TestCommittee_ProcessBlock(t *testing.T) { // CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{ - Height: config.DefaultParams.CRCommitteeStartHeight, + Height: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight, }, }, nil) codes1 := committee.GetMembersCodes() @@ -112,8 +111,8 @@ func TestCommittee_ProcessBlock(t *testing.T) { committee.GetState().StateKeyFrame = *round2 committee.ProcessBlock(&types.Block{ Header: common2.Header{ - Height: config.DefaultParams.CRCommitteeStartHeight + - config.DefaultParams.CRDutyPeriod - 1, + Height: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + config.DefaultParams.CRConfiguration.DutyPeriod - 1, }, }, nil) codes2 := committee.GetMembersCodes() @@ -126,12 +125,12 @@ func TestCommittee_ProcessBlock(t *testing.T) { } // CRCommitteeStartHeight + CRDutyPeriod - committee.LastVotingStartHeight = config.DefaultParams.CRCommitteeStartHeight + - config.DefaultParams.CRDutyPeriod - config.DefaultParams.CRVotingPeriod + committee.LastVotingStartHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + config.DefaultParams.CRConfiguration.DutyPeriod - config.DefaultParams.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{ - Height: config.DefaultParams.CRCommitteeStartHeight + - config.DefaultParams.CRDutyPeriod, + Height: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + config.DefaultParams.CRConfiguration.DutyPeriod, }, }, nil) codes2 = committee.GetMembersCodes() @@ -163,93 +162,95 @@ func sortDIDList(cid []common.Uint168, votes map[common.Uint168]common.Fixed64) } func TestCommittee_IsInVotingPeriod(t *testing.T) { - committee := state.NewCommittee(&config.DefaultParams) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // 0 assert.False(t, committee.IsInVotingPeriod(0)) // < CRVotingStartHeight assert.False(t, committee.IsInVotingPeriod( - config.DefaultParams.CRVotingStartHeight-1)) + config.DefaultParams.CRConfiguration.CRVotingStartHeight-1)) // [CRVotingStartHeight, CRCommitteeStartHeight - CRVotingPeriod] assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight- - config.DefaultParams.CRVotingPeriod-1)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight- + config.DefaultParams.CRConfiguration.VotingPeriod-1)) // CRCommitteeStartHeight - CRVotingPeriod assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight- - config.DefaultParams.CRVotingPeriod)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight- + config.DefaultParams.CRConfiguration.VotingPeriod)) // [CRCommitteeStartHeight - CRVotingPeriod, CRCommitteeStartHeight) assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight- - config.DefaultParams.CRVotingPeriod+1)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight- + config.DefaultParams.CRConfiguration.VotingPeriod+1)) // CRCommitteeStartHeight assert.False(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight)) // change to first committee - committee.LastCommitteeHeight = config.DefaultParams.CRCommitteeStartHeight + committee.LastCommitteeHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight // < CRCommitteeStartHeight + CRDutyPeriod - CRVotingPeriod committee.InElectionPeriod = true assert.False(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod-config.DefaultParams. - CRVotingPeriod-1)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod-config.DefaultParams. + CRConfiguration.VotingPeriod-1)) // CRCommitteeStartHeight + CRDutyPeriod - CRVotingPeriod assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod-config.DefaultParams. - CRVotingPeriod)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod-config.DefaultParams. + CRConfiguration.VotingPeriod)) // [CRCommitteeStartHeight + CRDutyPeriod - CRVotingPeriod, // CRCommitteeStartHeight + CRDutyPeriod) assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod-config.DefaultParams. - CRVotingPeriod+1)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod-config.DefaultParams. + CRConfiguration.VotingPeriod+1)) // CRCommitteeStartHeight + CRDutyPeriod assert.False(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod)) // change to next committee committee.LastCommitteeHeight = config.DefaultParams. - CRCommitteeStartHeight + config.DefaultParams.CRDutyPeriod + CRConfiguration.CRCommitteeStartHeight + config.DefaultParams.CRConfiguration.DutyPeriod // < CRCommitteeStartHeight + CRDutyPeriod * 2 - CRVotingPeriod assert.False(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod*2-config.DefaultParams. - CRVotingPeriod-1)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod*2-config.DefaultParams. + CRConfiguration.VotingPeriod-1)) // CRCommitteeStartHeight + CRDutyPeriod * 2 - CRVotingPeriod assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod*2-config.DefaultParams. - CRVotingPeriod)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod*2-config.DefaultParams. + CRConfiguration.VotingPeriod)) // [CRCommitteeStartHeight + CRDutyPeriod - CRVotingPeriod, // CRCommitteeStartHeight + CRDutyPeriod) assert.True(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod*2-config.DefaultParams. - CRVotingPeriod+1)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod*2-config.DefaultParams. + CRConfiguration.VotingPeriod+1)) // CRCommitteeStartHeight + CRDutyPeriod * 2 assert.False(t, committee.IsInVotingPeriod( - config.DefaultParams.CRCommitteeStartHeight+ - config.DefaultParams.CRDutyPeriod*2)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight+ + config.DefaultParams.CRConfiguration.DutyPeriod*2)) } func TestCommittee_RollbackTo_SameCommittee_VotingPeriod(t *testing.T) { - committee := state.NewCommittee(&config.DefaultParams) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) committee.RegisterFuncitons(&state.CommitteeFuncsConfig{}) code := randomBytes(34) @@ -257,8 +258,8 @@ func TestCommittee_RollbackTo_SameCommittee_VotingPeriod(t *testing.T) { cid := *randomUint168() // register candidate - height := config.DefaultParams.CRCommitteeStartHeight - - config.DefaultParams.CRVotingPeriod + height := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight - + config.DefaultParams.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: height, @@ -303,23 +304,24 @@ func TestCommittee_RollbackTo_SameCommittee_VotingPeriod(t *testing.T) { // rollback to the nickname before update assert.NoError(t, committee.RollbackTo( - config.DefaultParams.CRCommitteeStartHeight- - config.DefaultParams.CRVotingPeriod)) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight- + config.DefaultParams.CRConfiguration.VotingPeriod)) assert.True(t, committee.ExistCandidateByNickname(nickname)) } func TestCommittee_RollbackTo_SameCommittee_BeforeVoting(t *testing.T) { //let committee be the first committee started state keyframe := randomKeyFrame(12, - config.DefaultParams.CRCommitteeStartHeight) + config.DefaultParams.CRConfiguration.CRCommitteeStartHeight) keyframe.InElectionPeriod = false - committee := state.NewCommittee(&config.DefaultParams) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) committee.KeyFrame = *keyframe committee.RegisterFuncitons(&state.CommitteeFuncsConfig{}) // let processing height be 6 blocks before the second voting - height := config.DefaultParams.CRCommitteeStartHeight + config. - DefaultParams.CRDutyPeriod - config.DefaultParams.CRVotingPeriod - 6 + height := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + config. + DefaultParams.CRConfiguration.DutyPeriod - config.DefaultParams.CRConfiguration.VotingPeriod - 6 // simulate processing register CR before and after CR for i := 0; i < 10; i++ { @@ -348,8 +350,8 @@ func TestCommittee_RollbackTo_SameCommittee_BeforeVoting(t *testing.T) { assert.Equal(t, 4, len(committee.GetCandidates(state.Active))) // rollback to the voting height - height = config.DefaultParams.CRCommitteeStartHeight + config. - DefaultParams.CRDutyPeriod - config.DefaultParams.CRVotingPeriod + height = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + config. + DefaultParams.CRConfiguration.DutyPeriod - config.DefaultParams.CRConfiguration.VotingPeriod assert.NoError(t, committee.RollbackTo(height)) assert.False(t, keyframeEqual(keyframe, &committee.KeyFrame)) assert.Equal(t, 2, len(committee.GetCandidates(state.Active))) diff --git a/test/unit/committeerollback_test.go b/test/unit/committeerollback_test.go index 0c51eea9b..fd1c48507 100644 --- a/test/unit/committeerollback_test.go +++ b/test/unit/committeerollback_test.go @@ -12,6 +12,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" @@ -34,7 +35,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func getCIDByPublicKeyStr(publicKey string) *common.Uint168 { @@ -410,11 +411,13 @@ func TestCommittee_RollbackRegisterAndVoteCR(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, + ckpManager) // avoid getting UTXOs from database - currentHeight := config.DefaultParams.CRVotingStartHeight + currentHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -497,14 +500,15 @@ func TestCommittee_RollbackEndVotingPeriod(t *testing.T) { // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(cfg) + committee := state.NewCommittee(cfg, ckpManager) // avoid getting UTXOs from database - currentHeight := config.DefaultParams.CRVotingStartHeight + currentHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -545,7 +549,7 @@ func TestCommittee_RollbackEndVotingPeriod(t *testing.T) { }, }, nil) - currentHeight = cfg.CRCommitteeStartHeight - 1 + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight - 1 committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 0, len(committee.GetCurrentMembers())) @@ -601,15 +605,16 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { // set count of CR member params := config.GetDefaultParams() - cfg := ¶ms - cfg.CRCArbiters = cfg.CRCArbiters[0:4] - cfg.CRMemberCount = 4 + cfg := params + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:4] + cfg.CRConfiguration.MemberCount = 4 + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(cfg) + committee := state.NewCommittee(cfg, ckpManager) // avoid getting UTXOs from database - currentHeight := config.DefaultParams.CRVotingStartHeight + currentHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -662,7 +667,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { }, }, nil) - currentHeight = cfg.CRCommitteeStartHeight - 1 + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight - 1 committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) keyFrameA := committee.Snapshot() @@ -725,7 +730,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { }, nil) // set current Height to one block before ending voting period - currentHeight = cfg.CRCommitteeStartHeight - 1 + cfg.CRVotingPeriod + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight - 1 + cfg.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) keyFrameA2 := committee.Snapshot() @@ -776,16 +781,17 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr every cr DepositAmount is 5000 committee.ProcessBlock(&types.Block{ @@ -828,14 +834,14 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { //did1 did2 is cr did3 is candidate //did1 did2 DepositAmount 5000 ela //did3 is candidate DepositAmount 0 ela - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) // register cr again did1 did2 10000 did3 5000 - currentHeight = config.DefaultParams.CRCommitteeStartHeight + - cfg.CRDutyPeriod - cfg.CRVotingPeriod + currentHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + cfg.CRConfiguration.DutyPeriod - cfg.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -877,7 +883,7 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { //change commitee old cr did1 did2 -5000 DepositAmount 5000 //did1 is candidate -5000 DepositAmount 0 //did3 5000 - currentHeight = cfg.CRCommitteeStartHeight + cfg.CRDutyPeriod + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight + cfg.CRConfiguration.DutyPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) @@ -920,18 +926,19 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 - cfg.CRAgreementCount = 2 - cfg.CRClaimDPOSNodePeriod = 1000000 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + cfg.CRConfiguration.CRAgreementCount = 2 + cfg.CRConfiguration.CRClaimDPOSNodePeriod = 1000000 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -971,7 +978,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*did1).Votes) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) @@ -1012,7 +1019,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { checkResult(t, keyFrameA, keyFrameB, keyFrameC, keyFrameD) // set CR agreement count - committee.Params.CRAgreementCount = 2 + committee.Params.CRConfiguration.CRAgreementCount = 2 // review proposal proposalReviewTx1 := getCRCProposalReviewTx(proposalHash, payload.Approve, @@ -1053,7 +1060,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { // change to CRAgreed keyFrameA3 := committee.Snapshot() - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalHash).Status) @@ -1077,8 +1084,8 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { // change to VoterAgreed keyFrameA4 := committee.Snapshot() - currentHeight += cfg.ProposalPublicVotingPeriod - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalPublicVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.VoterAgreed, committee.GetProposal(proposalHash).Status) @@ -1121,16 +1128,17 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -1170,7 +1178,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*did1).Votes) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) @@ -1190,7 +1198,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { //assert.Equal(t, 2, committee.GetProposal(proposalTx.Payload.(*payload.CRCProposal).Hash())) // set CR agreement count - committee.Params.CRAgreementCount = 2 + committee.Params.CRConfiguration.CRAgreementCount = 2 // review proposal proposalReviewTx1 := getCRCProposalReviewTx(proposalHash, payload.Approve, @@ -1209,13 +1217,13 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { assert.Equal(t, state.Registered, committee.GetProposal(proposalHash).Status) // change to CRAgreed - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalHash).Status) // change to VoterAgreed - currentHeight += cfg.ProposalPublicVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalPublicVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.VoterAgreed, committee.GetProposal(proposalHash).Status) @@ -1223,7 +1231,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { // set secretary-general publicKeyStr4 := "027209c3a6bcb95e9ef766c81136bcd6f2338eee7f9caebf694825e411320bab12" privateKeyStr4 := "b3b1c16abd786c4994af9ee8c79d25457f66509731f74d6a9a9673ca872fa8fa" - committee.Params.SecretaryGeneral = publicKeyStr4 + committee.Params.CRConfiguration.SecretaryGeneral = publicKeyStr4 committee.GetHeight = func() uint32 { return currentHeight } @@ -1319,16 +1327,17 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -1368,7 +1377,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*did1).Votes) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) @@ -1387,7 +1396,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { assert.Equal(t, 1, len(committee.GetProposals(state.Registered))) // set CR agreement count - committee.Params.CRAgreementCount = 2 + committee.Params.CRConfiguration.CRAgreementCount = 2 // review proposal proposalReviewTx1 := getCRCProposalReviewTx(proposalHash, payload.Approve, @@ -1406,13 +1415,13 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { assert.Equal(t, state.Registered, committee.GetProposal(proposalHash).Status) // change to CRAgreed - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalHash).Status) // change to VoterAgreed - currentHeight += cfg.ProposalPublicVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalPublicVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.VoterAgreed, committee.GetProposal(proposalHash).Status) @@ -1454,7 +1463,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { // set secretary-general publicKeyStr4 := "027209c3a6bcb95e9ef766c81136bcd6f2338eee7f9caebf694825e411320bab12" privateKeyStr4 := "b3b1c16abd786c4994af9ee8c79d25457f66509731f74d6a9a9673ca872fa8fa" - committee.Params.SecretaryGeneral = publicKeyStr4 + committee.Params.CRConfiguration.SecretaryGeneral = publicKeyStr4 committee.GetHeight = func() uint32 { return currentHeight } @@ -1542,17 +1551,18 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 - cfg.CRAgreementCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + cfg.CRConfiguration.CRAgreementCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -1592,19 +1602,19 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*did1).Votes) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) - currentHeight = config.DefaultParams.CRCommitteeStartHeight + - cfg.CRDutyPeriod - cfg.CRVotingPeriod - 1 + currentHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + cfg.CRConfiguration.DutyPeriod - cfg.CRConfiguration.VotingPeriod - 1 committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) // register cr again - currentHeight = config.DefaultParams.CRCommitteeStartHeight + - cfg.CRDutyPeriod - cfg.CRVotingPeriod + currentHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + cfg.CRConfiguration.DutyPeriod - cfg.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -1641,7 +1651,7 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { keyFrameA := committee.Snapshot() // end second voting period - currentHeight = cfg.CRCommitteeStartHeight + cfg.CRDutyPeriod + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight + cfg.CRConfiguration.DutyPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, false, committee.IsInElectionPeriod()) @@ -1694,14 +1704,15 @@ func TestCommittee_RollbackCRCAppropriationTx(t *testing.T) { // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(cfg) + committee := state.NewCommittee(cfg, ckpManager) // avoid getting UTXOs from database - currentHeight := config.DefaultParams.CRVotingStartHeight + currentHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight committee.RegisterFuncitons(&state.CommitteeFuncsConfig{ GetHeight: func() uint32 { return currentHeight @@ -1747,7 +1758,7 @@ func TestCommittee_RollbackCRCAppropriationTx(t *testing.T) { }, nil) //currentHeight to before CRCommitteeStartHeight - currentHeight = cfg.CRCommitteeStartHeight - 1 + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight - 1 committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 0, len(committee.GetCurrentMembers())) @@ -1897,14 +1908,15 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(cfg) + committee := state.NewCommittee(cfg, ckpManager) // avoid getting UTXOs from database - currentHeight := config.DefaultParams.CRVotingStartHeight + currentHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -1943,7 +1955,7 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { }, }, nil) - currentHeight = cfg.CRCommitteeStartHeight - 1 + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight - 1 committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 0, len(committee.GetCurrentMembers())) @@ -1951,7 +1963,7 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { // process //here change committee - committee.Params.CRAgreementCount = 2 + committee.Params.CRConfiguration.CRAgreementCount = 2 currentHeight++ committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) @@ -2031,14 +2043,15 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(cfg) + committee := state.NewCommittee(cfg, ckpManager) // avoid getting UTXOs from database - currentHeight := config.DefaultParams.CRVotingStartHeight + currentHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -2077,7 +2090,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { }, }, nil) - currentHeight = cfg.CRCommitteeStartHeight - 1 + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight - 1 committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 0, len(committee.GetCurrentMembers())) @@ -2085,7 +2098,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { // process //here change committee - committee.Params.CRAgreementCount = 2 + committee.Params.CRConfiguration.CRAgreementCount = 2 currentHeight++ committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) @@ -2107,7 +2120,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { //here process impeachment //generate impeachment tx impeachValue := committee.CirculationAmount*common.Fixed64(committee. - Params.VoterRejectPercentage)/common.Fixed64(100) + 1 + Params.CRConfiguration.VoterRejectPercentage)/common.Fixed64(100) + 1 impeachmentTx := getCRCImpeachmentTx(publicKeyStr1, did1, impeachValue, *address1Uint168) currentHeight++ @@ -2209,16 +2222,17 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 - cfg.CRAgreementCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + cfg.CRConfiguration.CRAgreementCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ Header: common2.Header{ @@ -2271,7 +2285,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { publicKeyStr2, privateKeyStr2) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -2319,15 +2333,15 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { assert.Equal(t, state.Registered, committee.GetProposal(proposalCHash).Status) // change to CRAgreed - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalBHash).Status) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalCHash).Status) // register cr again - currentHeight = config.DefaultParams.CRCommitteeStartHeight + - cfg.CRDutyPeriod - cfg.CRVotingPeriod + currentHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + cfg.CRConfiguration.DutyPeriod - cfg.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -2350,7 +2364,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { withdrawCTx := getCRCProposalWithdrawTx(proposalCHash, publicKeyStr1, privateKeyStr1, 1, []*common2.Input{}, []*common2.Output{}) impeachValue := committee.CirculationAmount*common.Fixed64(committee. - Params.VoterRejectPercentage)/common.Fixed64(100) + 1 + Params.CRConfiguration.VoterRejectPercentage)/common.Fixed64(100) + 1 //generate impeachment tx impeachmentTx := getCRCImpeachmentTx(publicKeyStr1, did1, impeachValue, *address1Uint168) @@ -2439,16 +2453,17 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 - cfg.CRAgreementCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + cfg.CRConfiguration.CRAgreementCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight committee.RegisterFuncitons(&state.CommitteeFuncsConfig{ GetHeight: func() uint32 { return currentHeight @@ -2507,7 +2522,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { publicKeyStr2, privateKeyStr2) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -2555,15 +2570,15 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { assert.Equal(t, state.Registered, committee.GetProposal(proposalCHash).Status) // change to CRAgreed - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalBHash).Status) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalCHash).Status) // register cr again - currentHeight = config.DefaultParams.CRCommitteeStartHeight + - cfg.CRDutyPeriod - cfg.CRVotingPeriod + currentHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + cfg.CRConfiguration.DutyPeriod - cfg.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -2587,7 +2602,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { withdrawCTx := getCRCProposalWithdrawTx(proposalCHash, publicKeyStr1, privateKeyStr1, 1, []*common2.Input{}, []*common2.Output{}) impeachValue := committee.CirculationAmount*common.Fixed64(committee. - Params.VoterRejectPercentage)/common.Fixed64(100) + 1 + Params.CRConfiguration.VoterRejectPercentage)/common.Fixed64(100) + 1 //generate impeachment tx impeachmentTx := getCRCImpeachmentTx(publicKeyStr1, did1, impeachValue, *address1Uint168) @@ -2640,8 +2655,8 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { }, }, nil) - currentHeight = cfg.CRCommitteeStartHeight + cfg.CRDutyPeriod + 1 - committee.LastVotingStartHeight = currentHeight - cfg.CRVotingPeriod + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight + cfg.CRConfiguration.DutyPeriod + 1 + committee.LastVotingStartHeight = currentHeight - cfg.CRConfiguration.VotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) @@ -2705,17 +2720,18 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { registerCRTxn1 := getRegisterCRTx(publicKeyStr1, privateKeyStr1, nickName1) registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 - cfg.CRAgreementCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + cfg.CRConfiguration.CRAgreementCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -2764,7 +2780,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { publicKeyStr2, privateKeyStr2) proposalCHash := proposalTxC.Payload().(*payload.CRCProposal).Hash(payload.CRCProposalVersion01) - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, @@ -2810,14 +2826,14 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { assert.Equal(t, state.Registered, committee.GetProposal(proposalCHash).Status) // register to CRAgreed - currentHeight += cfg.ProposalPublicVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalPublicVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalBHash).Status) assert.Equal(t, state.CRAgreed, committee.GetProposal(proposalCHash).Status) // change to CRAgreed - currentHeight += cfg.ProposalCRVotingPeriod + currentHeight += cfg.CRConfiguration.ProposalCRVotingPeriod committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 1, len(committee.GetProposal(proposalBHash). @@ -2889,7 +2905,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { WithdrawnBudgets)) // rollback - currentHeight = cfg.CRVotingStartHeight + currentHeight = cfg.CRConfiguration.CRVotingStartHeight err := committee.RollbackTo(currentHeight) assert.NoError(t, err) keyFrameC := committee.Snapshot() @@ -2920,17 +2936,18 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { registerCRTxn1 := getRegisterCRTx(publicKeyStr1, privateKeyStr1, nickName1) registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) registerFuncs(committee.GetState()) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ Header: common2.Header{ @@ -2980,7 +2997,7 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { returnDepositTx1 := generateReturnDeposite(publicKeyStr1) returnDepositTx2 := generateReturnDeposite(publicKeyStr2) - currentHeight += committee.Params.CRDepositLockupBlocks + 1 + currentHeight += committee.Params.CRConfiguration.DepositLockupBlocks + 1 // returnDepositTx committee.ProcessBlock(&types.Block{ Header: common2.Header{ @@ -2996,7 +3013,7 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { assert.Equal(t, state.Returned, committee.GetCandidate(*cid2).State) // rollback - currentHeight = cfg.CRVotingStartHeight + currentHeight = cfg.CRConfiguration.CRVotingStartHeight err := committee.RollbackTo(currentHeight) assert.NoError(t, err) keyFrameC := committee.Snapshot() @@ -3023,16 +3040,17 @@ func TestCommittee_RollbackReview(t *testing.T) { registerCRTxn2 := getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2) registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // set count of CR member cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight //committee.recordBalanceHeight = currentHeight - 1 // register cr @@ -3073,7 +3091,7 @@ func TestCommittee_RollbackReview(t *testing.T) { assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*did1).Votes) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) @@ -3114,7 +3132,7 @@ func TestCommittee_RollbackReview(t *testing.T) { checkResult(t, keyFrameA, keyFrameB, keyFrameC, keyFrameD) // set CR agreement count - committee.Params.CRAgreementCount = 2 + committee.Params.CRConfiguration.CRAgreementCount = 2 // review proposal Approve proposalReviewTx1 := getCRCProposalReviewTx(proposalHash, payload.Approve, diff --git a/test/unit/crkeyframe_test.go b/test/unit/crkeyframe_test.go index d3eead239..e66b7b046 100644 --- a/test/unit/crkeyframe_test.go +++ b/test/unit/crkeyframe_test.go @@ -29,7 +29,7 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestKeyFrame_Deserialize(t *testing.T) { diff --git a/test/unit/dposkeyframe_test.go b/test/unit/dposkeyframe_test.go index e37e96c5e..8c0aaee5e 100644 --- a/test/unit/dposkeyframe_test.go +++ b/test/unit/dposkeyframe_test.go @@ -29,7 +29,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestRewardData_Deserialize(t *testing.T) { @@ -574,7 +574,7 @@ func arbiterMemberEqual(first state.ArbiterMember, second state.ArbiterMember) b return false } -// NextCRCArbitersMap map[common.Uint168]ArbiterMember +// NextCRCArbitersMap map[common.Uint168]ArbiterMember func arbitersMapEqual(first map[common.Uint168]state.ArbiterMember, second map[common.Uint168]state.ArbiterMember) bool { if len(first) != len(second) { diff --git a/test/unit/dposstate_test.go b/test/unit/dposstate_test.go index 4f8c41684..e63ae5ff3 100644 --- a/test/unit/dposstate_test.go +++ b/test/unit/dposstate_test.go @@ -34,7 +34,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } // mockBlock creates a block instance by the given height and transactions. @@ -254,7 +254,7 @@ func mockInactiveArbitratorsTx(publicKey []byte) interfaces.Transaction { } func TestState_ProcessTransaction(t *testing.T) { - params := config.GetDefaultParams() + params := *config.GetDefaultParams() state := state2.NewState(¶ms, nil, nil, nil, func() bool { return false }, nil, nil, nil, @@ -1047,8 +1047,8 @@ func TestState_InactiveProducer_Normal(t *testing.T) { func() bool { return false }, nil, nil, nil, nil, nil, nil, nil) - state.ChainParams.InactivePenalty = 50 - state.ChainParams.ChangeCommitteeNewCRHeight = 1 + state.ChainParams.DPoSConfiguration.InactivePenalty = 50 + state.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight = 1 state.ChainParams.DPoSV2StartHeight = 1 // Create 10 producers info. producers := make([]*payload.ProducerInfo, 10) @@ -1090,7 +1090,7 @@ func TestState_InactiveProducer_Normal(t *testing.T) { currentHeight := 11 config.DefaultParams.PublicDPOSHeight = 11 - config.DefaultParams.MaxInactiveRounds = 10 + config.DefaultParams.DPoSConfiguration.MaxInactiveRounds = 10 // simulate producers[0] do not sign for continuous 11 blocks for round := 0; round < 3; round++ { @@ -1114,7 +1114,7 @@ func TestState_InactiveProducer_Normal(t *testing.T) { // check penalty inactiveProducer := state.GetProducer(producers[0].NodePublicKey) if !assert.Equal(t, inactiveProducer.Penalty(), - state.ChainParams.InactivePenalty) { + state.ChainParams.DPoSConfiguration.InactivePenalty) { t.FailNow() } } @@ -1166,7 +1166,7 @@ func TestState_InactiveProducer_FailNoContinuous(t *testing.T) { currentHeight := 11 config.DefaultParams.PublicDPOSHeight = 11 - config.DefaultParams.MaxInactiveRounds = 10 + config.DefaultParams.DPoSConfiguration.MaxInactiveRounds = 10 // simulate producers[0] do not sign for over 10 blocks, // but is not continuous @@ -1204,7 +1204,7 @@ func TestState_InactiveProducer_RecoverFromInactiveState(t *testing.T) { func() bool { return false }, nil, nil, nil, nil, nil, nil, nil) - state.ChainParams.ChangeCommitteeNewCRHeight = 1 + state.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight = 1 state.ChainParams.DPoSV2StartHeight = 1 // Create 10 producers info. producers := make([]*payload.ProducerInfo, 10) @@ -1246,7 +1246,7 @@ func TestState_InactiveProducer_RecoverFromInactiveState(t *testing.T) { currentHeight := 11 config.DefaultParams.PublicDPOSHeight = 11 - config.DefaultParams.MaxInactiveRounds = 10 + config.DefaultParams.DPoSConfiguration.MaxInactiveRounds = 10 // simulate producers[0] do not sign for continuous 11 blocks for round := 0; round < 3; round++ { @@ -1270,7 +1270,7 @@ func TestState_InactiveProducer_RecoverFromInactiveState(t *testing.T) { // check penalty inactiveProducer := state.GetProducer(producers[0].NodePublicKey) if !assert.Equal(t, inactiveProducer.Penalty(), - state.ChainParams.InactivePenalty) { + state.ChainParams.DPoSConfiguration.InactivePenalty) { t.FailNow() } @@ -1299,7 +1299,7 @@ func TestState_InactiveProducer_DuringUpdateVersion(t *testing.T) { func() bool { return false }, nil, nil, nil, nil, nil, nil, nil) - state.ChainParams.InactivePenalty = 50 + state.ChainParams.DPoSConfiguration.InactivePenalty = 50 // Create 10 producers info. producers := make([]*payload.ProducerInfo, 10) @@ -1360,7 +1360,7 @@ func TestState_InactiveProducer_DuringUpdateVersion(t *testing.T) { currentHeight++ config.DefaultParams.PublicDPOSHeight = 11 - config.DefaultParams.MaxInactiveRounds = 10 + config.DefaultParams.DPoSConfiguration.MaxInactiveRounds = 10 // simulate producers[0] do not sign for continuous 11 blocks for round := 0; round < 3; round++ { @@ -1394,7 +1394,7 @@ func TestDPoSState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { func() bool { return false }, nil, nil, nil, nil, nil, nil, nil) - height := config.DefaultParams.CRVotingStartHeight - 1 + height := config.DefaultParams.CRConfiguration.CRVotingStartHeight - 1 _, pk, _ := crypto.GenerateKeyPair() pkBuf, _ := pk.EncodePoint(true) @@ -1665,7 +1665,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { state.GetArbiters = func() []*state2.ArbiterInfo { result := make([]*state2.ArbiterInfo, 0) for i, p := range pds { - if i >= len(state.ChainParams.CRCArbiters)+state.ChainParams.GeneralArbiters { + if i >= len(state.ChainParams.DPoSConfiguration.CRCArbiters)+state.ChainParams.DPoSConfiguration.NormalArbitratorsCount { break } result = append(result, &state2.ArbiterInfo{ @@ -1678,8 +1678,8 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { // set the random DPOS node. pds[len(pds)-1].SetSelected(true) - config.DefaultParams.MaxInactiveRounds = 36 - config.DefaultParams.MaxInactiveRoundsOfRandomNode = 10 + config.DefaultParams.DPoSConfiguration.MaxInactiveRounds = 36 + config.DefaultParams.DPoSConfiguration.MaxInactiveRoundsOfRandomNode = 10 // random DPOS node does not work for 10 turns. for i := 0; i < 10*36; i++ { @@ -1688,7 +1688,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { if p.Selected() { nodePublcKey = pds[0].NodePublicKey() } - height := state.ChainParams.ChangeCommitteeNewCRHeight + 1 + uint32(i) + height := state.ChainParams.CRConfiguration.ChangeCommitteeNewCRHeight + 1 + uint32(i) state.CountArbitratorsInactivityV1( height, &payload.Confirm{ diff --git a/test/unit/heightversion_test.go b/test/unit/heightversion_test.go index 008c048ed..1adeeefe9 100644 --- a/test/unit/heightversion_test.go +++ b/test/unit/heightversion_test.go @@ -12,6 +12,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract/program" transaction2 "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" @@ -35,7 +36,7 @@ func init() { } func TestHeightVersionInit(t *testing.T) { - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() arbitratorsStr := []string{ "023a133480176214f88848c6eaa684a54b316849df2b8570b57f3a917f19bbc77a", "030a26f8b4ab0ea219eb461d1e454ce5f0bd0d289a6a64ffc0743dab7bd5be0be9", @@ -51,7 +52,7 @@ func TestHeightVersionInit(t *testing.T) { } activeNetParams := &config.DefaultParams - activeNetParams.CRCArbiters = []string{ + activeNetParams.DPoSConfiguration.CRCArbiters = []string{ "023a133480176214f88848c6eaa684a54b316849df2b8570b57f3a917f19bbc77a", "030a26f8b4ab0ea219eb461d1e454ce5f0bd0d289a6a64ffc0743dab7bd5be0be9", "0288e79636e41edce04d4fa95d8f62fed73a76164f8631ccc42f5425f960e4a0c7", @@ -60,15 +61,16 @@ func TestHeightVersionInit(t *testing.T) { } var err error bestHeight = 0 - + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) arbiters, err = state.NewArbitrators(activeNetParams, nil, nil, nil, nil, - nil, nil, nil, nil) + nil, nil, nil, nil, + ckpManager) assert.NoError(t, err) arbiters.RegisterFunction(func() uint32 { return bestHeight }, func() *common.Uint256 { return &common.Uint256{} }, nil, nil) - arbiters.State = state.NewState(activeNetParams, nil, nil,nil, + arbiters.State = state.NewState(activeNetParams, nil, nil, nil, func() bool { return false }, nil, nil, nil, nil, nil, nil, nil) @@ -77,7 +79,7 @@ func TestHeightVersionInit(t *testing.T) { func TestArbitrators_GetNormalArbitratorsDescV0(t *testing.T) { arbitrators := make([][]byte, 0) - for _, v := range config.DefaultParams.OriginArbiters { + for _, v := range config.DefaultParams.DPoSConfiguration.OriginArbiters { a, _ := common.HexStringToBytes(v) arbitrators = append(arbitrators, a) } @@ -187,43 +189,43 @@ func TestArbitrators_GetNormalArbitratorsDesc(t *testing.T) { func TestArbitrators_GetNextOnDutyArbitratorV0(t *testing.T) { currentArbitrator := arbiters.GetNextOnDutyArbitratorV0(1, 0) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[0], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[0], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(2, 0) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[1], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[1], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(3, 0) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[2], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[2], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(4, 0) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[3], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[3], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(5, 0) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[4], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[4], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(0, 1) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[0], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[0], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(0, 2) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[1], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[1], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(0, 3) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[2], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[2], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(0, 4) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[3], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[3], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) currentArbitrator = arbiters.GetNextOnDutyArbitratorV0(0, 5) - assert.Equal(t, arbiters.State.ChainParams.OriginArbiters[4], + assert.Equal(t, arbiters.State.ChainParams.DPoSConfiguration.OriginArbiters[4], common.BytesToHexString(currentArbitrator.GetNodePublicKey())) } @@ -234,7 +236,7 @@ func TestArbitrators_GetNextOnDutyArbitrator(t *testing.T) { arbiters.ChangeCurrentArbitrators(bestHeight + 1) arbiters.History.Commit(bestHeight + 1) - sortedArbiters := arbiters.State.ChainParams.CRCArbiters + sortedArbiters := arbiters.State.ChainParams.DPoSConfiguration.CRCArbiters sort.Slice(sortedArbiters, func(i, j int) bool { return sortedArbiters[i] < sortedArbiters[j] }) diff --git a/test/unit/returndepositindex_test.go b/test/unit/returndepositindex_test.go index fac762135..161a633c2 100644 --- a/test/unit/returndepositindex_test.go +++ b/test/unit/returndepositindex_test.go @@ -30,7 +30,7 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } var ( diff --git a/test/unit/reward_test.go b/test/unit/reward_test.go index 3053bbb1c..015dcb54c 100644 --- a/test/unit/reward_test.go +++ b/test/unit/reward_test.go @@ -12,6 +12,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" @@ -54,17 +55,18 @@ func TestCommittee_ChangeCommitteeReward(t *testing.T) { registerCRTxn3 := getRegisterCRTx(publicKeyStr3, privateKeyStr3, nickName3) // set count of CR member - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() cfg := &config.DefaultParams - cfg.CRCArbiters = cfg.CRCArbiters[0:2] - cfg.CRMemberCount = 2 - cfg.GeneralArbiters = 24 + cfg.DPoSConfiguration.CRCArbiters = cfg.DPoSConfiguration.CRCArbiters[0:2] + cfg.CRConfiguration.MemberCount = 2 + cfg.DPoSConfiguration.NormalArbitratorsCount = 24 + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) // new committee - committee := state.NewCommittee(&config.DefaultParams) + committee := state.NewCommittee(&config.DefaultParams, ckpManager) // avoid getting UTXOs from database - currentHeight := cfg.CRVotingStartHeight + currentHeight := cfg.CRConfiguration.CRVotingStartHeight // register cr committee.ProcessBlock(&types.Block{ @@ -104,18 +106,18 @@ func TestCommittee_ChangeCommitteeReward(t *testing.T) { assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*did1).Votes) // end first voting period - currentHeight = cfg.CRCommitteeStartHeight + currentHeight = cfg.CRConfiguration.CRCommitteeStartHeight committee.ProcessBlock(&types.Block{ Header: common2.Header{Height: currentHeight}}, nil) assert.Equal(t, 2, len(committee.GetCurrentMembers())) - var bestHeight uint32 arbitrators, _ := state2.NewArbitrators(&config.DefaultParams, - committee, nil, nil, nil, nil, nil, nil, nil) + committee, nil, nil, nil, nil, + nil, nil, nil, ckpManager) arbitrators.RegisterFunction(func() uint32 { return bestHeight }, func() *common.Uint256 { return &common.Uint256{} }, nil, nil) - arbitrators.ChainParams.NoCRCDPOSNodeHeight = 2000000 + arbitrators.ChainParams.DPoSConfiguration.NoCRCDPOSNodeHeight = 2000000 // Create 200 producers info. producers := make([]*payload.ProducerInfo, 200) @@ -163,7 +165,7 @@ func TestCommittee_ChangeCommitteeReward(t *testing.T) { } arbitrators.ProcessBlock(mockBlock(arbitrators.ChainParams.PublicDPOSHeight- - arbitrators.ChainParams.PreConnectOffset-1), nil) + arbitrators.ChainParams.DPoSConfiguration.PreConnectOffset-1), nil) arbitrators.ProcessBlock(mockBlock(arbitrators.ChainParams.PublicDPOSHeight-1), nil) arbitrators.DutyIndex = 25 diff --git a/test/unit/server_test.go b/test/unit/server_test.go index 66a955841..71e433f9e 100644 --- a/test/unit/server_test.go +++ b/test/unit/server_test.go @@ -24,7 +24,7 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } // iPeer fakes a server.IPeer for test. diff --git a/test/unit/state_test.go b/test/unit/state_test.go index 214fb3ff5..c7f267da0 100644 --- a/test/unit/state_test.go +++ b/test/unit/state_test.go @@ -10,6 +10,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" @@ -32,7 +33,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func TestState_GetCandidatesRelated(t *testing.T) { @@ -86,9 +87,10 @@ func TestState_ExistCandidateRelated(t *testing.T) { func TestState_ProcessBlock_PendingUpdateThenCancel(t *testing.T) { cfg := &config.DefaultParams - cfg.CRVotingStartHeight = 0 + cfg.CRConfiguration.CRVotingStartHeight = 0 currentHeight := uint32(1) - committee := state2.NewCommittee(cfg) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state2.NewCommittee(cfg, ckpManager) committee.RegisterFuncitons(&state2.CommitteeFuncsConfig{ GetHeight: func() uint32 { return currentHeight @@ -163,9 +165,10 @@ func TestState_ProcessBlock_PendingUpdateThenCancel(t *testing.T) { func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { cfg := &config.DefaultParams - cfg.CRVotingStartHeight = 0 + cfg.CRConfiguration.CRVotingStartHeight = 0 currentHeight := uint32(1) - committee := state2.NewCommittee(cfg) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state2.NewCommittee(cfg, ckpManager) committee.RegisterFuncitons(&state2.CommitteeFuncsConfig{ GetHeight: func() uint32 { return currentHeight @@ -253,9 +256,10 @@ func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { func TestState_ProcessBlock_MixedCRProcessing(t *testing.T) { cfg := &config.DefaultParams - cfg.CRVotingStartHeight = 0 + cfg.CRConfiguration.CRVotingStartHeight = 0 currentHeight := uint32(1) - committee := state2.NewCommittee(cfg) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state2.NewCommittee(cfg, ckpManager) committee.GetState().StateKeyFrame = *randomStateKeyFrame(5, true) committee.RegisterFuncitons(&state2.CommitteeFuncsConfig{ GetHeight: func() uint32 { @@ -312,10 +316,11 @@ func TestState_ProcessBlock_MixedCRProcessing(t *testing.T) { func TestState_ProcessBlock_VotingAndCancel(t *testing.T) { cfg := &config.DefaultParams - cfg.CRVotingStartHeight = 0 + cfg.CRConfiguration.CRVotingStartHeight = 0 currentHeight := uint32(1) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) keyframe := randomStateKeyFrame(5, true) - committee := state2.NewCommittee(cfg) + committee := state2.NewCommittee(cfg, ckpManager) committee.GetState().StateKeyFrame = *keyframe committee.RegisterFuncitons(&state2.CommitteeFuncsConfig{ GetHeight: func() uint32 { @@ -390,9 +395,10 @@ func TestState_ProcessBlock_VotingAndCancel(t *testing.T) { func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { cfg := &config.DefaultParams - cfg.CRVotingStartHeight = 0 + cfg.CRConfiguration.CRVotingStartHeight = 0 currentHeight := uint32(1) - committee := state2.NewCommittee(cfg) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + committee := state2.NewCommittee(cfg, ckpManager) committee.RegisterFuncitons(&state2.CommitteeFuncsConfig{ GetHeight: func() uint32 { return currentHeight @@ -507,7 +513,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { assert.Equal(t, state2.Canceled, candidate.State) // reached the Height to return deposit amount. - currentHeight = cancelHeight + committee.Params.CRDepositLockupBlocks + currentHeight = cancelHeight + committee.Params.CRConfiguration.DepositLockupBlocks committee.ProcessBlock(&types.Block{ Header: common2.Header{ Height: currentHeight, diff --git a/test/unit/transaction_test.go b/test/unit/transaction_test.go index 4378ff61c..07f21687e 100644 --- a/test/unit/transaction_test.go +++ b/test/unit/transaction_test.go @@ -31,7 +31,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } type transactionSuite struct { diff --git a/test/unit/txvalidator_specailtx_test.go b/test/unit/txvalidator_specailtx_test.go index 3c47f80e1..87061cf01 100644 --- a/test/unit/txvalidator_specailtx_test.go +++ b/test/unit/txvalidator_specailtx_test.go @@ -15,6 +15,7 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" @@ -33,7 +34,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } type txValidatorSpecialTxTestSuite struct { @@ -92,10 +93,12 @@ func (s *txValidatorSpecialTxTestSuite) SetupSuite() { if err != nil { s.Error(err) } + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) s.Chain, err = blockchain.New(chainStore, &config.DefaultParams, state.NewState(&config.DefaultParams, nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil, nil), nil) + nil, nil, nil, + nil, nil), nil, ckpManager) if err != nil { s.Error(err) } diff --git a/test/unit/txvalidator_test.go b/test/unit/txvalidator_test.go index fb005934b..3885dee26 100644 --- a/test/unit/txvalidator_test.go +++ b/test/unit/txvalidator_test.go @@ -25,6 +25,8 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core" + "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" @@ -62,7 +64,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } func (s *txValidatorTestSuite) SetupSuite() { @@ -70,19 +72,22 @@ func (s *txValidatorTestSuite) SetupSuite() { params := &config.DefaultParams params.DPoSV2StartHeight = 0 - blockchain.FoundationAddress = params.Foundation - s.foundationAddress = params.Foundation + FoundationAddress, _ := common.Uint168FromAddress(params.FoundationAddress) + blockchain.FoundationAddress = *FoundationAddress + s.foundationAddress = *FoundationAddress chainStore, err := blockchain.NewChainStore(filepath.Join(test.DataPath, "txvalidator"), params) if err != nil { s.Error(err) } + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) s.Chain, err = blockchain.New(chainStore, params, state.NewState(params, nil, nil, nil, func() bool { return false }, nil, nil, nil, nil, nil, nil, nil), - crstate.NewCommittee(params)) + crstate.NewCommittee(params, ckpManager), ckpManager, + ) if err != nil { s.Error(err) } @@ -100,7 +105,8 @@ func (s *txValidatorTestSuite) SetupSuite() { arbiters, err := state.NewArbitrators(params, nil, nil, nil, - nil, nil, nil, nil, nil) + nil, nil, nil, + nil, nil, ckpManager) if err != nil { s.Fail("initialize arbitrator failed") } @@ -120,9 +126,9 @@ func (s *txValidatorTestSuite) TearDownSuite() { func (s *txValidatorTestSuite) TestCheckTxHeightVersion() { // set blockHeight1 less than CRVotingStartHeight and set blockHeight2 // to CRVotingStartHeight. - blockHeight1 := s.Chain.GetParams().CRVotingStartHeight - 1 - blockHeight2 := s.Chain.GetParams().CRVotingStartHeight - blockHeight3 := s.Chain.GetParams().RegisterCRByDIDHeight + blockHeight1 := s.Chain.GetParams().CRConfiguration.CRVotingStartHeight - 1 + blockHeight2 := s.Chain.GetParams().CRConfiguration.CRVotingStartHeight + blockHeight3 := s.Chain.GetParams().CRConfiguration.RegisterCRByDIDHeight blockHeight4 := s.Chain.GetParams().DPoSV2StartHeight stake, _ := functions.GetTransactionByTxType(common2.ExchangeVotes) @@ -431,16 +437,17 @@ func (s *txValidatorTestSuite) TestCheckTransactionInput() { func (s *txValidatorTestSuite) TestCheckTransactionOutput() { // coinbase tx := newCoinBaseTransaction(new(payload.CoinBase), 0) + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) tx.SetOutputs([]*common2.Output{ - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress}, - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress}, }) err := s.Chain.CheckTransactionOutput(tx, s.HeightVersion1) s.NoError(err) // outputs < 2 tx.SetOutputs([]*common2.Output{ - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress}, }) err = s.Chain.CheckTransactionOutput(tx, s.HeightVersion1) s.EqualError(err, "coinbase output is not enough, at least 2") @@ -454,13 +461,13 @@ func (s *txValidatorTestSuite) TestCheckTransactionOutput() { s.EqualError(err, "asset ID in coinbase is invalid") // reward to foundation in coinbase = 30% (CheckTxOut version) - totalReward := config.DefaultParams.RewardPerBlock + totalReward := config.DefaultParams.PowConfiguration.RewardPerBlock fmt.Printf("Block reward amount %s", totalReward.String()) foundationReward := common.Fixed64(float64(totalReward) * 0.3) fmt.Printf("Foundation reward amount %s", foundationReward.String()) tx.SetOutputs([]*common2.Output{ - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress, Value: foundationReward}, - {AssetID: config.ELAAssetID, ProgramHash: common.Uint168{}, Value: totalReward - foundationReward}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress, Value: foundationReward}, + {AssetID: *ELAAssetID, ProgramHash: common.Uint168{}, Value: totalReward - foundationReward}, }) err = s.Chain.CheckTransactionOutput(tx, s.HeightVersion1) s.NoError(err) @@ -469,8 +476,8 @@ func (s *txValidatorTestSuite) TestCheckTransactionOutput() { foundationReward = common.Fixed64(float64(totalReward) * 0.299999) fmt.Printf("Foundation reward amount %s", foundationReward.String()) tx.SetOutputs([]*common2.Output{ - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress, Value: foundationReward}, - {AssetID: config.ELAAssetID, ProgramHash: common.Uint168{}, Value: totalReward - foundationReward}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress, Value: foundationReward}, + {AssetID: *ELAAssetID, ProgramHash: common.Uint168{}, Value: totalReward - foundationReward}, }) err = s.Chain.CheckTransactionOutput(tx, s.HeightVersion1) s.EqualError(err, "reward to foundation in coinbase < 30%") @@ -478,7 +485,7 @@ func (s *txValidatorTestSuite) TestCheckTransactionOutput() { // normal transaction tx = buildTx() for _, output := range tx.Outputs() { - output.AssetID = config.ELAAssetID + output.AssetID = *ELAAssetID output.ProgramHash = common.Uint168{} } err = s.Chain.CheckTransactionOutput(tx, s.HeightVersion1) @@ -506,7 +513,7 @@ func (s *txValidatorTestSuite) TestCheckTransactionOutput() { appendSpecial := func() []*common2.Output { return append(tx.Outputs(), &common2.Output{ Type: common2.OTVote, - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: address, Value: common.Fixed64(mrand.Int63()), OutputLock: mrand.Uint32(), @@ -528,7 +535,7 @@ func (s *txValidatorTestSuite) TestCheckTransactionOutput() { tx.SetVersion(common2.TxVersionDefault) tx.SetOutputs(randomOutputs()) for _, output := range tx.Outputs() { - output.AssetID = config.ELAAssetID + output.AssetID = *ELAAssetID address := common.Uint168{} address[0] = 0x23 output.ProgramHash = address @@ -739,6 +746,7 @@ func (s *txValidatorTestSuite) TestCheckDuplicateSidechainTx() { func (s *txValidatorTestSuite) TestCheckTransactionBalance() { // WithdrawFromSideChain will pass check in any condition + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) tx := functions.CreateTransaction( 0, common2.WithdrawFromSideChain, @@ -756,7 +764,7 @@ func (s *txValidatorTestSuite) TestCheckTransactionBalance() { outputValue1 := common.Fixed64(100 * s.ELA) deposit := newCoinBaseTransaction(new(payload.CoinBase), 0) deposit.SetOutputs([]*common2.Output{ - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress, Value: outputValue1}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress, Value: outputValue1}, }) references := map[*common2.Input]common2.Output{ @@ -778,8 +786,8 @@ func (s *txValidatorTestSuite) TestCheckTransactionBalance() { outputValue1 = common.Fixed64(30 * s.ELA) outputValue2 := common.Fixed64(70 * s.ELA) tx.SetOutputs([]*common2.Output{ - {AssetID: config.ELAAssetID, ProgramHash: s.foundationAddress, Value: outputValue1}, - {AssetID: config.ELAAssetID, ProgramHash: common.Uint168{}, Value: outputValue2}, + {AssetID: *ELAAssetID, ProgramHash: s.foundationAddress, Value: outputValue1}, + {AssetID: *ELAAssetID, ProgramHash: common.Uint168{}, Value: outputValue2}, }) references = map[*common2.Input]common2.Output{ @@ -922,7 +930,7 @@ func (s *txValidatorTestSuite) TestCheckRegisterProducerTransaction() { // check node public key same with CRC txn.Payload().(*payload.ProducerInfo).OwnerPublicKey = publicKey2 - pk, _ := common.HexStringToBytes(config.DefaultParams.CRCArbiters[0]) + pk, _ := common.HexStringToBytes(config.DefaultParams.DPoSConfiguration.CRCArbiters[0]) txn.Payload().(*payload.ProducerInfo).NodePublicKey = pk config.DefaultParams.PublicDPOSHeight = 0 err, _ = txn.SpecialContextCheck() @@ -931,7 +939,7 @@ func (s *txValidatorTestSuite) TestCheckRegisterProducerTransaction() { // check owner public key same with CRC txn.Payload().(*payload.ProducerInfo).NodePublicKey = publicKey2 - pk, _ = common.HexStringToBytes(config.DefaultParams.CRCArbiters[0]) + pk, _ = common.HexStringToBytes(config.DefaultParams.DPoSConfiguration.CRCArbiters[0]) txn.Payload().(*payload.ProducerInfo).OwnerPublicKey = pk config.DefaultParams.PublicDPOSHeight = 0 err, _ = txn.SpecialContextCheck() @@ -1111,11 +1119,13 @@ func (s *txValidatorTestSuite) TestCheckRegisterDposV2ProducerTransaction() { } func (s *txValidatorTestSuite) TestCheckStakeTransaction() { + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) publicKey := "03878cbe6abdafc702befd90e2329c4f37e7cb166410f0ecb70488c74c85b81d66" publicKeyBytes, _ := common.HexStringToBytes(publicKey) code := getCode(publicKeyBytes) c, _ := contract.CreateStakeContractByCode(code) stakeAddress_uint168 := c.ToProgramHash() + stakeAddress, _ := stakeAddress_uint168.ToAddress() rpPayload := &outputpayload.ExchangeVotesOutput{ Version: 0, StakeAddress: *stakeAddress_uint168, @@ -1210,7 +1220,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: -1, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -1235,7 +1245,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 100000000, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -1261,7 +1271,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 100000000, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -1288,7 +1298,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 100000000, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -1302,8 +1312,8 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { Parameter: nil, }}, ) - param := s.Chain.GetParams() - param.StakePool = common.Uint168{0x1, 0x2, 0x3} + param := *s.Chain.GetParams() + param.StakePool = "STAKE" tx := txn.(*transaction.ExchangeVotesTransaction) tx.DefaultChecker.SetParameters(&transaction.TransactionParameters{ BlockChain: s.Chain, @@ -1321,7 +1331,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 100000000, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -1335,12 +1345,12 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction() { Parameter: nil, }}, ) - param = s.Chain.GetParams() - param.StakePool = *stakeAddress_uint168 + param = *s.Chain.GetParams() + param.StakePool = stakeAddress tx = txn.(*transaction.ExchangeVotesTransaction) tx.DefaultChecker.SetParameters(&transaction.TransactionParameters{ BlockChain: s.Chain, - Config: s.Chain.GetParams(), + Config: ¶m, }) err = txn.CheckTransactionOutput() s.NoError(err) @@ -1862,7 +1872,8 @@ func (s *txValidatorTestSuite) TestCheckRegisterProducerTransaction2() { s.CurrentHeight = 1 params := s.Chain.GetParams() params.DPoSV2StartHeight = 0 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.SetState(state.NewState(s.Chain.GetParams(), nil, nil, nil, func() bool { return false }, func(programHash common.Uint168) (common.Fixed64, error) { @@ -2088,7 +2099,7 @@ func (s *txValidatorTestSuite) TestCheckRegisterProducerTransaction2() { Previous: common.Uint256{}, MerkleRoot: common.EmptyHash, Timestamp: uint32(time.Now().Unix()), - Bits: config.DefaultParams.PowLimitBits, + Bits: config.DefaultParams.PowConfiguration.PowLimitBits, Height: 1, Nonce: 1, } @@ -2173,7 +2184,8 @@ func (s *txValidatorTestSuite) TestCheckUpdateProducerTransaction() { ) s.CurrentHeight = 1 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.SetState(state.NewState(s.Chain.GetParams(), nil, nil, nil, func() bool { return false }, func(programHash common.Uint168) (common.Fixed64, error) { @@ -2234,7 +2246,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateProducerTransaction() { // check node public key same with CRC txn.Payload().(*payload.ProducerInfo).OwnerPublicKey = publicKey2 - pk, _ := common.HexStringToBytes(config.DefaultParams.CRCArbiters[0]) + pk, _ := common.HexStringToBytes(config.DefaultParams.DPoSConfiguration.CRCArbiters[0]) txn.Payload().(*payload.ProducerInfo).NodePublicKey = pk config.DefaultParams.PublicDPOSHeight = 0 err, _ = txn.SpecialContextCheck() @@ -2243,7 +2255,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateProducerTransaction() { // check owner public key same with CRC txn.Payload().(*payload.ProducerInfo).NodePublicKey = publicKey2 - pk, _ = common.HexStringToBytes(config.DefaultParams.CRCArbiters[0]) + pk, _ = common.HexStringToBytes(config.DefaultParams.DPoSConfiguration.CRCArbiters[0]) txn.Payload().(*payload.ProducerInfo).OwnerPublicKey = pk config.DefaultParams.PublicDPOSHeight = 0 err, _ = txn.SpecialContextCheck() @@ -2357,7 +2369,7 @@ func (s *txValidatorTestSuite) TestCheckActivateProducerTransaction() { } func (s *txValidatorTestSuite) TestCheckRegisterCRTransaction() { - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() // Generate a register CR transaction publicKeyStr1 := "03c77af162438d4b7140f8544ad6523b9734cca9c7a62476d54ed5d1bddc7a39c3" @@ -2381,8 +2393,8 @@ func (s *txValidatorTestSuite) TestCheckRegisterCRTransaction() { cid1 := getCID(code1) cid2 := getCID(code2) - votingHeight := config.DefaultParams.CRVotingStartHeight - registerCRByDIDHeight := config.DefaultParams.RegisterCRByDIDHeight + votingHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight + registerCRByDIDHeight := config.DefaultParams.CRConfiguration.RegisterCRByDIDHeight // All ok txn = CreateTransactionByType(txn, s.Chain) @@ -2420,7 +2432,7 @@ func (s *txValidatorTestSuite) TestCheckRegisterCRTransaction() { txn.Payload().(*payload.CRInfo).Url = url txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, - BlockHeight: config.DefaultParams.CRVotingStartHeight - 1, + BlockHeight: config.DefaultParams.CRConfiguration.CRVotingStartHeight - 1, TimeStamp: s.Chain.BestChain.Timestamp, Config: s.Chain.GetParams(), BlockChain: s.Chain, @@ -2432,7 +2444,7 @@ func (s *txValidatorTestSuite) TestCheckRegisterCRTransaction() { s.Chain.GetCRCommittee().InElectionPeriod = true txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, - BlockHeight: config.DefaultParams.CRCommitteeStartHeight + 1, + BlockHeight: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1, TimeStamp: s.Chain.BestChain.Timestamp, Config: s.Chain.GetParams(), BlockChain: s.Chain, @@ -3309,7 +3321,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalTrackingTransaction() { proposalHash := randomUint256() recipient := randomUint168() - votingHeight := config.DefaultParams.CRVotingStartHeight + votingHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // Set secretary general. s.Chain.GetCRCommittee().GetProposalManager().SecretaryGeneralPublicKey = publicKeyStr3 @@ -3629,8 +3641,10 @@ func (s *txValidatorTestSuite) getCRCProposalTrackingTx( func (s *txValidatorTestSuite) TestCheckCRCAppropriationTransaction() { // Set CR assets address and CR expenses address. - s.Chain.GetParams().CRAssetsAddress = *randomUint168() - s.Chain.GetParams().CRExpensesAddress = *randomUint168() + s.Chain.GetParams().CRConfiguration.CRAssetsAddress = "CRASSETSXXXXXXXXXXXXXXXXXXXX2qDX5J" + s.Chain.GetParams().CRConfiguration.CRExpensesAddress = "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" + CRAssetsAddress, _ := common.Uint168FromAddress(s.Chain.GetParams().CRConfiguration.CRAssetsAddress) + CRExpensesAddress, _ := common.Uint168FromAddress(s.Chain.GetParams().CRConfiguration.CRExpensesAddress) // Set CR assets and CRC committee amount. s.Chain.GetCRCommittee().CRCFoundationBalance = common.Fixed64(900 * 1e8) @@ -3647,7 +3661,7 @@ func (s *txValidatorTestSuite) TestCheckCRCAppropriationTransaction() { } refOutput := common2.Output{ Value: 900 * 1e8, - ProgramHash: s.Chain.GetParams().CRAssetsAddress, + ProgramHash: *CRAssetsAddress, } refOutputErr := common2.Output{ Value: 900 * 1e8, @@ -3658,19 +3672,19 @@ func (s *txValidatorTestSuite) TestCheckCRCAppropriationTransaction() { // Create CRC appropriation transaction. output1 := &common2.Output{ Value: 90 * 1e8, - ProgramHash: s.Chain.GetParams().CRExpensesAddress, + ProgramHash: *CRExpensesAddress, } output2 := &common2.Output{ Value: 810 * 1e8, - ProgramHash: s.Chain.GetParams().CRAssetsAddress, + ProgramHash: *CRAssetsAddress, } output1Err := &common2.Output{ Value: 91 * 1e8, - ProgramHash: s.Chain.GetParams().CRExpensesAddress, + ProgramHash: *CRExpensesAddress, } output2Err := &common2.Output{ Value: 809 * 1e8, - ProgramHash: s.Chain.GetParams().CRAssetsAddress, + ProgramHash: *CRAssetsAddress, } // Check correct transaction. @@ -3810,7 +3824,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateCRTransaction() { nickName2 := "nickname 2" nickName3 := "nickname 3" - votingHeight := config.DefaultParams.CRVotingStartHeight + votingHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight // //registe an cr to update registerCRTxn1 := s.getRegisterCRTx(publicKeyStr1, privateKeyStr1, @@ -3818,8 +3832,9 @@ func (s *txValidatorTestSuite) TestCheckUpdateCRTransaction() { registerCRTxn2 := s.getRegisterCRTx(publicKeyStr2, privateKeyStr2, nickName2, payload.CRInfoDIDVersion, &common.Uint168{}) - s.CurrentHeight = s.Chain.GetParams().CRVotingStartHeight + 1 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.CurrentHeight = s.Chain.GetParams().CRConfiguration.CRVotingStartHeight + 1 + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.GetCRCommittee().RegisterFuncitons(&crstate.CommitteeFuncsConfig{ GetTxReference: s.Chain.UTXOCache.GetTxReference, GetUTXO: s.Chain.GetDB().GetFFLDB().GetUTXO, @@ -3901,7 +3916,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateCRTransaction() { //not in vote Period lower txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, - BlockHeight: config.DefaultParams.CRVotingStartHeight - 1, + BlockHeight: config.DefaultParams.CRConfiguration.CRVotingStartHeight - 1, TimeStamp: s.Chain.BestChain.Timestamp, Config: s.Chain.GetParams(), BlockChain: s.Chain, @@ -3910,13 +3925,13 @@ func (s *txValidatorTestSuite) TestCheckUpdateCRTransaction() { s.EqualError(err, "transaction validate error: payload content invalid:should create tx during voting period") // set RegisterCRByDIDHeight after CRCommitteeStartHeight - s.Chain.GetParams().RegisterCRByDIDHeight = config.DefaultParams.CRCommitteeStartHeight + 10 + s.Chain.GetParams().CRConfiguration.RegisterCRByDIDHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 10 //not in vote Period lower upper c.params.CRCommitteeStartHeight s.Chain.GetCRCommittee().InElectionPeriod = true txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, - BlockHeight: config.DefaultParams.CRCommitteeStartHeight + 1, + BlockHeight: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1, TimeStamp: s.Chain.BestChain.Timestamp, Config: s.Chain.GetParams(), BlockChain: s.Chain, @@ -3955,7 +3970,8 @@ func (s *txValidatorTestSuite) TestCheckUpdateCRTransaction() { func (s *txValidatorTestSuite) TestCheckCRCProposalRealWithdrawTransaction() { // Set CR expenses address. - s.Chain.GetParams().CRExpensesAddress = *randomUint168() + s.Chain.GetParams().CRConfiguration.CRExpensesAddress = "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" + CRExpensesAddress, _ := common.Uint168FromAddress(s.Chain.GetParams().CRConfiguration.CRExpensesAddress) // Set WithdrawableTxInfo withdrawTransactionHash1 := *randomUint256() @@ -3983,7 +3999,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalRealWithdrawTransaction() { } refOutput := common2.Output{ Value: 20 * 1e8, - ProgramHash: s.Chain.GetParams().CRExpensesAddress, + ProgramHash: *CRExpensesAddress, } reference[input] = refOutput @@ -3998,7 +4014,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalRealWithdrawTransaction() { } output3 := &common2.Output{ Value: 1 * 1e8, - ProgramHash: s.Chain.GetParams().CRExpensesAddress, + ProgramHash: *CRExpensesAddress, } output1Err := &common2.Output{ Value: 10 * 1e8, @@ -4071,14 +4087,15 @@ func (s *txValidatorTestSuite) TestCheckUnregisterCRTransaction() { publicKeyStr2 := "036db5984e709d2e0ec62fd974283e9a18e7b87e8403cc784baf1f61f775926535" privateKeyStr2 := "b2c25e877c8a87d54e8a20a902d27c7f24ed52810813ba175ca4e8d3036d130e" - votingHeight := config.DefaultParams.CRVotingStartHeight + votingHeight := config.DefaultParams.CRConfiguration.CRVotingStartHeight nickName1 := "nickname 1" //register a cr to unregister registerCRTxn := s.getRegisterCRTx(publicKeyStr1, privateKeyStr1, nickName1, payload.CRInfoVersion, &common.Uint168{}) s.CurrentHeight = 1 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.GetCRCommittee().RegisterFuncitons(&crstate.CommitteeFuncsConfig{ GetTxReference: s.Chain.UTXOCache.GetTxReference, GetUTXO: s.Chain.GetDB().GetFFLDB().GetUTXO, @@ -4122,7 +4139,7 @@ func (s *txValidatorTestSuite) TestCheckUnregisterCRTransaction() { //not in vote Period lower err = txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, - BlockHeight: config.DefaultParams.CRVotingStartHeight - 1, + BlockHeight: config.DefaultParams.CRConfiguration.CRVotingStartHeight - 1, TimeStamp: s.Chain.BestChain.Timestamp, Config: s.Chain.GetParams(), BlockChain: s.Chain, @@ -4135,7 +4152,7 @@ func (s *txValidatorTestSuite) TestCheckUnregisterCRTransaction() { config.DefaultParams.DPoSV2StartHeight = 2000000 err = txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, - BlockHeight: config.DefaultParams.CRCommitteeStartHeight + 1, + BlockHeight: config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1, TimeStamp: s.Chain.BestChain.Timestamp, Config: s.Chain.GetParams(), BlockChain: s.Chain, @@ -4212,7 +4229,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalReviewTransaction() { privateKeyStr1 := "15e0947580575a9b6729570bed6360a890f84a07dc837922fe92275feec837d4" publicKeyStr2 := "036db5984e709d2e0ec62fd974283e9a18e7b87e8403cc784baf1f61f775926535" privateKeyStr2 := "b2c25e877c8a87d54e8a20a902d27c7f24ed52810813ba175ca4e8d3036d130e" - tenureHeight := config.DefaultParams.CRCommitteeStartHeight + tenureHeight := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight nickName1 := "nickname 1" fmt.Println("getcode ", getCodeHexStr("02e23f70b9b967af35571c32b1442d787c180753bbed5cd6e7d5a5cfe75c7fc1ff")) @@ -4306,7 +4323,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalReviewTransaction() { func (s *txValidatorTestSuite) getCRCProposalWithdrawTx(crPublicKeyStr, crPrivateKeyStr string, recipient, commitee *common.Uint168, recipAmout, commiteAmout common.Fixed64, payloadVersion byte) interfaces.Transaction { - + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) privateKey1, _ := common.HexStringToBytes(crPrivateKeyStr) pkBytes, _ := common.HexStringToBytes(crPublicKeyStr) @@ -4354,12 +4371,12 @@ func (s *txValidatorTestSuite) getCRCProposalWithdrawTx(crPublicKeyStr, }) txn.SetOutputs([]*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *recipient, Value: recipAmout, }, { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *commitee, Value: commiteAmout, }, @@ -4377,10 +4394,11 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalWithdrawTransaction() { publicKeyStr1 := "02f981e4dae4983a5d284d01609ad735e3242c5672bb2c7bb0018cc36f9ab0c4a5" privateKeyStr1 := "15e0947580575a9b6729570bed6360a890f84a07dc837922fe92275feec837d4" RecipientAddress := "ERyUmNH51roR9qfru37Kqkaok2NghR7L5U" - CRExpensesAddress := "8VYXVxKKSAxkmRrfmGpQR2Kc66XhG6m3ta" + CRExpensesAddress := "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" NOCRExpensesAddress := "EWm2ZGeSyDBBAsVSsvSvspPKV4wQBKPjUk" + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) Recipient, _ := common.Uint168FromAddress(RecipientAddress) - tenureHeight := config.DefaultParams.CRCommitteeStartHeight + tenureHeight := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight pk1Bytes, _ := common.HexStringToBytes(publicKeyStr1) ela := common.Fixed64(100000000) CRExpensesAddressU168, _ := common.Uint168FromAddress(CRExpensesAddress) @@ -4397,12 +4415,12 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalWithdrawTransaction() { } outputs := []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *CRExpensesAddressU168, Value: common.Fixed64(60 * ela), }, { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *NOCRExpensesAddressU168, Value: common.Fixed64(600 * ela), }, @@ -4411,7 +4429,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalWithdrawTransaction() { references := make(map[*common2.Input]common2.Output) references[inputs[0]] = *outputs[0] - s.Chain.GetParams().CRExpensesAddress = *CRExpensesAddressU168 + s.Chain.GetParams().CRConfiguration.CRExpensesAddress = "CREXPENSESXXXXXXXXXXXXXXXXXX4UdT6b" // stage = 1 ok txn := s.getCRCProposalWithdrawTx(publicKeyStr1, privateKeyStr1, Recipient, CRExpensesAddressU168, 9*ela, 50*ela, 0) @@ -4532,7 +4550,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalWithdrawTransaction() { } outputs = []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *CRExpensesAddressU168, Value: common.Fixed64(61 * ela), }, @@ -4552,7 +4570,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalWithdrawTransaction() { s.EqualError(err, "transaction validate error: payload content invalid:withdrawPayload.Amount != withdrawAmount ") outputs = []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *CRExpensesAddressU168, Value: common.Fixed64(61 * ela), }, @@ -4698,7 +4716,7 @@ func (s *txValidatorTestSuite) TestCheckSecretaryGeneralProposalTransaction() { secretaryPublicKeyStr := "031e12374bae471aa09ad479f66c2306f4bcc4ca5b754609a82a1839b94b4721b9" secretaryPrivateKeyStr := "94396a69462208b8fd96d83842855b867d3b0e663203cb31d0dfaec0362ec034" - tenureHeight := config.DefaultParams.CRCommitteeStartHeight + 1 + tenureHeight := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1 ownerNickName := "nickname owner" crNickName := "nickname cr" @@ -4766,9 +4784,9 @@ func (s *txValidatorTestSuite) TestCheckSecretaryGeneralProposalTransaction() { //ChangeSecretaryGeneralProposal tx must InElectionPeriod and not during voting period config.DefaultParams.DPoSV2StartHeight = 2000000 - s.Chain.GetCRCommittee().LastCommitteeHeight = config.DefaultParams.CRCommitteeStartHeight - tenureHeight = config.DefaultParams.CRCommitteeStartHeight + config.DefaultParams.CRDutyPeriod - - config.DefaultParams.CRVotingPeriod + 1 + s.Chain.GetCRCommittee().LastCommitteeHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + tenureHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + config.DefaultParams.CRConfiguration.DutyPeriod - + config.DefaultParams.CRConfiguration.VotingPeriod + 1 txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, BlockHeight: tenureHeight, @@ -4788,7 +4806,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalRegisterSideChainTransaction( publicKeyStr2 := "036db5984e709d2e0ec62fd974283e9a18e7b87e8403cc784baf1f61f775926535" privateKeyStr2 := "b2c25e877c8a87d54e8a20a902d27c7f24ed52810813ba175ca4e8d3036d130e" - tenureHeight := config.DefaultParams.CRCommitteeStartHeight + 1 + tenureHeight := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1 nickName1 := "nickname 1" member1 := s.getCRMember(publicKeyStr1, privateKeyStr1, nickName1) @@ -4864,7 +4882,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalTransaction() { publicKeyStr2 := "036db5984e709d2e0ec62fd974283e9a18e7b87e8403cc784baf1f61f775926535" privateKeyStr2 := "b2c25e877c8a87d54e8a20a902d27c7f24ed52810813ba175ca4e8d3036d130e" - tenureHeight := config.DefaultParams.CRCommitteeStartHeight + 1 + tenureHeight := config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1 nickName1 := "nickname 1" nickName2 := "nickname 2" @@ -4899,8 +4917,8 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalTransaction() { // register cr proposal in voting period member1.MemberState = crstate.MemberElected - tenureHeight = config.DefaultParams.CRCommitteeStartHeight + - config.DefaultParams.CRDutyPeriod - config.DefaultParams.CRVotingPeriod + tenureHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + + config.DefaultParams.CRConfiguration.DutyPeriod - config.DefaultParams.CRConfiguration.VotingPeriod s.Chain.GetCRCommittee().InElectionPeriod = false txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, @@ -4915,7 +4933,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalTransaction() { // recipient is empty s.Chain.GetCRCommittee().InElectionPeriod = true - tenureHeight = config.DefaultParams.CRCommitteeStartHeight + 1 + tenureHeight = config.DefaultParams.CRConfiguration.CRCommitteeStartHeight + 1 txn.Payload().(*payload.CRCProposal).Recipient = common.Uint168{} txn.SetParameters(&transaction.TransactionParameters{ Transaction: txn, @@ -5162,7 +5180,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalTransaction() { txn = s.getCRCProposalTx(publicKeyStr2, privateKeyStr2, publicKeyStr1, privateKeyStr1) crcProposal, _ := txn.Payload().(*payload.CRCProposal) proposalHashSet := crstate.NewProposalHashSet() - for i := 0; i < int(s.Chain.GetParams().MaxCommitteeProposalCount); i++ { + for i := 0; i < int(s.Chain.GetParams().CRConfiguration.MaxCommitteeProposalCount); i++ { proposalHashSet.Add(*randomUint256()) } s.Chain.GetCRCommittee().GetProposalManager().ProposalHashes[crcProposal. @@ -5179,7 +5197,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalTransaction() { err, _ = txn.SpecialContextCheck() s.EqualError(err, "transaction validate error: payload content invalid:proposal is full") - s.Chain.GetParams().MaxCommitteeProposalCount = s.Chain.GetParams().MaxCommitteeProposalCount + 100 + s.Chain.GetParams().CRConfiguration.MaxCommitteeProposalCount = s.Chain.GetParams().CRConfiguration.MaxCommitteeProposalCount + 100 // invalid reserved custom id txn = s.getCRCReservedCustomIDProposalTx(publicKeyStr2, privateKeyStr2, publicKeyStr1, privateKeyStr1) proposal, _ = txn.Payload().(*payload.CRCProposal) @@ -5253,7 +5271,8 @@ func (s *txValidatorTestSuite) TestCheckTransactionDepositUTXO() { func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { s.CurrentHeight = 1 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.GetCRCommittee().RegisterFuncitons(&crstate.CommitteeFuncsConfig{ GetTxReference: s.Chain.UTXOCache.GetTxReference, GetUTXO: s.Chain.GetDB().GetFFLDB().GetUTXO, @@ -5379,7 +5398,7 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { err, _ = rdTx.SpecialContextCheck() s.EqualError(err, "transaction validate error: payload content invalid:overspend deposit") - s.CurrentHeight += s.Chain.GetParams().CRDepositLockupBlocks + s.CurrentHeight += s.Chain.GetParams().CRConfiguration.DepositLockupBlocks s.Chain.GetState().ProcessBlock(&types.Block{ Header: common2.Header{ Height: s.CurrentHeight, @@ -5399,13 +5418,15 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { } func (s *txValidatorTestSuite) TestCheckStakeTransaction2() { + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) s.CurrentHeight = 1 _, pk, _ := crypto.GenerateKeyPair() //publicKey, _ := pk.EncodePoint(true) cont, _ := contract.CreateStandardContract(pk) code := cont.Code ct, _ := contract.CreateStakeContractByCode(code) - stakeAddress := ct.ToProgramHash() + stakeHash := ct.ToProgramHash() + stakeAddress, _ := stakeHash.ToAddress() ps := &payload.ExchangeVotes{} attribute := []*common2.Attribute{} @@ -5422,7 +5443,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction2() { ) tx1.SetOutputs([]*common2.Output{ &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 2000, ProgramHash: blockchain.FoundationAddress, }, @@ -5436,15 +5457,15 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction2() { } outputs := []*common2.Output{ { - AssetID: config.ELAAssetID, - ProgramHash: *stakeAddress, + AssetID: *ELAAssetID, + ProgramHash: *stakeHash, Type: common2.OTStake, Value: common.Fixed64(1000 * 1e8), Payload: &outputpayload.ExchangeVotesOutput{ - StakeAddress: *stakeAddress, + StakeAddress: *stakeHash, }, }, { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *cont.ToProgramHash(), Type: common2.OTNone, Value: common.Fixed64(1000 * 1e8), @@ -5468,7 +5489,7 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction2() { bc := s.Chain config := bc.GetParams() - config.StakePool = *stakeAddress + config.StakePool = stakeAddress tx := txn.(*transaction.ExchangeVotesTransaction) tx.DefaultChecker.SetParameters(&transaction.TransactionParameters{ BlockChain: bc, @@ -5481,13 +5502,14 @@ func (s *txValidatorTestSuite) TestCheckStakeTransaction2() { } func (s *txValidatorTestSuite) TestCheckReutrnVotesTransaction() { + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) s.CurrentHeight = 1 _, pk, _ := crypto.GenerateKeyPair() //publicKey, _ := pk.EncodePoint(true) cont, _ := contract.CreateStandardContract(pk) code := cont.Code - ct, _ := contract.CreateStakeContractByCode(code) - stakeAddress := ct.ToProgramHash() + //ct, _ := contract.CreateStakeContractByCode(code) + //stakeAddress := ct.ToProgramHash() pl := &payload.ReturnVotes{ Value: 100, } @@ -5506,7 +5528,7 @@ func (s *txValidatorTestSuite) TestCheckReutrnVotesTransaction() { ) tx1.SetOutputs([]*common2.Output{ &common2.Output{ - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 1000, ProgramHash: blockchain.FoundationAddress, }, @@ -5520,7 +5542,7 @@ func (s *txValidatorTestSuite) TestCheckReutrnVotesTransaction() { } outputs := []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, ProgramHash: *cont.ToProgramHash(), Type: common2.OTNone, Value: common.Fixed64(1000 * 1e8), @@ -5544,7 +5566,7 @@ func (s *txValidatorTestSuite) TestCheckReutrnVotesTransaction() { bc := s.Chain config := bc.GetParams() - config.StakePool = *stakeAddress + config.StakePool = "STAKEREWARDXXXXXXXXXXXXXXXXXFD5SHU" tx := txn.(*transaction.ReturnVotesTransaction) tx.DefaultChecker.SetParameters(&transaction.TransactionParameters{ BlockChain: bc, @@ -5566,6 +5588,7 @@ func (s *txValidatorTestSuite) TestCheckReutrnVotesTransaction() { func (s *txValidatorTestSuite) TestCheckReturnVotesTransaction2() { private := "97751342c819562a8d65059d759494fc9b2b565232bef047d1eae93f7c97baed" publicKey := "0228329FD319A5444F2265D08482B8C09360AE59945C50FA5211548C0C11D31F08" + ELAAssetID, _ := common.Uint256FromHexString(core.ELAAssetID) publicKeyBytes, _ := common.HexStringToBytes(publicKey) code := getCode(publicKeyBytes) c, _ := contract.CreateStakeContractByCode(code) @@ -5633,7 +5656,7 @@ func (s *txValidatorTestSuite) TestCheckReturnVotesTransaction2() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: -1, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -5666,7 +5689,7 @@ func (s *txValidatorTestSuite) TestCheckReturnVotesTransaction2() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 1, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -5698,7 +5721,7 @@ func (s *txValidatorTestSuite) TestCheckReturnVotesTransaction2() { []*common2.Input{}, []*common2.Output{ { - AssetID: config.ELAAssetID, + AssetID: *ELAAssetID, Value: 1, OutputLock: 0, ProgramHash: *stakeAddress_uint168, @@ -5772,9 +5795,10 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { ct, _ := contract.CreateCRIDContractByCode(code) cid := ct.ToProgramHash() - s.Chain.GetParams().CRVotingStartHeight = uint32(1) - s.Chain.GetParams().CRCommitteeStartHeight = uint32(3000) - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.GetParams().CRConfiguration.CRVotingStartHeight = uint32(1) + s.Chain.GetParams().CRConfiguration.CRCommitteeStartHeight = uint32(3000) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.GetCRCommittee().RegisterFuncitons(&crstate.CommitteeFuncsConfig{ GetTxReference: s.Chain.UTXOCache.GetTxReference, GetUTXO: s.Chain.GetDB().GetFFLDB().GetUTXO, @@ -5907,7 +5931,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { // check a correct return cr deposit coin transaction. rdTx.Outputs()[0].Value = 4999 * 100000000 rdTx.Programs()[0].Code = code - s.CurrentHeight = s.Chain.GetParams().CRCommitteeStartHeight + s.CurrentHeight = s.Chain.GetParams().CRConfiguration.CRCommitteeStartHeight err, _ = rdTx.SpecialContextCheck() s.NoError(err) @@ -6045,7 +6069,8 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { "nickName3", payload.CRInfoVersion, &common.Uint168{}) s.CurrentHeight = 1 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.GetCRCommittee().RegisterFuncitons(&crstate.CommitteeFuncsConfig{ GetTxReference: s.Chain.UTXOCache.GetTxReference, GetUTXO: s.Chain.GetDB().GetFFLDB().GetUTXO, @@ -6099,7 +6124,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs1, references, producersMap, nil, crsMap), "the output address of vote tx should exist in its input") @@ -6120,7 +6145,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs2, references, producersMap, nil, crsMap), "the output address of vote tx should exist in its input") @@ -6147,7 +6172,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs3, references, producersMap, nil, crsMap), "the output address of vote tx should exist in its input") @@ -6172,16 +6197,16 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs4, references, producersMap, nil, crsMap), "invalid vote output payload producer candidate: "+publicKey2) // Check vote output v0 with correct output program hash - s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs1, references, producersMap, nil, crsMap)) - s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs2, references, producersMap, nil, crsMap)) - s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs3, references, producersMap, nil, crsMap)) // Check vote output of v0 with crc type and invalid candidate @@ -6201,7 +6226,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs5, references, producersMap, nil, crsMap), "payload VoteProducerVersion not support vote CR") @@ -6222,7 +6247,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs6, references, producersMap, nil, crsMap), "invalid vote output payload CR candidate: "+candidateCID2.String()) @@ -6249,7 +6274,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs7, references, producersMap, nil, crsMap), "payload VoteProducerVersion not support vote CR") @@ -6271,7 +6296,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs8, references, producersMap, nil, crsMap), "votes larger than output amount") @@ -6294,7 +6319,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs9, references, producersMap, nil, crsMap), "total votes larger than output amount") @@ -6322,7 +6347,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs10, references, producersMap, nil, crsMap), "votes larger than output amount") @@ -6350,7 +6375,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs11, references, producersMap, nil, crsMap)) // Check vote output of v1 with wrong votes @@ -6377,7 +6402,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs12, references, producersMap, nil, crsMap)) // Check vote output v1 with correct votes @@ -6402,7 +6427,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }) s.Chain.GetCRCommittee().GetProposalManager().Proposals[*proposalHash1] = &crstate.ProposalState{Status: 1} - s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.NoError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs13, references, producersMap, nil, crsMap)) // Check vote output of v1 with wrong votes @@ -6425,7 +6450,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { }, }, }) - s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRVotingStartHeight, + s.EqualError(s.Chain.CheckVoteOutputs(config.DefaultParams.CRConfiguration.CRVotingStartHeight, outputs14, references, producersMap, nil, crsMap), "invalid CRCProposal: c0fc5185e8d0c82e13894e5ba0fc5375dc79285419a705c4c1e0188799b85a9c") } @@ -6461,14 +6486,14 @@ func (s *txValidatorTestSuite) TestCreateCRCAppropriationTransaction() { crAddress := "ERyUmNH51roR9qfru37Kqkaok2NghR7L5U" crcFoundation, _ := common.Uint168FromAddress(crAddress) - s.Chain.GetParams().CRAssetsAddress = *crcFoundation + s.Chain.GetParams().CRConfiguration.CRAssetsAddress = crAddress crcCommiteeAddressStr := "ESq12oQrvGqHfTkEDYJyR9MxZj1NMnonjo" - crcCommiteeAddressHash, _ := common.Uint168FromAddress(crcCommiteeAddressStr) - s.Chain.GetParams().CRExpensesAddress = *crcCommiteeAddressHash + s.Chain.GetParams().CRConfiguration.CRExpensesAddress = crcCommiteeAddressStr s.CurrentHeight = 1 - s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams())) + ckpManager := checkpoint.NewManager(config.GetDefaultParams()) + s.Chain.SetCRCommittee(crstate.NewCommittee(s.Chain.GetParams(), ckpManager)) s.Chain.GetCRCommittee().RegisterFuncitons(&crstate.CommitteeFuncsConfig{ GetTxReference: s.Chain.UTXOCache.GetTxReference, GetUTXO: s.Chain.GetDB().GetFFLDB().GetUTXO, @@ -6528,7 +6553,7 @@ func (s *txValidatorTestSuite) TestCreateCRCAppropriationTransaction() { }, Header: common2.Header{ Height: 1, - Previous: s.Chain.GetParams().GenesisBlock.Hash(), + Previous: core.GenesisBlock(s.Chain.GetParams().FoundationAddress).Hash(), }, } hash := block.Hash() @@ -6704,7 +6729,7 @@ func (s *txValidatorTestSuite) TestArbitersAccumulateReward() { type fields struct { State *state.State - ChainParams *config.Params + ChainParams *config.Configuration CRCommittee *crstate.Committee bestHeight func() uint32 bestBlockHash func() *common.Uint256 @@ -6747,14 +6772,19 @@ func (s *txValidatorTestSuite) TestArbitersAccumulateReward() { { "Normal", fields{ - ChainParams: &config.Params{ - PublicDPOSHeight: 1, - CRVotingStartHeight: 1, + ChainParams: &config.Configuration{ + PublicDPOSHeight: 1, + CRConfiguration: config.CRConfiguration{ + CRVotingStartHeight: 1, + MemberCount: 6, + }, NewELAIssuanceHeight: 1, HalvingRewardHeight: 1, HalvingRewardInterval: 1, - CRMemberCount: 6, - GeneralArbiters: 12, + DPoSConfiguration: config.DPoSConfiguration{ + + NormalArbitratorsCount: 12, + }, }, DposV2ActiveHeight: 1, dposV2EffectedProducers: make(map[string]*state.Producer), diff --git a/test/unit/unspentindex_test.go b/test/unit/unspentindex_test.go index 9fc9549cd..e79c3001e 100644 --- a/test/unit/unspentindex_test.go +++ b/test/unit/unspentindex_test.go @@ -6,27 +6,23 @@ package unit import ( - "os" - "path/filepath" "testing" "github.com/elastos/Elastos.ELA/blockchain/indexers" - "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/transaction" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/core/types/interfaces" - "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/contract/program" + "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/database" _ "github.com/elastos/Elastos.ELA/database/ffldb" "github.com/elastos/Elastos.ELA/utils/test" - "github.com/btcsuite/btcd/wire" "github.com/stretchr/testify/assert" ) @@ -58,7 +54,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() unspentIndexCoinbase = functions.CreateTransaction( 0, @@ -243,7 +239,7 @@ func TestUnspentIndexInit(t *testing.T) { var err error unspentIndexDB, err = LoadBlockDB(test.DataPath) assert.NoError(t, err) - testUnspentIndex = indexers.NewUnspentIndex(unspentIndexDB, &config.DefaultParams) + testUnspentIndex = indexers.NewUnspentIndex(unspentIndexDB, config.GetDefaultParams()) assert.NotEqual(t, nil, testUnspentIndex) assert.Equal(t, indexers.UnspentIndexKey, testUnspentIndex.Key()) assert.Equal(t, indexers.UnspentIndexName, testUnspentIndex.Name()) @@ -371,64 +367,6 @@ func TestUnspentIndex_DisconnectBlock(t *testing.T) { }) } -const ( - // blockDbNamePrefix is the prefix for the block database name. The - // database type is appended to this value to form the full block - // database name. - blockDbNamePrefix = "blocks" -) - -// dbPath returns the path to the block database given a database type. -func blockDbPath(dataPath, dbType string) string { - // The database name is based on the database type. - dbName := blockDbNamePrefix + "_" + dbType - if dbType == "sqlite" { - dbName = dbName + ".db" - } - dbPath := filepath.Join(dataPath, dbName) - return dbPath -} - -// loadBlockDB loads (or creates when needed) the block database taking into -// account the selected database backend and returns a handle to it. It also -// contains additional logic such warning the user if there are multiple -// databases which consume space on the file system and ensuring the regression -// test database is clean when in regression test mode. -func LoadBlockDB(dataPath string) (database.DB, error) { - // The memdb backend does not have a file path associated with it, so - // handle it uniquely. We also don't want to worry about the multiple - // database type warnings when running with the memory database. - - // The database name is based on the database type. - dbType := "ffldb" - dbPath := blockDbPath(dataPath, dbType) - - log.Infof("Loading block database from '%s'", dbPath) - db, err := database.Open(dbType, dbPath, wire.MainNet) - if err != nil { - // Return the error if it's not because the database doesn't - // exist. - if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode != - database.ErrDbDoesNotExist { - - return nil, err - } - - // Create the db if it does not exist. - err = os.MkdirAll(dataPath, 0700) - if err != nil { - return nil, err - } - db, err = database.Create(dbType, dbPath, wire.MainNet) - if err != nil { - return nil, err - } - } - - log.Info("Block database loaded") - return db, nil -} - func TestUnspentIndexEnd(t *testing.T) { _ = unspentIndexDB.Update(func(dbTx database.Tx) error { meta := dbTx.Metadata() diff --git a/test/unit/utxocache_test.go b/test/unit/utxocache_test.go index 83bc975ab..87ab80f4d 100644 --- a/test/unit/utxocache_test.go +++ b/test/unit/utxocache_test.go @@ -7,18 +7,16 @@ package unit import ( "errors" - "fmt" "testing" "github.com/elastos/Elastos.ELA/blockchain" + "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" - - "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/common/config" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/utils/test" @@ -40,7 +38,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() referTx = functions.CreateTransaction( common2.TxVersion09, @@ -132,7 +130,7 @@ func NewUtxoCacheDB() *UtxoCacheDB { func TestUTXOCache_Init(t *testing.T) { utxoCacheDB = NewUtxoCacheDB() - fmt.Println("refer tx hash:", referTx.Hash().String()) + //fmt.Println("refer tx hash:", referTx.Hash().String()) utxoCacheDB.SetTransaction(referTx) } diff --git a/test/unit/utxoindex_test.go b/test/unit/utxoindex_test.go index e759cbd80..75e9a288b 100644 --- a/test/unit/utxoindex_test.go +++ b/test/unit/utxoindex_test.go @@ -7,28 +7,87 @@ package unit import ( "errors" - "fmt" + "os" + "path/filepath" "testing" - "github.com/elastos/Elastos.ELA/common/config" - "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/transaction" - "github.com/elastos/Elastos.ELA/core/types/functions" - "github.com/elastos/Elastos.ELA/core/types/interfaces" - "github.com/elastos/Elastos.ELA/blockchain/indexers" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" + "github.com/elastos/Elastos.ELA/core/contract/program" + "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/database" "github.com/elastos/Elastos.ELA/utils/test" + "github.com/btcsuite/btcd/wire" "github.com/stretchr/testify/assert" ) +const ( + // blockDbNamePrefix is the prefix for the block database name. The + // database type is appended to this value to form the full block + // database name. + blockDbNamePrefix = "blocks" +) + +// dbPath returns the path to the block database given a database type. +func blockDbPath(dataPath, dbType string) string { + // The database name is based on the database type. + dbName := blockDbNamePrefix + "_" + dbType + if dbType == "sqlite" { + dbName = dbName + ".db" + } + dbPath := filepath.Join(dataPath, dbName) + return dbPath +} + +// loadBlockDB loads (or creates when needed) the block database taking into +// account the selected database backend and returns a handle to it. It also +// contains additional logic such warning the user if there are multiple +// databases which consume space on the file system and ensuring the regression +// test database is clean when in regression test mode. +func LoadBlockDB(dataPath string) (database.DB, error) { + // The memdb backend does not have a file path associated with it, so + // handle it uniquely. We also don't want to worry about the multiple + // database type warnings when running with the memory database. + + // The database name is based on the database type. + dbType := "ffldb" + dbPath := blockDbPath(dataPath, dbType) + + log.Infof("Loading block database from '%s'", dbPath) + db, err := database.Open(dbType, dbPath, wire.MainNet) + if err != nil { + // Return the error if it's not because the database doesn't + // exist. + if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode != + database.ErrDbDoesNotExist { + + return nil, err + } + + // Create the db if it does not exist. + err = os.MkdirAll(dataPath, 0700) + if err != nil { + return nil, err + } + db, err = database.Create(dbType, dbPath, wire.MainNet) + if err != nil { + return nil, err + } + } + + log.Info("Block database loaded") + return db, nil +} + var ( referHeight = uint32(100) referRecipient1, _ = common.Uint168FromAddress("EJMzC16Eorq9CuFCGtyMrq4Jmgw9jYCHQR") @@ -52,7 +111,7 @@ func init() { functions.GetTransactionByBytes = transaction.GetTransactionByBytes functions.CreateTransaction = transaction.CreateTransaction functions.GetTransactionParameters = transaction.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() testUtxoIndexReferTx = functions.CreateTransaction( common2.TxVersion09, @@ -216,7 +275,7 @@ func TestUTXOIndexInit(t *testing.T) { assert.NoError(t, err) testTxStore = NewTestTxStore() testTxStore.SetTx(testUtxoIndexReferTx, referHeight) - fmt.Println("refer tx hash:", testUtxoIndexReferTx.Hash().String()) + //fmt.Println("refer tx hash:", testUtxoIndexReferTx.Hash().String()) testUtxoIndex = indexers.NewUtxoIndex(utxoIndexDB, testTxStore) assert.NotEqual(t, nil, testUtxoIndex) diff --git a/test/unit/validation_test.go b/test/unit/validation_test.go index 201bece46..09d9a1c1f 100644 --- a/test/unit/validation_test.go +++ b/test/unit/validation_test.go @@ -35,7 +35,7 @@ func init() { functions.GetTransactionByBytes = transaction2.GetTransactionByBytes functions.CreateTransaction = transaction2.CreateTransaction functions.GetTransactionParameters = transaction2.GetTransactionparameters - config.DefaultParams = config.GetDefaultParams() + config.DefaultParams = *config.GetDefaultParams() } type act interface { @@ -278,11 +278,11 @@ func TestSchnorrRunProgramsOrigin(t *testing.T) { } privKey := decodePrivateKey(test.d, t) - MyPublicKey := decodePublicKey(test.pk, t) - fmt.Println("MyPublicKey", MyPublicKey) - pubKey, err := crypto.DecodePoint(MyPublicKey[:]) - fmt.Println(err) - fmt.Println(pubKey) + //MyPublicKey := decodePublicKey(test.pk, t) + //fmt.Println("MyPublicKey", MyPublicKey) + //pubKey, err := crypto.DecodePoint(MyPublicKey[:]) + //fmt.Println(err) + //fmt.Println(pubKey) pks = append(pks, privKey) @@ -300,11 +300,9 @@ func TestSchnorrRunProgramsOrigin(t *testing.T) { //this is the sum pk elliptic. copy(pk[:], crypto.Marshal(crypto.Curve, Px, Py)) - publicKey1, _ := crypto.DecodePoint(pk[:]) - fmt.Println(publicKey1) - //var err error + //publicKey1, _ := crypto.DecodePoint(pk[:]) + //fmt.Println(publicKey1) var tx interfaces.Transaction - //var acts []act var hashes []common.Uint168 var programs []*program.Program @@ -336,7 +334,7 @@ func TestSchnorrRunProgramsOrigin(t *testing.T) { }) } -//TestAggregateSignatures TestSchnorrRunProgramsOrigin +// TestAggregateSignatures TestSchnorrRunProgramsOrigin func TestAggregateSignatures(t *testing.T) { var testCases = []struct { d string //private key @@ -570,7 +568,7 @@ func TestSchnorrRunPrograms(t *testing.T) { if err != nil { fmt.Printf("AggregateSignatures index %d fail err %s \n", index, err.Error()) } else { - fmt.Printf("AggregateSignatures index %d passed \n", index) + //fmt.Printf("AggregateSignatures index %d passed \n", index) } } assert.NoError(t, err, "[RunProgram] passed with 1 checksig program") diff --git a/utils/common.go b/utils/common.go index 42608275b..d8661119a 100644 --- a/utils/common.go +++ b/utils/common.go @@ -58,7 +58,7 @@ func StartPProf(port uint32, host string) { listenAddr := net.JoinHostPort("", strconv.FormatUint( uint64(port), 10)) viewer.SetConfiguration(viewer.WithMaxPoints(100), - viewer.WithInterval(300000), + viewer.WithInterval(3e5), viewer.WithAddr(listenAddr), viewer.WithLinkAddr(host)) mgr := statsview.New() @@ -196,3 +196,28 @@ func GetProgramHashByCode(code []byte) (*common.Uint168, error) { return nil, errors.New("invalid code type") } } + +// checkHost check the host or IP address is valid and available. +func CheckHost(host string) error { + // Empty host check. + if host == "" { + return errors.New("arbiter IPAddress must set when arbiter" + + " service enabled") + } + + // Skip if host is already an IP address. + if ip := net.ParseIP(host); ip != nil { + return nil + } + + // Attempt to look up an IP address associated with the parsed host. + ips, err := net.LookupIP(host) + if err != nil { + return err + } + if len(ips) == 0 { + return fmt.Errorf("no addresses found for %s", host) + } + + return nil +} diff --git a/wallet/coin.go b/wallet/coin.go index 30b8bbb43..2d4b008b1 100644 --- a/wallet/coin.go +++ b/wallet/coin.go @@ -6,10 +6,10 @@ package wallet import ( - common2 "github.com/elastos/Elastos.ELA/core/types/common" "io" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" ) type Coin struct { diff --git a/wallet/coin_test.go b/wallet/coin_test.go index 03f51bfb8..d6eee171f 100644 --- a/wallet/coin_test.go +++ b/wallet/coin_test.go @@ -7,11 +7,11 @@ package wallet import ( "bytes" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "testing" "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/common" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/stretchr/testify/assert" ) diff --git a/wallet/coincheckpoint.go b/wallet/coincheckpoint.go index 2d91bf0ad..e328d4e74 100644 --- a/wallet/coincheckpoint.go +++ b/wallet/coincheckpoint.go @@ -7,7 +7,6 @@ package wallet import ( "bytes" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "io" "sync" @@ -16,6 +15,7 @@ import ( "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/types" + common2 "github.com/elastos/Elastos.ELA/core/types/common" ) // CoinsCheckPoint implement the ICheckPoint interface and store all coins diff --git a/wallet/coincheckpoint_test.go b/wallet/coincheckpoint_test.go index 8586f5fc1..0f59af7fd 100644 --- a/wallet/coincheckpoint_test.go +++ b/wallet/coincheckpoint_test.go @@ -10,11 +10,11 @@ import ( "testing" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types/functions" pg "github.com/elastos/Elastos.ELA/core/contract/program" "github.com/elastos/Elastos.ELA/core/transaction" "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/functions" "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/stretchr/testify/assert" diff --git a/wallet/common.go b/wallet/common.go index a08d0b3b3..8aeca581b 100644 --- a/wallet/common.go +++ b/wallet/common.go @@ -15,7 +15,7 @@ import ( var ( Store blockchain.IChainStore Chain *blockchain.BlockChain - ChainParam *config.Params + ChainParam *config.Configuration addressBook = make(map[string]*AddressInfo, 0) abMutex sync.RWMutex diff --git a/wallet/wallet.go b/wallet/wallet.go index a6be77be3..b2167953c 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -7,15 +7,16 @@ package wallet import ( "errors" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "os" "path/filepath" "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/common" + config2 "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils" ) @@ -27,6 +28,12 @@ const ( // dataExtension defines checkpoint file extension of utxo checkpoint. dataExtension = ".ucp" + // dataPath indicates the path storing the chain data. + dataPath = "data" + + // checkpointPath indicates the path storing the checkpoint data. + checkpointPath = "checkpoints" + // savePeriod defines interval height between two neighbor check // points. savePeriod = uint32(720) @@ -83,7 +90,10 @@ func (w *Wallet) ImportPubkey(pubKey []byte, enableUtxoDB bool) error { address: address, code: sc.Code, }) - ChainParam.CkpManager.Reset(func(point checkpoint.ICheckPoint) bool { + config := config2.DefaultParams + ckpManager := checkpoint.NewManager(&config) + ckpManager.SetDataPath(filepath.Join(dataPath, checkpointPath)) + ckpManager.Reset(func(point checkpoint.ICheckPoint) bool { return point.Key() == utxoCheckPointKey }) @@ -106,7 +116,10 @@ func (w *Wallet) ImportAddress(address string, enableUtxoDB bool) error { address: address, code: nil, }) - ChainParam.CkpManager.Reset(func(point checkpoint.ICheckPoint) bool { + config := config2.DefaultParams + ckpManager := checkpoint.NewManager(&config) + ckpManager.SetDataPath(filepath.Join(dataPath, checkpointPath)) + ckpManager.Reset(func(point checkpoint.ICheckPoint) bool { return point.Key() == utxoCheckPointKey }) diff --git a/wallet/wallet_test.go b/wallet/wallet_test.go index 81d35c0ed..1a94f2fe8 100644 --- a/wallet/wallet_test.go +++ b/wallet/wallet_test.go @@ -30,7 +30,7 @@ var wallet *Wallet func TestWallet_New(t *testing.T) { log.NewDefault(test.NodeLogPath, 0, 0, 0) defaultParams := config.GetDefaultParams() - ChainParam = &defaultParams + ChainParam = defaultParams wallet = New(test.DataDir)