Skip to content

Commit

Permalink
Merge pull request FUSIONFoundation#48 from cross-chain/v3.0.0-fix
Browse files Browse the repository at this point in the history
Add fsnbt API: isAutoBuyTicket, startAutoBuyTicket and stopAutoBuyTicket
  • Loading branch information
zhaojun-sh authored Jul 22, 2019
2 parents 607aa84 + e6cb18c commit d28ac6c
Show file tree
Hide file tree
Showing 20 changed files with 221 additions and 91 deletions.
1 change: 1 addition & 0 deletions cmd/efsn/chaincmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ The export-preimages command export hash preimages to an RLP encoded stream`,
utils.FakePoWFlag,
utils.TestnetFlag,
utils.RinkebyFlag,
utils.DevnetFlag,
},
Category: "BLOCKCHAIN COMMANDS",
Description: `
Expand Down
2 changes: 2 additions & 0 deletions cmd/efsn/consolecmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ func remoteConsole(ctx *cli.Context) error {
path = filepath.Join(path, "testnet")
} else if ctx.GlobalBool(utils.RinkebyFlag.Name) {
path = filepath.Join(path, "rinkeby")
} else if ctx.GlobalBool(utils.DevnetFlag.Name) {
path = filepath.Join(path, "devnet")
}
}
endpoint = fmt.Sprintf("%s/efsn.ipc", path)
Expand Down
20 changes: 9 additions & 11 deletions cmd/efsn/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
"strings"
"time"

"github.com/elastic/gosigar"
"github.com/FusionFoundation/efsn/accounts"
"github.com/FusionFoundation/efsn/accounts/keystore"
"github.com/FusionFoundation/efsn/cmd/utils"
Expand All @@ -41,6 +40,7 @@ import (
"github.com/FusionFoundation/efsn/log"
"github.com/FusionFoundation/efsn/metrics"
"github.com/FusionFoundation/efsn/node"
"github.com/elastic/gosigar"
"gopkg.in/urfave/cli.v1"
)

Expand Down Expand Up @@ -123,6 +123,7 @@ var (
utils.DeveloperPeriodFlag,
utils.TestnetFlag,
utils.RinkebyFlag,
utils.DevnetFlag,
utils.VMEnableDebugFlag,
utils.NetworkIdFlag,
utils.RPCCORSDomainFlag,
Expand Down Expand Up @@ -279,6 +280,11 @@ func geth(ctx *cli.Context) error {
func startNode(ctx *cli.Context, stack *node.Node) {
debug.Memsize.Add("node", stack)

// add more log and checking in devnet
if ctx.GlobalBool(utils.DevnetFlag.Name) {
common.DebugMode = true
}

// Start up the node itself
utils.StartNode(stack)

Expand Down Expand Up @@ -333,16 +339,8 @@ func startNode(ctx *cli.Context, stack *node.Node) {
}
}
}()
// Start auto buy tickets if enabled
if ctx.GlobalBool(utils.AutoBuyTicketsEnabledFlag.Name) {
// use first account
if unlocks != nil && passwords != nil {
common.AutoBuyTicket = true
go ethapi.AutoBuyTicket(common.HexToAddress(unlocks[0]), passwords[0])
}else{
log.Warn("Failed to AutoBuyTicket", "by args", utils.AutoBuyTicketsEnabledFlag.Name)
}
}
// Start auto buy tickets
go ethapi.AutoBuyTicket(ctx.GlobalBool(utils.AutoBuyTicketsEnabledFlag.Name))
// Start auxiliary services if enabled
if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
// Mining only makes sense if a full Ethereum node is running
Expand Down
1 change: 1 addition & 0 deletions cmd/efsn/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ var AppHelpFlagGroups = []flagGroup{
utils.NetworkIdFlag,
utils.TestnetFlag,
utils.RinkebyFlag,
utils.DevnetFlag,
utils.SyncModeFlag,
utils.GCModeFlag,
utils.EthStatsURLFlag,
Expand Down
25 changes: 22 additions & 3 deletions cmd/utils/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ var (
Name: "rinkeby",
Usage: "Rinkeby network: pre-configured proof-of-authority test network",
}
DevnetFlag = cli.BoolFlag{
Name: "devnet",
Usage: "Develop network: pre-configured proof-of-stake test network",
}
DeveloperFlag = cli.BoolFlag{
Name: "dev",
Usage: "Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled",
Expand Down Expand Up @@ -641,6 +645,9 @@ func MakeDataDir(ctx *cli.Context) string {
if ctx.GlobalBool(RinkebyFlag.Name) {
return filepath.Join(path, "rinkeby")
}
if ctx.GlobalBool(DevnetFlag.Name) {
return filepath.Join(path, "devnet")
}
return path
}
Fatalf("Cannot determine default data directory, please set manually (--datadir)")
Expand Down Expand Up @@ -695,6 +702,8 @@ func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
urls = params.TestnetBootnodes
case ctx.GlobalBool(RinkebyFlag.Name):
urls = params.RinkebyBootnodes
case ctx.GlobalBool(DevnetFlag.Name):
urls = params.DevnetBootnodes
case cfg.BootstrapNodes != nil:
return // already set, don't apply defaults.
}
Expand Down Expand Up @@ -989,6 +998,8 @@ func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
case ctx.GlobalBool(RinkebyFlag.Name):
cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
case ctx.GlobalBool(DevnetFlag.Name):
cfg.DataDir = filepath.Join(node.DefaultDataDir(), "devnet")
}

if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
Expand Down Expand Up @@ -1129,7 +1140,7 @@ func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) {
// SetEthConfig applies eth-related command line flags to the config.
func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
// Avoid conflicting network flags
checkExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag)
checkExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag, DevnetFlag)
checkExclusive(ctx, LightServFlag, SyncModeFlag, "light")

ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
Expand Down Expand Up @@ -1223,17 +1234,23 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
switch {
case ctx.GlobalBool(TestnetFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
//cfg.NetworkId = params.TestnetChainConfig.ChainID.Uint64()
cfg.NetworkId = 3
}
cfg.Genesis = core.DefaultTestnetGenesisBlock()
case ctx.GlobalBool(RinkebyFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
cfg.NetworkId = 4
cfg.NetworkId = params.RinkebyChainConfig.ChainID.Uint64()
}
cfg.Genesis = core.DefaultRinkebyGenesisBlock()
case ctx.GlobalBool(DevnetFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
cfg.NetworkId = params.DevnetChainConfig.ChainID.Uint64()
}
cfg.Genesis = core.DefaultDevnetGenesisBlock()
case ctx.GlobalBool(DeveloperFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
cfg.NetworkId = 1337
cfg.NetworkId = params.AllCliqueProtocolChanges.ChainID.Uint64()
}
// Create new developer account or reuse existing one
var (
Expand Down Expand Up @@ -1372,6 +1389,8 @@ func MakeGenesis(ctx *cli.Context) *core.Genesis {
genesis = core.DefaultTestnetGenesisBlock()
case ctx.GlobalBool(RinkebyFlag.Name):
genesis = core.DefaultRinkebyGenesisBlock()
case ctx.GlobalBool(DevnetFlag.Name):
genesis = core.DefaultDevnetGenesisBlock()
case ctx.GlobalBool(DeveloperFlag.Name):
Fatalf("Developer chains are ephemeral")
}
Expand Down
12 changes: 12 additions & 0 deletions common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,18 @@ func (s *MultiSwap) DeepCopy() MultiSwap {
}
}

func CheckSwapTargets(targets []Address, addr Address) error {
if len(targets) == 0 {
return nil
}
for _, target := range targets {
if addr == target {
return nil
}
}
return fmt.Errorf("swap taker does not match the specified targets")
}

// KeyValue wacom
type KeyValue struct {
Key string
Expand Down
2 changes: 1 addition & 1 deletion common/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package common

const (
var (
DebugMode = false
)

Expand Down
28 changes: 20 additions & 8 deletions consensus/datong/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ var (
errInvalidUncleHash = errors.New("non empty uncle hash")

errUnauthorized = errors.New("unauthorized")

ErrNoTicket = errors.New("Miner doesn't have ticket")
)

// SignerFn is a signer callback function to request a hash to be signed by a
Expand Down Expand Up @@ -324,6 +326,7 @@ func (dt *DaTong) Finalize(chain consensus.ChainReader, header *types.Header, st
}

snap := newSnapshot()
isInMining := header.MixDigest == (common.Hash{})

//update tickets
headerState := statedb
Expand Down Expand Up @@ -365,8 +368,8 @@ func (dt *DaTong) Finalize(chain consensus.ChainReader, header *types.Header, st

//delete tickets before coinbase if selected miner did not Seal
for i, t := range retreat {
if i >= maxNumberOfDeletedTickets {
break
if common.DebugMode && !isInMining && i == 0 {
log.Info("retreat ticket", "nonce", header.Nonce.Uint64(), "id", retreat[0].ID.String(), "owner", retreat[0].Owner, "blockHeight", header.Number, "ticketHeight", retreat[0].Height)
}
deleteTicket(t, ticketRetreat, !(t.IsInGenesis() || i == 0))
}
Expand All @@ -375,7 +378,7 @@ func (dt *DaTong) Finalize(chain consensus.ChainReader, header *types.Header, st
if err != nil {
return nil, errors.New("UpdateTickets failed: " + err.Error())
}
if header.MixDigest == (common.Hash{}) {
if isInMining {
header.MixDigest = hash
} else if header.MixDigest != hash {
return nil, fmt.Errorf("MixDigest mismatch, have:%v, want:%v", header.MixDigest, hash)
Expand Down Expand Up @@ -534,6 +537,10 @@ func (dt *DaTong) getAllTickets(chain consensus.ChainReader, header *types.Heade
return err
}

if _, hasError := maps["Error"]; hasError {
return nil
}

idstr, idok := maps["TicketID"].(string)
ownerstr, ownerok := maps["TicketOwner"].(string)
datastr, dataok := maps["Base"].(string)
Expand Down Expand Up @@ -635,6 +642,9 @@ func getSnapDataByHeader(header *types.Header) []byte {

func getSnapData(data []byte) []byte {
extraSuffix := len(data) - extraSeal
if extraSuffix < extraVanity {
return []byte{}
}
return data[extraVanity:extraSuffix]
}

Expand Down Expand Up @@ -723,7 +733,7 @@ func (dt *DaTong) calcBlockDifficulty(chain consensus.ChainReader, header *types
}
}
if !haveTicket {
return nil, nil, 0, nil, fmt.Errorf("Miner doesn't have ticket at block height %v", parent.Number)
return nil, nil, 0, nil, ErrNoTicket
}
ticketsTotalAmount, numberOfticketOwners := parentTickets.NumberOfTicketsAndOwners()

Expand All @@ -745,21 +755,23 @@ func (dt *DaTong) calcBlockDifficulty(chain consensus.ChainReader, header *types
}
close(ch)
sort.Sort(list)
for _, t := range list {
selectedTime := uint64(0)
for i, t := range list {
owner := t.tk.Owner
if owner == header.Coinbase {
selected = t.tk
break
} else {
retreat = append(retreat, t.tk) // one miner one selected ticket
selectedTime++
if i < maxNumberOfDeletedTickets {
retreat = append(retreat, t.tk) // one miner one selected ticket
}
}
}
if selected == nil {
return nil, nil, 0, nil, errors.New("myself tickets not selected in maxBlockTime")
}

selectedTime := uint64(len(retreat))

// cacl difficulty
difficulty := new(big.Int).SetUint64(ticketsTotalAmount - selectedTime)
if selectedTime > 0 {
Expand Down
26 changes: 26 additions & 0 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,24 @@ func DefaultRinkebyGenesisBlock() *Genesis {
}
}

// DefaultDevnetGenesisBlock returns the Develop network genesis block.
func DefaultDevnetGenesisBlock() *Genesis {
return &Genesis{
Config: params.DevnetChainConfig,
Nonce: 1,
ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000000000000100000001000000000101040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
GasLimit: 4700000,
Difficulty: big.NewInt(1),
Timestamp: 1561852800, // June 30 2019
TicketCreateInfo: &TicketsCreate{
Owner: common.HexToAddress("0x0122bf3930c1201a21133937ad5c83eb4ded1b08"),
Time: 1561852800, // June 30 2019
Count: 5,
},
Alloc: jsonPrealloc(devnetAllocDataJson),
}
}

// DeveloperGenesisBlock returns the 'efsn --dev' genesis block. Note, this must
// be seeded with the
func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
Expand Down Expand Up @@ -420,3 +438,11 @@ func decodePrealloc(data string) GenesisAlloc {
}
return ga
}

func jsonPrealloc(data string) GenesisAlloc {
var ga GenesisAlloc
if err := json.Unmarshal([]byte(data), &ga); err != nil {
panic(err)
}
return ga
}
9 changes: 9 additions & 0 deletions core/genesis_alloc.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@

package core

const devnetAllocDataJson = `{
"0x3a1b3b81ed061581558a81f11d63e03129347437": {"balance": "100000000000000000000000000"},
"0x0963a18ea497b7724340fdfe4ff6e060d3f9e388": {"balance": "100000000000000000000000000"},
"0x5ee5c548a649594feb24882c3deb456d36a78801": {"balance": "100000000000000000000000000"},
"0x0122bf3930c1201a21133937ad5c83eb4ded1b08": {"balance": "100000000000000000000000000"},
"0x37a200388caa75edcc53a2bd329f7e9563c6acb6": {"balance": "100000000000000000000000000"},
"0x07f35aba9555a532c0edc2bd6350c891b6f2c8d0": {"balance": "100000000000000000000000000"}
}`

// Constants containing the genesis allocation of built-in genesis blocks.
// Their content is an RLP-encoded list of (address, balance) tuples.
// Use mkalloc.go to create/update them.
Expand Down
41 changes: 0 additions & 41 deletions core/state/statedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -985,26 +985,6 @@ func (db *StateDB) calcNotationDisplay(notation uint64) uint64 {
return (notation*100 + check)
}

// // GenNotation wacom
// func (db *StateDB) GenNotation(addr common.Address) error {
// stateObject := db.GetOrNewStateObject(addr)
// if stateObject != nil {
// if n := db.GetNotation(addr); n != 0 {
// return fmt.Errorf("Account %s has a notation:%d", addr.String(), n)
// }
// notations, err := db.AllNotation()
// if err != nil {
// log.Error("GenNotation: Unable to decode bytes in AllNotation")
// return err
// }
// notations = append(notations, addr)
// stateObject.SetNotation(uint64(len(notations)))
// db.notations = notations
// return db.updateNotations()
// }
// return nil
// }

// AllAssets wacom
func (db *StateDB) AllAssets() (map[common.Hash]common.Asset, error) {
return nil, fmt.Errorf("All assets has been depreciated, use api.fusionnetwork.io")
Expand Down Expand Up @@ -1340,27 +1320,6 @@ func (db *StateDB) RemoveMultiSwap(id common.Hash) error {
return nil
}

type assetsStruct struct {
HASH common.Hash
ASSET common.Asset
}

type sortableAssetLURSlice []assetsStruct

func (s sortableAssetLURSlice) Len() int {
return len(s)
}

func (s sortableAssetLURSlice) Less(i, j int) bool {
a, _ := new(big.Int).SetString(s[i].HASH.Hex(), 0)
b, _ := new(big.Int).SetString(s[j].HASH.Hex(), 0)
return a.Cmp(b) < 0
}

func (s sortableAssetLURSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}

// GetStructData wacom
func (db *StateDB) GetStructData(addr common.Address, key []byte) []byte {
if key == nil {
Expand Down
Loading

0 comments on commit d28ac6c

Please sign in to comment.