Skip to content

Commit

Permalink
Check code (#268)
Browse files Browse the repository at this point in the history
* fixs some incorrect code

* fix regexp some err

* use account manager regexp
  • Loading branch information
erickyan86 committed May 21, 2019
1 parent 5097ee4 commit ddde007
Show file tree
Hide file tree
Showing 27 changed files with 54 additions and 109 deletions.
10 changes: 3 additions & 7 deletions accountmanager/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,7 @@ func NewAccount(accountName common.Name, founderName common.Name, pubkey common.

//HaveCode check account have code
func (a *Account) HaveCode() bool {
if a.GetCodeSize() == 0 {
return false
}
return true
return a.GetCodeSize() != 0
}

// IsEmpty check account empty
Expand Down Expand Up @@ -274,7 +271,7 @@ func (a *Account) GetCodeHash() (common.Hash, error) {
//GetBalanceByID get balance by asset id
func (a *Account) GetBalanceByID(assetID uint64) (*big.Int, error) {
p, find := a.binarySearch(assetID)
if find == true {
if find {
return a.Balances[p].Balance, nil
}

Expand All @@ -289,7 +286,7 @@ func (a *Account) GetBalancesList() []*AssetBalance {

//GetAllBalances get all balance list
func (a *Account) GetAllBalances() (map[uint64]*big.Int, error) {
var ba = make(map[uint64]*big.Int, 0)
var ba = make(map[uint64]*big.Int)
for _, ab := range a.Balances {
ba[ab.AssetID] = ab.Balance
}
Expand Down Expand Up @@ -353,7 +350,6 @@ func (a *Account) AddNewAssetByAssetID(assetID uint64, amount *big.Int) {
}
}
}
return
}

//SetBalance set amount to balance
Expand Down
21 changes: 5 additions & 16 deletions accountmanager/accountmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import (
)

var (
acctRegExp = regexp.MustCompile("^([a-z][a-z0-9]{6,15})(?:\\.([a-z0-9]{1,8})){0,1}$")
acctRegExp = regexp.MustCompile(`^([a-z][a-z0-9]{6,15})(?:\.([a-z0-9]{1,8})){0,1}$`)
acctManagerName = "sysAccount"
acctInfoPrefix = "acctInfo"
accountNameIDPrefix = "accountNameId"
Expand Down Expand Up @@ -159,7 +159,6 @@ func (am *AccountManager) InitAccountCounter() {
}
am.sdb.Put(acctManagerName, counterPrefix, b)
}
return
}

//getAccountCounter get account counter cur value
Expand Down Expand Up @@ -465,7 +464,7 @@ func (am *AccountManager) SetAccount(acct *Account) error {
if acct == nil {
return ErrAccountIsNil
}
if acct.IsDestroyed() == true {
if acct.IsDestroyed() {
return ErrAccountIsDestroy
}
b, err := rlp.EncodeToBytes(acct)
Expand Down Expand Up @@ -546,7 +545,7 @@ func (am *AccountManager) RecoverTx(signer types.Signer, tx *types.Transaction)
return fmt.Errorf("exceed max sign length, want most %d, actual is %d", params.MaxSignLength, len(pubs))
}

recoverRes := &recoverActionResult{make(map[common.Name]*accountAuthor, 0)}
recoverRes := &recoverActionResult{make(map[common.Name]*accountAuthor)}
for i, pub := range pubs {
index := action.GetSignIndex(uint64(i))
if uint64(len(index)) > params.MaxSignDepth {
Expand All @@ -558,7 +557,7 @@ func (am *AccountManager) RecoverTx(signer types.Signer, tx *types.Transaction)
}
}

authorVersion := make(map[common.Name]common.Hash, 0)
authorVersion := make(map[common.Name]common.Hash)
for name, acctAuthor := range recoverRes.acctAuthors {
var count uint64
for _, weight := range acctAuthor.indexWeight {
Expand Down Expand Up @@ -688,7 +687,7 @@ func (am *AccountManager) GetAssetInfoByID(assetID uint64) (*asset.AssetObject,

// GetAllAssetbyAssetId get accout asset and subAsset Info
func (am *AccountManager) GetAllAssetbyAssetId(acct *Account, assetId uint64) (map[uint64]*big.Int, error) {
var ba = make(map[uint64]*big.Int, 0)
var ba = make(map[uint64]*big.Int)

b, err := acct.GetBalanceByID(assetId)
if err != nil {
Expand Down Expand Up @@ -1239,7 +1238,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
internalAction := &types.InternalAction{Action: actionX.NewRPCAction(0), ActionType: "", GasUsed: 0, GasLimit: 0, Depth: 0, Error: ""}
internalActions = append(internalActions, internalAction)
}
break
case types.UpdateAccount:
var acct UpdataAccountAction
err := rlp.DecodeBytes(action.Data(), &acct)
Expand All @@ -1250,7 +1248,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
if err := am.UpdateAccount(action.Sender(), &acct); err != nil {
return nil, err
}
break
case types.UpdateAccountAuthor:
var acctAuth AccountAuthorAction
err := rlp.DecodeBytes(action.Data(), &acctAuth)
Expand All @@ -1260,7 +1257,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
if err := am.UpdateAccountAuthor(action.Sender(), &acctAuth); err != nil {
return nil, err
}
break
case types.IssueAsset:
var asset IssueAsset
err := rlp.DecodeBytes(action.Data(), &asset)
Expand All @@ -1275,7 +1271,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
actionX := types.NewAction(types.Transfer, common.Name(accountManagerContext.ChainConfig.ChainName), asset.Owner, 0, assetID, 0, asset.Amount, nil, nil)
internalAction := &types.InternalAction{Action: actionX.NewRPCAction(0), ActionType: "", GasUsed: 0, GasLimit: 0, Depth: 0, Error: ""}
internalActions = append(internalActions, internalAction)
break
case types.IncreaseAsset:
var inc IncAsset
err := rlp.DecodeBytes(action.Data(), &inc)
Expand All @@ -1291,8 +1286,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
actionX := types.NewAction(types.Transfer, common.Name(accountManagerContext.ChainConfig.ChainName), inc.To, 0, inc.AssetId, 0, inc.Amount, nil, nil)
internalAction := &types.InternalAction{Action: actionX.NewRPCAction(0), ActionType: "", GasUsed: 0, GasLimit: 0, Depth: 0, Error: ""}
internalActions = append(internalActions, internalAction)
break

case types.DestroyAsset:
// var asset asset.AssetObject
// err := rlp.DecodeBytes(action.Data(), &asset)
Expand All @@ -1309,7 +1302,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
actionX := types.NewAction(types.Transfer, common.Name(accountManagerContext.ChainConfig.AssetName), common.Name(accountManagerContext.ChainConfig.ChainName), 0, action.AssetID(), 0, action.Value(), nil, nil)
internalAction := &types.InternalAction{Action: actionX.NewRPCAction(0), ActionType: "", GasUsed: 0, GasLimit: 0, Depth: 0, Error: ""}
internalActions = append(internalActions, internalAction)
break
case types.UpdateAsset:
var asset UpdateAsset
err := rlp.DecodeBytes(action.Data(), &asset)
Expand All @@ -1330,7 +1322,6 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
if err := am.ast.UpdateAsset(action.Sender(), asset.AssetID, asset.Founder); err != nil {
return nil, err
}
break
case types.SetAssetOwner:
var asset UpdateAssetOwner
err := rlp.DecodeBytes(action.Data(), &asset)
Expand All @@ -1348,9 +1339,7 @@ func (am *AccountManager) process(accountManagerContext *types.AccountManagerCon
if err := am.ast.SetAssetNewOwner(action.Sender(), asset.AssetID, asset.Owner); err != nil {
return nil, err
}
break
case types.Transfer:
break
default:
return nil, ErrUnkownTxType
}
Expand Down
21 changes: 6 additions & 15 deletions asset/asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
)

var (
assetRegExp = regexp.MustCompile("^([a-z][a-z0-9]{1,15})(?:\\.([a-z0-9]{1,8})){0,1}$")
assetRegExp = regexp.MustCompile(`^([a-z][a-z0-9]{1,15})(?:\.([a-z0-9]{1,8})){0,1}$`)
assetManagerName = "assetAccount"
assetCountPrefix = "assetCount"
assetNameIdPrefix = "assetNameId"
Expand Down Expand Up @@ -163,16 +163,13 @@ func (a *Asset) getAssetCount() (uint64, error) {
func (a *Asset) InitAssetCount() {
_, err := a.getAssetCount()
if err == ErrAssetCountNotExist {
var assetID uint64
assetID = 0
//store assetCount
var assetID uint64 //store assetCount
b, err := rlp.EncodeToBytes(&assetID)
if err != nil {
panic(err)
}
a.sdb.Put(assetManagerName, assetCountPrefix, b)
}
return
}

//GetAllAssetObject get all asset
Expand Down Expand Up @@ -280,7 +277,7 @@ func (a *Asset) IssueAssetObject(ao *AssetObject) (uint64, error) {

//IssueAsset issue asset
func (a *Asset) IssueAsset(assetName string, number uint64, symbol string, amount *big.Int, dec uint64, founder common.Name, owner common.Name, limit *big.Int, contract common.Name, description string) (uint64, error) {
assetId, err := a.GetAssetIdByName(assetName)
_, err := a.GetAssetIdByName(assetName)
if err != nil && err != ErrAssetNotExist {
return 0, err
}
Expand All @@ -293,11 +290,7 @@ func (a *Asset) IssueAsset(assetName string, number uint64, symbol string, amoun
if err != nil {
return 0, err
}
assetId, err = a.addNewAssetObject(ao)
if err != nil {
return 0, err
}
return assetId, nil
return a.addNewAssetObject(ao)
}

//DestroyAsset destroy asset
Expand Down Expand Up @@ -353,16 +346,14 @@ func (a *Asset) IncreaseAsset(accountName common.Name, assetId uint64, amount *b
}

//check AddIssue > UpperLimit
var AddIssue *big.Int
AddIssue = new(big.Int).Add(asset.GetAssetAddIssue(), amount)
AddIssue := new(big.Int).Add(asset.GetAssetAddIssue(), amount)
if asset.GetUpperLimit().Cmp(big.NewInt(0)) > 0 && AddIssue.Cmp(asset.GetUpperLimit()) > 0 {
return ErrUpperLimit
}
asset.SetAssetAddIssue(AddIssue)

//check Amount > UpperLimit
var total *big.Int
total = new(big.Int).Add(asset.GetAssetAmount(), amount)
total := new(big.Int).Add(asset.GetAssetAmount(), amount)
if asset.GetUpperLimit().Cmp(big.NewInt(0)) > 0 && total.Cmp(asset.GetUpperLimit()) > 0 {
return ErrUpperLimit
}
Expand Down
4 changes: 2 additions & 2 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -639,10 +639,10 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
state, timestamp := bc.triegc.Pop()
log.Debug("Memory trie", "number", state.(WriteStateToDB).Number, "sizegc", sizegc, "timestamp", -timestamp)

if bc.statePruningClean == false {
if !bc.statePruningClean {
bc.triegc.Push(state, timestamp)
for !bc.triegc.Empty() {
state, timestamp = bc.triegc.Pop()
state, _ = bc.triegc.Pop()
log.Debug("Tiredb commit db", "root", state.(WriteStateToDB).Root.String(), "number", state.(WriteStateToDB).Number)
if err := triedb.Commit(state.(WriteStateToDB).Root, true); err != nil {
return false, err
Expand Down
1 change: 0 additions & 1 deletion blockchain/downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -675,5 +675,4 @@ func (task *downloadTask) Do() {
}
}
task.blocks = blocks
return
}
2 changes: 0 additions & 2 deletions blockchain/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ var (
errReorgSystemBlock = errors.New("not reorg system block")

errGenesisNoConfig = errors.New("genesis has no chain configuration")

errGenesisNoDpos = errors.New("genesis has no dpos configuration")
)

// GenesisMismatchError is raised when trying to overwrite an existing
Expand Down
5 changes: 0 additions & 5 deletions blockchain/forkcontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,6 @@ type ForkConfig struct {
Forkpercentage uint64
}

var defaultForkConfig = &ForkConfig{
ForkBlockNum: 10000,
Forkpercentage: 80,
}

// ForkInfo store in state db.
type ForkInfo struct {
CurForkID uint64
Expand Down
2 changes: 1 addition & 1 deletion blockchain/gen_genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestGenGenesis(t *testing.T) {
t.Fatal(fmt.Sprintf("genesis marshal --- %v", err))
}

if bytes.Compare(j, nj) != 0 {
if !bytes.Equal(j, nj) {
t.Fatal(fmt.Sprintf("genesis mismatch --- %v", err))
}
}
4 changes: 2 additions & 2 deletions blockchain/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,12 @@ func SetupGenesisBlock(db fdb.Database, genesis *Genesis) (chainCfg *params.Chai

number := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
if number == nil {
return newcfg, dposConfig(newcfg), common.Hash{}, fmt.Errorf("missing block number for head header hash")
return newcfg, dposConfig(newcfg), common.Hash{}, errors.New("missing block number for head header hash")
}

storedcfg := rawdb.ReadChainConfig(db, stored)
if storedcfg == nil {
return newcfg, dposConfig(newcfg), common.Hash{}, fmt.Errorf("Found genesis block without chain config")
return newcfg, dposConfig(newcfg), common.Hash{}, errors.New("Found genesis block without chain config")
}
am.SetAccountNameConfig(&am.Config{
AccountNameLevel: storedcfg.AccountNameCfg.Level,
Expand Down
2 changes: 1 addition & 1 deletion blockchain/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func TestSetupGenesis(t *testing.T) {

bts, _ := json.Marshal(config)
wbts, _ := json.Marshal(test.wantConfig)
if bytes.Compare(bts, wbts) != 0 {
if !bytes.Equal(bts, wbts) {
t.Errorf("%s:\n 2 returned %v\nwant %v", test.name, config, test.wantConfig)
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/ft/miner.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import (
"bufio"
"io"
"os"
"regexp"

am "github.com/fractalplatform/fractal/accountmanager"
"github.com/fractalplatform/fractal/common"
"github.com/fractalplatform/fractal/params"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -90,7 +90,7 @@ var setCoinbaseCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
name := common.Name(args[0])
if !name.IsValid(regexp.MustCompile("^([a-z][a-z0-9]{6,15})(?:\\.([a-z0-9]{1,8})){0,1}$")) {
if !name.IsValid(am.GetAcountNameRegExp()) {
jww.ERROR.Println("valid name: " + name)
return
}
Expand Down
6 changes: 3 additions & 3 deletions common/name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestValidateName(t *testing.T) {
{"longnamelongnamelongnamelongname", false},
}

reg := regexp.MustCompile("^[a-z][a-z0-9]{6,16}(\\.[a-z][a-z0-9]{0,16}){0,2}$")
reg := regexp.MustCompile(`^[a-z][a-z0-9]{6,16}(\.[a-z][a-z0-9]{0,16}){0,2}$`)
for _, test := range tests {
if result := StrToName(test.str).IsValid(reg); result != test.exp {
t.Errorf("IsValidAccountName(%s) == %v; expected %v, len:%v",
Expand Down Expand Up @@ -90,7 +90,7 @@ func TestNameUnmarshalJSON(t *testing.T) {
}

func TestIsChildren(t *testing.T) {
acctRegExp := regexp.MustCompile("^([a-z][a-z0-9]{6,15})(?:\\.([a-z0-9]{1,8})){0,1}$")
acctRegExp := regexp.MustCompile(`^([a-z][a-z0-9]{6,15})(?:\.([a-z0-9]{1,8})){0,1}$`)

type fields struct {
from Name
Expand All @@ -116,7 +116,7 @@ func TestIsChildren(t *testing.T) {
// {"longnamelongnamelongnamelongname", false},
}

//eg := regexp.MustCompile("^[a-z][a-z0-9]{6,16}(\\.[a-z][a-z0-9]{0,16}){0,2}$")
//eg := regexp.MustCompile("^[a-z][a-z0-9]{6,16}(\.[a-z][a-z0-9]{0,16}){0,2}$")
for _, tt := range tests {

if result := tt.fields.from.IsChildren(tt.fields.acct, tt.fields.reg); result != tt.exp {
Expand Down
4 changes: 1 addition & 3 deletions consensus/miner/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,18 +345,16 @@ func (worker *Worker) commitNewWork(timestamp int64, quit chan struct{}) (*types
if err != nil {
return nil, fmt.Errorf("seal block, err: %v", err)
}
var logs []*types.Log
for _, r := range work.currentReceipts {
for _, l := range r.Logs {
l.BlockHash = block.Hash()
}
logs = append(logs, r.Logs...)
}
for _, log := range work.currentState.Logs() {
log.BlockHash = block.Hash()
}

if bytes.Compare(block.ParentHash().Bytes(), worker.CurrentHeader().Hash().Bytes()) != 0 {
if !bytes.Equal(block.ParentHash().Bytes(), worker.CurrentHeader().Hash().Bytes()) {
return nil, fmt.Errorf("old parent hash")
}
if _, err := worker.WriteBlockWithState(block, work.currentReceipts, work.currentState); err != nil {
Expand Down
4 changes: 2 additions & 2 deletions event/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func BenchmarkSubscribe(t *testing.B) {
var channel1 chan *Event
var start = time.Now()
sub := Subscribe(station1, channel1, P2PRouterTestString, "")
duration := time.Now().Sub(start)
duration := time.Since(start)
StationUnregister(station1)
sub.Unsubscribe()
if duration > maxTime {
Expand All @@ -83,7 +83,7 @@ func BenchmarkSubscribe(t *testing.B) {
minTime = duration
}
totalTime += duration.Nanoseconds()
if time.Now().Sub(testTime) > 15*time.Second {
if time.Since(testTime) > 15*time.Second {
break
}
}
Expand Down
3 changes: 1 addition & 2 deletions feemanager/fee.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,7 @@ func (of *ObjectFee) binarySearch(assetID uint64) (int64, bool) {

func (of *ObjectFee) addAssetFee(assetID uint64, value *big.Int) {
index, find := of.binarySearch(assetID)

if find == true {
if find {
assetFee := of.AssetFees[index]
assetFee.addFee(value)
return
Expand Down
Loading

0 comments on commit ddde007

Please sign in to comment.