<commit_before>// Copyright 2018 The Fractal Team Authors
// This file is part of the fractal project.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package dpos

import (
	"errors"
	"fmt"
	"math/big"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/ethereum/go-ethereum/log"
	"github.com/fractalplatform/fractal/accountmanager"
	"github.com/fractalplatform/fractal/common"
	"github.com/fractalplatform/fractal/consensus"
	"github.com/fractalplatform/fractal/crypto"
	"github.com/fractalplatform/fractal/snapshot"
	"github.com/fractalplatform/fractal/state"
	"github.com/fractalplatform/fractal/types"
	lru "github.com/hashicorp/golang-lru"
)

var (
	errMissingSignature           = errors.New("extra-data 65 byte suffix signature missing")
	errMismatchSignerAndValidator = errors.New("mismatch block signer and candidate")
	errInvalidMintBlockTime       = errors.New("invalid time to mint the block")
	errInvalidBlockCandidate      = errors.New("invalid block candidate")
	errInvalidTimestamp           = errors.New("invalid timestamp")
	ErrIllegalCandidateName       = errors.New("illegal candidate name")
	ErrIllegalCandidatePubKey     = errors.New("illegal candidate pubkey")
	ErrTooMuchRreversible         = errors.New("too much rreversible blocks")
	ErrSystemTakeOver             = errors.New("system account take over")
	errUnknownBlock               = errors.New("unknown block")
	extraSeal                     = 65
	timeOfGenesisBlock            int64
)

type stateDB struct {
	name    string
	assetid uint64
	state   *state.StateDB
}

func (s *stateDB) GetSnapshot(key string, timestamp uint64) ([]byte, error) {
	snapshotManager := snapshot.NewSnapshotManager(s.state)
	return snapshotManager.GetSnapshotMsg(s.name, key, timestamp)
}

func (s *stateDB) Get(key string) ([]byte, error) {
	return s.state.Get(s.name, key)
}
func (s *stateDB) Put(key string, value []byte) error {
	s.state.Put(s.name, key, value)
	return nil
}
func (s *stateDB) Delete(key string) error {
	s.state.Delete(s.name, key)
	return nil
}
func (s *stateDB) Undelegate(to string, amount *big.Int) (*types.Action, error) {
	action := types.NewAction(types.Transfer, common.StrToName(s.name), common.StrToName(to), 0, s.assetid, 0, amount, nil, nil)
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return action, err
	}
	return action, accountDB.TransferAsset(common.StrToName(s.name), common.StrToName(to), s.assetid, amount)
}
func (s *stateDB) IncAsset2Acct(from string, to string, amount *big.Int) (*types.Action, error) {
	action := types.NewAction(types.IncreaseAsset, common.StrToName(s.name), common.StrToName(to), 0, s.assetid, 0, amount, nil, nil)
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return action, err
	}
	return action, accountDB.IncAsset2Acct(common.StrToName(from), common.StrToName(to), s.assetid, amount)
}
func (s *stateDB) IsValidSign(name string, pubkey []byte) bool {
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return false
	}
	return accountDB.IsValidSign(common.StrToName(name), common.BytesToPubKey(pubkey)) == nil
}
func (s *stateDB) GetBalanceByTime(name string, timestamp uint64) (*big.Int, error) {
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return big.NewInt(0), err
	}
	return accountDB.GetBalanceByTime(common.StrToName(name), s.assetid, 1, timestamp)
}

// Genesis dpos genesis store
func Genesis(cfg *Config, state *state.StateDB, timestamp uint64, number uint64) error {
	sys := NewSystem(state, cfg)
	if err := sys.SetCandidate(&CandidateInfo{
		Name:          cfg.SystemName,
		URL:           cfg.SystemURL,
		Quantity:      big.NewInt(0),
		TotalQuantity: big.NewInt(0),
		Number:        number,
	}); err != nil {
		return err
	}

	epcho := cfg.epoch(timestamp)
	if err := sys.SetLastestEpcho(epcho); err != nil {
		return err
	}
	if err := sys.SetState(&GlobalState{
		Epcho:                  epcho,
		PreEpcho:               epcho,
		ActivatedTotalQuantity: big.NewInt(0),
		TotalQuantity:          big.NewInt(0),
		OffCandidateNumber:     []uint64{},
		OffCandidateSchedule:   []uint64{},
		Number:                 number,
	}); err != nil {<commit_msg>fix get balance by time bug (#298)<commit_after>// Copyright 2018 The Fractal Team Authors
// This file is part of the fractal project.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package dpos

import (
	"errors"
	"fmt"
	"math/big"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/ethereum/go-ethereum/log"
	"github.com/fractalplatform/fractal/accountmanager"
	"github.com/fractalplatform/fractal/common"
	"github.com/fractalplatform/fractal/consensus"
	"github.com/fractalplatform/fractal/crypto"
	"github.com/fractalplatform/fractal/snapshot"
	"github.com/fractalplatform/fractal/state"
	"github.com/fractalplatform/fractal/types"
	lru "github.com/hashicorp/golang-lru"
)

var (
	errMissingSignature           = errors.New("extra-data 65 byte suffix signature missing")
	errMismatchSignerAndValidator = errors.New("mismatch block signer and candidate")
	errInvalidMintBlockTime       = errors.New("invalid time to mint the block")
	errInvalidBlockCandidate      = errors.New("invalid block candidate")
	errInvalidTimestamp           = errors.New("invalid timestamp")
	ErrIllegalCandidateName       = errors.New("illegal candidate name")
	ErrIllegalCandidatePubKey     = errors.New("illegal candidate pubkey")
	ErrTooMuchRreversible         = errors.New("too much rreversible blocks")
	ErrSystemTakeOver             = errors.New("system account take over")
	errUnknownBlock               = errors.New("unknown block")
	extraSeal                     = 65
	timeOfGenesisBlock            int64
)

type stateDB struct {
	name    string
	assetid uint64
	state   *state.StateDB
}

func (s *stateDB) GetSnapshot(key string, timestamp uint64) ([]byte, error) {
	snapshotManager := snapshot.NewSnapshotManager(s.state)
	return snapshotManager.GetSnapshotMsg(s.name, key, timestamp)
}

func (s *stateDB) Get(key string) ([]byte, error) {
	return s.state.Get(s.name, key)
}
func (s *stateDB) Put(key string, value []byte) error {
	s.state.Put(s.name, key, value)
	return nil
}
func (s *stateDB) Delete(key string) error {
	s.state.Delete(s.name, key)
	return nil
}
func (s *stateDB) Undelegate(to string, amount *big.Int) (*types.Action, error) {
	action := types.NewAction(types.Transfer, common.StrToName(s.name), common.StrToName(to), 0, s.assetid, 0, amount, nil, nil)
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return action, err
	}
	return action, accountDB.TransferAsset(common.StrToName(s.name), common.StrToName(to), s.assetid, amount)
}
func (s *stateDB) IncAsset2Acct(from string, to string, amount *big.Int) (*types.Action, error) {
	action := types.NewAction(types.IncreaseAsset, common.StrToName(s.name), common.StrToName(to), 0, s.assetid, 0, amount, nil, nil)
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return action, err
	}
	return action, accountDB.IncAsset2Acct(common.StrToName(from), common.StrToName(to), s.assetid, amount)
}
func (s *stateDB) IsValidSign(name string, pubkey []byte) bool {
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return false
	}
	return accountDB.IsValidSign(common.StrToName(name), common.BytesToPubKey(pubkey)) == nil
}
func (s *stateDB) GetBalanceByTime(name string, timestamp uint64) (*big.Int, error) {
	accountDB, err := accountmanager.NewAccountManager(s.state)
	if err != nil {
		return big.NewInt(0), err
	}
	balance, err := accountDB.GetBalanceByTime(common.StrToName(name), s.assetid, 1, timestamp)
	if err == accountmanager.ErrAccountNotExist {
		return big.NewInt(0), nil
	}
	return balance, err
}

// Genesis dpos genesis store
func Genesis(cfg *Config, state *state.StateDB, timestamp uint64, number uint64) error {
	sys := NewSystem(state, cfg)
	if err := sys.SetCandidate(&CandidateInfo{
		Name:          cfg.SystemName,
		URL:           cfg.SystemURL,
		Quantity:      big.NewInt(0),
		TotalQuantity: big.NewInt(0),
		Number:        number,
	}); err != nil {
		return err
	}

	epcho := cfg.epoch(timestamp)
	if err := sys.SetLastestEpcho(epcho); err != nil {
		return err
	}
	if err := sys.SetState(&GlobalState{
		Epcho:                  epcho,
		PreEpcho:               epcho,
		ActivatedTotalQuantity: big.NewInt(0),
		TotalQuantity:          big.NewInt(0),
		OffCandidateNumber:     []uint64{},
		OffCandidateSchedule:   []uint64{},
		Number:                 number,
	}); err != nil {
{'fraction_non_alphanumeric': 0.11841701605481134, 'fraction_numerical': 0.007976275692811126, 'mean_word_length': 3.9393939393939394, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5486757', 'n_tokens_mistral': 3276, 'n_tokens_neox': 3156, 'n_words': 854}