Skip to content

Commit

Permalink
Merge pull request #280 from aergoio/topic/refactor-name
Browse files Browse the repository at this point in the history
small refactoring about names, staking, votings
  • Loading branch information
rabbitprincess authored Oct 6, 2023
2 parents 0bad16c + e076259 commit a282031
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 93 deletions.
2 changes: 0 additions & 2 deletions chain/chainhandle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/aergoio/aergo-lib/db"
"github.com/aergoio/aergo/v2/account/key"
"github.com/aergoio/aergo/v2/contract"
"github.com/aergoio/aergo/v2/contract/system"
"github.com/aergoio/aergo/v2/internal/common"
"github.com/aergoio/aergo/v2/state"
"github.com/aergoio/aergo/v2/types"
Expand All @@ -37,7 +36,6 @@ func initTest(t *testing.T, testmode bool) {
t.Fatalf("failed init : %s", err.Error())
}
types.InitGovernance("dpos", true)
system.InitGovernance("dpos")

}

Expand Down
1 change: 0 additions & 1 deletion chain/chainservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,6 @@ func NewChainService(cfg *cfg.Config) *ChainService {

// For a strict governance transaction validation.
types.InitGovernance(cs.ConsensusType(), cs.IsPublic())
system.InitGovernance(cs.ConsensusType())

//reset parameter of aergo.system
systemState, err := cs.SDB().GetSystemAccountState()
Expand Down
61 changes: 25 additions & 36 deletions contract/name/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,41 +14,37 @@ import (
func ExecuteNameTx(bs *state.BlockState, scs *state.ContractState, txBody *types.TxBody,
sender, receiver *state.V, blockInfo *types.BlockHeaderInfo) ([]*types.Event, error) {

systemContractState, err := bs.StateDB.GetSystemAccountState()

ci, err := ValidateNameTx(txBody, sender, scs, systemContractState)
ci, err := ValidateNameTx(txBody, sender, scs)
if err != nil {
return nil, err
}

var events []*types.Event

var nameState *state.V
owner := getOwner(scs, []byte(types.AergoName), false)
if owner != nil {
if bytes.Equal(sender.ID(), owner) {
nameState = sender
} else {
nameState, err = bs.GetAccountStateV(owner)
if err != nil {
if nameState, err = bs.GetAccountStateV(owner); err != nil {
return nil, err
}
}
} else {
nameState = receiver
}

var events []*types.Event
switch ci.Name {
case types.NameCreate:
if err = CreateName(scs, txBody, sender, nameState,
ci.Args[0].(string)); err != nil {
nameArg := ci.Args[0].(string)
if err = CreateName(scs, txBody, sender, nameState, nameArg); err != nil {
return nil, err
}
jsonArgs := ""
if blockInfo.ForkVersion < 2 {
jsonArgs = `{"name":"` + ci.Args[0].(string) + `"}`
jsonArgs = `{"name":"` + nameArg + `"}`
} else {
jsonArgs = `["` + ci.Args[0].(string) + `"]`
jsonArgs = `["` + nameArg + `"]`
}
events = append(events, &types.Event{
ContractAddress: receiver.ID(),
Expand All @@ -57,16 +53,16 @@ func ExecuteNameTx(bs *state.BlockState, scs *state.ContractState, txBody *types
JsonArgs: jsonArgs,
})
case types.NameUpdate:
if err = UpdateName(bs, scs, txBody, sender, nameState,
ci.Args[0].(string), ci.Args[1].(string)); err != nil {
nameArg := ci.Args[0].(string)
toArg := ci.Args[1].(string)
if err = UpdateName(bs, scs, txBody, sender, nameState, nameArg, toArg); err != nil {
return nil, err
}
jsonArgs := ""
if blockInfo.ForkVersion < 2 {
jsonArgs = `{"name":"` + ci.Args[0].(string) +
`","to":"` + ci.Args[1].(string) + `"}`
jsonArgs = `{"name":"` + nameArg + `","to":"` + toArg + `"}`
} else {
jsonArgs = `["` + ci.Args[0].(string) + `","` + ci.Args[1].(string) + `"]`
jsonArgs = `["` + nameArg + `","` + toArg + `"]`
}
events = append(events, &types.Event{
ContractAddress: receiver.ID(),
Expand All @@ -75,7 +71,8 @@ func ExecuteNameTx(bs *state.BlockState, scs *state.ContractState, txBody *types
JsonArgs: jsonArgs,
})
case types.SetContractOwner:
ownerState, err := SetContractOwner(bs, scs, ci.Args[0].(string), nameState)
ownerArg := ci.Args[0].(string)
ownerState, err := SetContractOwner(bs, scs, ownerArg, nameState)
if err != nil {
return nil, err
}
Expand All @@ -87,9 +84,7 @@ func ExecuteNameTx(bs *state.BlockState, scs *state.ContractState, txBody *types
return events, nil
}

func ValidateNameTx(tx *types.TxBody, sender *state.V,
scs, systemcs *state.ContractState) (*types.CallInfo, error) {

func ValidateNameTx(tx *types.TxBody, sender *state.V, scs *state.ContractState) (*types.CallInfo, error) {
if sender != nil && sender.Balance().Cmp(tx.GetAmountBigInt()) < 0 {
return nil, types.ErrInsufficientBalance
}
Expand All @@ -99,30 +94,25 @@ func ValidateNameTx(tx *types.TxBody, sender *state.V,
return nil, err
}

name := ci.Args[0].(string)

nameArg := ci.Args[0].(string)
switch ci.Name {
case types.NameCreate:
namePrice := system.GetNamePrice()
if namePrice.Cmp(tx.GetAmountBigInt()) > 0 {
if system.GetNamePrice().Cmp(tx.GetAmountBigInt()) > 0 {
return nil, types.ErrTooSmallAmount
}
owner := getOwner(scs, []byte(name), false)
if owner != nil {
return nil, fmt.Errorf("aleady occupied %s", string(name))
if owner := getOwner(scs, []byte(nameArg), false); owner != nil {
return nil, fmt.Errorf("aleady occupied %s", string(nameArg))
}
case types.NameUpdate:
namePrice := system.GetNamePrice()
if namePrice.Cmp(tx.GetAmountBigInt()) > 0 {
if system.GetNamePrice().Cmp(tx.GetAmountBigInt()) > 0 {
return nil, types.ErrTooSmallAmount
}
if (!bytes.Equal(tx.Account, []byte(name))) &&
(!bytes.Equal(tx.Account, getOwner(scs, []byte(name), false))) {
return nil, fmt.Errorf("owner not matched : %s", name)
if (!bytes.Equal(tx.Account, []byte(nameArg))) &&
(!bytes.Equal(tx.Account, getOwner(scs, []byte(nameArg), false))) {
return nil, fmt.Errorf("owner not matched : %s", nameArg)
}
case types.SetContractOwner:
owner := getOwner(scs, []byte(types.AergoName), false)
if owner != nil {
if owner := getOwner(scs, []byte(types.AergoName), false); owner != nil {
return nil, fmt.Errorf("owner aleady set to %s", types.EncodeAddress(owner))
}
default:
Expand All @@ -135,8 +125,6 @@ func ValidateNameTx(tx *types.TxBody, sender *state.V,
func SetContractOwner(bs *state.BlockState, scs *state.ContractState,
address string, nameState *state.V) (*state.V, error) {

name := []byte(types.AergoName)

rawaddr, err := types.DecodeAddress(address)
if err != nil {
return nil, err
Expand All @@ -150,6 +138,7 @@ func SetContractOwner(bs *state.BlockState, scs *state.ContractState,
ownerState.AddBalance(nameState.Balance())
nameState.SubBalance(nameState.Balance())

name := []byte(types.AergoName)
if err = registerOwner(scs, name, rawaddr, name); err != nil {
return nil, err
}
Expand Down
11 changes: 5 additions & 6 deletions contract/name/name.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ func createName(scs *state.ContractState, name []byte, owner []byte) error {
// UpdateName is avaliable after bid implement
func UpdateName(bs *state.BlockState, scs *state.ContractState, tx *types.TxBody,
sender, receiver *state.V, name, to string) error {
amount := tx.GetAmountBigInt()
if len(getAddress(scs, []byte(name))) <= types.NameLength {
return fmt.Errorf("%s is not created yet", string(name))
}
destination, _ := types.DecodeAddress(to)
destination = GetAddress(scs, destination)

amount := tx.GetAmountBigInt()
sender.SubBalance(amount)
receiver.AddBalance(amount)
contract, err := bs.StateDB.OpenContractStateAccount(types.ToAccountID(destination))
Expand Down Expand Up @@ -88,7 +89,7 @@ func Resolve(bs *state.BlockState, name []byte, legacy bool) ([]byte, error) {
}

func openContract(bs *state.BlockState) (*state.ContractState, error) {
v, err := bs.GetAccountStateV([]byte("aergo.name"))
v, err := bs.GetAccountStateV([]byte(types.AergoName))
if err != nil {
return nil, err
}
Expand All @@ -101,17 +102,15 @@ func openContract(bs *state.BlockState) (*state.ContractState, error) {

// GetAddress is resolve name for mempool
func GetAddress(scs *state.ContractState, name []byte) []byte {
if len(name) == types.AddressLength ||
types.IsSpecialAccount(name) {
if len(name) == types.AddressLength || types.IsSpecialAccount(name) {
return name
}
return getAddress(scs, name)
}

// GetAddressLegacy is resolve name for mempool by buggy logic, leaved for backward compatibility
func GetAddressLegacy(scs *state.ContractState, name []byte) []byte {
if len(name) == types.AddressLength ||
strings.Contains(string(name), ".") {
if len(name) == types.AddressLength || strings.Contains(string(name), ".") {
return name
}
return getAddress(scs, name)
Expand Down
3 changes: 1 addition & 2 deletions contract/name/name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,12 @@ func TestName(t *testing.T) {
receiver, _ := sdb.GetStateDB().GetAccountStateV(tx.Recipient)
bs := sdb.NewBlockState(sdb.GetRoot())
scs := openContractState(t, bs)
systemcs := openSystemContractState(t, bs)

err := CreateName(scs, tx, sender, receiver, name)
assert.NoError(t, err, "create name")

scs = nextBlockContractState(t, bs, scs)
_, err = ValidateNameTx(tx, sender, scs, systemcs)
_, err = ValidateNameTx(tx, sender, scs)
assert.Error(t, err, "same name")

ret := getAddress(scs, []byte(name))
Expand Down
40 changes: 12 additions & 28 deletions contract/system/staking.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import (
"github.com/aergoio/aergo/v2/types"
)

var consensusType string

var (
stakingKey = []byte("staking")
stakingTotalKey = []byte("stakingtotal")
Expand All @@ -25,10 +23,6 @@ var (
const StakingDelay = 60 * 60 * 24 //block interval
//const StakingDelay = 5

func InitGovernance(consensus string) {
consensusType = consensus
}

type stakeCmd struct {
*SystemContext
amount *big.Int
Expand Down Expand Up @@ -61,23 +55,18 @@ func (c *stakeCmd) run() (*types.Event, error) {
}
sender.SubBalance(amount)
receiver.AddBalance(amount)

jsonArgs := ""
if c.SystemContext.BlockInfo.ForkVersion < 2 {
return &types.Event{
ContractAddress: receiver.ID(),
EventIdx: 0,
EventName: "stake",
JsonArgs: `{"who":"` +
types.EncodeAddress(sender.ID()) +
`", "amount":"` + amount.String() + `"}`,
}, nil
jsonArgs = `{"who":"` + types.EncodeAddress(sender.ID()) + `", "amount":"` + amount.String() + `"}`
} else {
jsonArgs = `["` + types.EncodeAddress(sender.ID()) + `", {"_bignum":"` + amount.String() + `"}]`
}
return &types.Event{
ContractAddress: receiver.ID(),
EventIdx: 0,
EventName: "stake",
JsonArgs: `["` +
types.EncodeAddress(sender.ID()) +
`", {"_bignum":"` + amount.String() + `"}]`,
JsonArgs: jsonArgs,
}, nil
}

Expand Down Expand Up @@ -114,23 +103,18 @@ func (c *unstakeCmd) run() (*types.Event, error) {
}
sender.AddBalance(balanceAdjustment)
receiver.SubBalance(balanceAdjustment)

jsonArgs := ""
if c.SystemContext.BlockInfo.ForkVersion < 2 {
return &types.Event{
ContractAddress: receiver.ID(),
EventIdx: 0,
EventName: "unstake",
JsonArgs: `{"who":"` +
types.EncodeAddress(sender.ID()) +
`", "amount":"` + balanceAdjustment.String() + `"}`,
}, nil
jsonArgs = `{"who":"` + types.EncodeAddress(sender.ID()) + `", "amount":"` + balanceAdjustment.String() + `"}`
} else {
jsonArgs = `["` + types.EncodeAddress(sender.ID()) + `", {"_bignum":"` + balanceAdjustment.String() + `"}]`
}
return &types.Event{
ContractAddress: receiver.ID(),
EventIdx: 0,
EventName: "unstake",
JsonArgs: `["` +
types.EncodeAddress(sender.ID()) +
`", {"_bignum":"` + balanceAdjustment.String() + `"}]`,
JsonArgs: jsonArgs,
}, nil
}

Expand Down
17 changes: 6 additions & 11 deletions contract/system/vote.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,23 +194,18 @@ func (c *voteCmd) run() (*types.Event, error) {
if err := c.updateVoteResult(); err != nil {
return nil, err
}

jsonArgs := ""
if c.SystemContext.BlockInfo.ForkVersion < 2 {
return &types.Event{
ContractAddress: c.Receiver.ID(),
EventIdx: 0,
EventName: c.op.ID(),
JsonArgs: `{"who":"` +
types.EncodeAddress(c.txBody.Account) +
`", "vote":` + string(c.args) + `}`,
}, nil
jsonArgs = `{"who":"` + types.EncodeAddress(c.txBody.Account) + `", "vote":` + string(c.args) + `}`
} else {
jsonArgs = `["` + types.EncodeAddress(c.txBody.Account) + `", ` + string(c.args) + `]`
}
return &types.Event{
ContractAddress: c.Receiver.ID(),
EventIdx: 0,
EventName: c.op.ID(),
JsonArgs: `["` +
types.EncodeAddress(c.txBody.Account) +
`", ` + string(c.args) + `]`,
JsonArgs: jsonArgs,
}, nil
}

Expand Down
1 change: 0 additions & 1 deletion contract/system/vote_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ func initTest(t *testing.T) (*state.ContractState, *state.V, *state.V) {
t.Fatalf("failed init : %s", err.Error())
}
// Need to pass the
InitGovernance("dpos")
const testSender = "AmPNYHyzyh9zweLwDyuoiUuTVCdrdksxkRWDjVJS76WQLExa2Jr4"

scs, err := bs.GetSystemAccountState()
Expand Down
1 change: 0 additions & 1 deletion contract/vm_dummy/vm_dummy.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ func LoadDummyChain(opts ...DummyChainOptions) (*DummyChain, error) {

// To pass the governance tests.
types.InitGovernance("dpos", true)
system.InitGovernance("dpos")

// To pass dao parameters test
scs, err := bc.sdb.GetStateDB().GetSystemAccountState()
Expand Down
6 changes: 1 addition & 5 deletions mempool/mempool.go
Original file line number Diff line number Diff line change
Expand Up @@ -676,15 +676,11 @@ func (mp *MemPool) validateTx(tx types.Transaction, account types.Address) error
return err
}
case types.AergoName:
systemcs, err := mp.stateDB.GetSystemAccountState()
if err != nil {
return err
}
sender, err := mp.stateDB.GetAccountStateV(account)
if err != nil {
return err
}
if _, err := name.ValidateNameTx(tx.GetBody(), sender, scs, systemcs); err != nil {
if _, err := name.ValidateNameTx(tx.GetBody(), sender, scs); err != nil {
return err
}
case types.AergoEnterprise:
Expand Down

0 comments on commit a282031

Please sign in to comment.