From 6bf4805e01d0594d6c744ecd5c67ab48d7932f5e Mon Sep 17 00:00:00 2001 From: CoderZhi Date: Wed, 15 Sep 2021 14:14:22 -0700 Subject: [PATCH 1/6] change info to warn in staking protocol (#2792) --- action/protocol/staking/protocol.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/action/protocol/staking/protocol.go b/action/protocol/staking/protocol.go index 58286ddc03..22decfb100 100644 --- a/action/protocol/staking/protocol.go +++ b/action/protocol/staking/protocol.go @@ -339,7 +339,7 @@ func (p *Protocol) handle(ctx context.Context, act action.Action, csm CandidateS if receiptErr, ok := err.(ReceiptError); ok { actionCtx := protocol.MustGetActionCtx(ctx) log.L().With( - zap.String("actionHash", hex.EncodeToString(actionCtx.ActionHash[:]))).Info("Failed to commit staking action", zap.Error(err)) + zap.String("actionHash", hex.EncodeToString(actionCtx.ActionHash[:]))).Debug("Failed to commit staking action", zap.Error(err)) return p.settleAction(ctx, csm, receiptErr.ReceiptStatus(), logs, tLogs) } return nil, err From c8f479c33294a95ba62b571ef1ce42fa8aa53b30 Mon Sep 17 00:00:00 2001 From: Dustin Xie Date: Tue, 14 Sep 2021 19:25:07 -0700 Subject: [PATCH 2/6] [evm] defer enabling Berlin + London (#2790) --- action/protocol/execution/evm/evm.go | 3 - action/protocol/execution/evm/evm_test.go | 12 ++-- .../execution/evm/evmstatedbadapter.go | 39 ++----------- .../execution/evm/evmstatedbadapter_test.go | 55 ------------------- .../protocol/execution/evm/testdata_test.go | 17 ++---- 5 files changed, 15 insertions(+), 111 deletions(-) diff --git a/action/protocol/execution/evm/evm.go b/action/protocol/execution/evm/evm.go index a5e1ae9b03..aa7c22d19a 100644 --- a/action/protocol/execution/evm/evm.go +++ b/action/protocol/execution/evm/evm.go @@ -270,9 +270,6 @@ func getChainConfig(g genesis.Blockchain, height uint64) *params.ChainConfig { if g.IsIceland(height) { chainConfig.ChainID = new(big.Int).SetUint64(uint64(config.EVMNetworkID())) } - // enable Berlin + London at Jutland - chainConfig.BerlinBlock = new(big.Int).SetUint64(g.JutlandBlockHeight) - chainConfig.LondonBlock = new(big.Int).SetUint64(g.JutlandBlockHeight) return &chainConfig } diff --git a/action/protocol/execution/evm/evm_test.go b/action/protocol/execution/evm/evm_test.go index 5fdfd85067..92cbabf1e8 100644 --- a/action/protocol/execution/evm/evm_test.go +++ b/action/protocol/execution/evm/evm_test.go @@ -217,16 +217,16 @@ func TestConstantinople(t *testing.T) { } else { require.Nil(evmChainConfig.ChainID) } + require.Equal(big.NewInt(int64(g.IcelandBlockHeight)), evmChainConfig.MuirGlacierBlock) + require.Equal(big.NewInt(int64(g.IcelandBlockHeight)), evmChainConfig.IstanbulBlock) require.Equal(isIceland, evmChainConfig.IsIstanbul(evm.Context.BlockNumber)) require.Equal(isIceland, evmChainConfig.IsMuirGlacier(evm.Context.BlockNumber)) require.Equal(isIceland, chainRules.IsIstanbul) - // jutland = enable Berlin + London - isJutland := g.IsJutland(e.height) - require.Equal(isJutland, evmChainConfig.IsBerlin(evm.Context.BlockNumber)) - require.Equal(isJutland, evmChainConfig.IsLondon(evm.Context.BlockNumber)) - require.Equal(isJutland, chainRules.IsBerlin) - require.Equal(isJutland, chainRules.IsLondon) + require.False(evmChainConfig.IsBerlin(evm.Context.BlockNumber)) + require.False(evmChainConfig.IsLondon(evm.Context.BlockNumber)) + require.False(chainRules.IsBerlin) + require.False(chainRules.IsLondon) } } diff --git a/action/protocol/execution/evm/evmstatedbadapter.go b/action/protocol/execution/evm/evmstatedbadapter.go index 2278078295..fcfa0712f4 100644 --- a/action/protocol/execution/evm/evmstatedbadapter.go +++ b/action/protocol/execution/evm/evmstatedbadapter.go @@ -62,8 +62,6 @@ type ( suicideSnapshot map[int]deleteAccount // snapshots of suicide accounts preimages preimageMap preimageSnapshot map[int]preimageMap - accessList *accessList // Per-transaction access list - accessListSnapshot map[int]*accessList notFixTopicCopyBug bool asyncContractTrie bool sortCachedContracts bool @@ -111,8 +109,6 @@ func NewStateDBAdapter( suicideSnapshot: make(map[int]deleteAccount), preimages: make(preimageMap), preimageSnapshot: make(map[int]preimageMap), - accessList: newAccessList(), - accessListSnapshot: make(map[int]*accessList), notFixTopicCopyBug: notFixTopicCopyBug, asyncContractTrie: asyncContractTrie, } @@ -385,43 +381,25 @@ func (stateDB *StateDBAdapter) Exist(evmAddr common.Address) bool { // // This method should only be called if Berlin/2929+2930 is applicable at the current number. func (stateDB *StateDBAdapter) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) { - stateDB.AddAddressToAccessList(sender) - if dst != nil { - stateDB.AddAddressToAccessList(*dst) - // If it's a create-tx, the destination will be added inside evm.create - } - for _, addr := range precompiles { - stateDB.AddAddressToAccessList(addr) - } - for _, el := range list { - stateDB.AddAddressToAccessList(el.Address) - for _, key := range el.StorageKeys { - stateDB.AddSlotToAccessList(el.Address, key) - } - } } // AddressInAccessList returns true if the given address is in the access list func (stateDB *StateDBAdapter) AddressInAccessList(addr common.Address) bool { - return stateDB.accessList.ContainsAddress(addr) + return false } // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list func (stateDB *StateDBAdapter) SlotInAccessList(addr common.Address, slot common.Hash) (addressOk bool, slotOk bool) { - return stateDB.accessList.Contains(addr, slot) + return false, false } // AddAddressToAccessList adds the given address to the access list. This operation is safe to perform // even if the feature/fork is not active yet -func (stateDB *StateDBAdapter) AddAddressToAccessList(addr common.Address) { - stateDB.accessList.AddAddress(addr) -} +func (stateDB *StateDBAdapter) AddAddressToAccessList(addr common.Address) {} // AddSlotToAccessList adds the given (address,slot) to the access list. This operation is safe to perform // even if the feature/fork is not active yet -func (stateDB *StateDBAdapter) AddSlotToAccessList(addr common.Address, slot common.Hash) { - stateDB.accessList.AddSlot(addr, slot) -} +func (stateDB *StateDBAdapter) AddSlotToAccessList(addr common.Address, slot common.Hash) {} // Empty returns true if the the contract is empty func (stateDB *StateDBAdapter) Empty(evmAddr common.Address) bool { @@ -471,9 +449,6 @@ func (stateDB *StateDBAdapter) RevertToSnapshot(snapshot int) { // restore preimages stateDB.preimages = nil stateDB.preimages = stateDB.preimageSnapshot[snapshot] - // restore access list - stateDB.accessList = nil - stateDB.accessList = stateDB.accessListSnapshot[snapshot] } func (stateDB *StateDBAdapter) cachedContractAddrs() []hash.Hash160 { @@ -514,8 +489,6 @@ func (stateDB *StateDBAdapter) Snapshot() int { p[k] = v } stateDB.preimageSnapshot[sn] = p - // save a copy of access list - stateDB.accessListSnapshot[sn] = stateDB.accessList.Copy() return sn } @@ -850,14 +823,10 @@ func (stateDB *StateDBAdapter) clear() { stateDB.suicideSnapshot = nil stateDB.preimages = nil stateDB.preimageSnapshot = nil - stateDB.accessList = nil - stateDB.accessListSnapshot = nil stateDB.cachedContract = make(contractMap) stateDB.contractSnapshot = make(map[int]contractMap) stateDB.suicided = make(deleteAccount) stateDB.suicideSnapshot = make(map[int]deleteAccount) stateDB.preimages = make(preimageMap) stateDB.preimageSnapshot = make(map[int]preimageMap) - stateDB.accessList = newAccessList() - stateDB.accessListSnapshot = make(map[int]*accessList) } diff --git a/action/protocol/execution/evm/evmstatedbadapter_test.go b/action/protocol/execution/evm/evmstatedbadapter_test.go index 29a5d94208..b02a95fc1d 100644 --- a/action/protocol/execution/evm/evmstatedbadapter_test.go +++ b/action/protocol/execution/evm/evmstatedbadapter_test.go @@ -209,9 +209,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { {common.BytesToHash(v1[:]), []byte("cat")}, {common.BytesToHash(v2[:]), []byte("dog")}, }, - []access{ - {c1, []common.Hash{k1, k2}, []common.Hash{k3, k4}, false}, - }, }, { []bal{ @@ -233,10 +230,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { []image{ {common.BytesToHash(v3[:]), []byte("hen")}, }, - []access{ - {c1, []common.Hash{k3, k4}, nil, true}, - {c2, []common.Hash{k1, k3}, []common.Hash{k2, k4}, false}, - }, }, { nil, @@ -251,9 +244,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { []image{ {common.BytesToHash(v4[:]), []byte("fox")}, }, - []access{ - {c2, []common.Hash{k2, k4}, nil, true}, - }, }, } @@ -281,25 +271,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { for _, e := range test.preimage { stateDB.AddPreimage(e.hash, e.v) } - // set access list - for _, e := range test.accessList { - require.Equal(e.exist, stateDB.AddressInAccessList(e.addr)) - for _, slot := range e.slots { - aOk, sOk := stateDB.SlotInAccessList(e.addr, slot) - require.Equal(e.exist, aOk) - require.False(sOk) - stateDB.AddSlotToAccessList(e.addr, slot) - e.exist = true - aOk, sOk = stateDB.SlotInAccessList(e.addr, slot) - require.True(aOk) - require.True(sOk) - } - for _, slot := range e.nx { - aOk, sOk := stateDB.SlotInAccessList(e.addr, slot) - require.True(aOk) - require.False(sOk) - } - } require.Equal(i, stateDB.Snapshot()) } @@ -328,10 +299,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { {common.BytesToHash(v3[:]), []byte("hen")}, {common.BytesToHash(v4[:]), []byte("fox")}, }, - []access{ - {c1, []common.Hash{k1, k2, k3, k4}, nil, true}, - {c2, []common.Hash{k1, k2, k3, k4}, nil, true}, - }, }, { []bal{ @@ -352,10 +319,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { {common.BytesToHash(v3[:]), []byte("hen")}, {common.BytesToHash(v4[:]), []byte(nil)}, }, - []access{ - {c1, []common.Hash{k1, k2, k3, k4}, nil, true}, - {c2, []common.Hash{k1, k3}, []common.Hash{k2, k4}, true}, - }, }, { []bal{ @@ -380,10 +343,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { {common.BytesToHash(v3[:]), []byte(nil)}, {common.BytesToHash(v4[:]), []byte(nil)}, }, - []access{ - {c1, []common.Hash{k1, k2}, []common.Hash{k3, k4}, true}, - {c2, nil, []common.Hash{k1, k2, k3, k4}, false}, - }, }, } @@ -410,20 +369,6 @@ func TestSnapshotRevertAndCommit(t *testing.T) { v := stateDB.preimages[e.hash] require.Equal(e.v, []byte(v)) } - // test access list - for _, e := range test.accessList { - require.Equal(e.exist, stateDB.AddressInAccessList(e.addr)) - for _, slot := range e.slots { - aOk, sOk := stateDB.SlotInAccessList(e.addr, slot) - require.Equal(e.exist, aOk) - require.True(sOk) - } - for _, slot := range e.nx { - aOk, sOk := stateDB.SlotInAccessList(e.addr, slot) - require.Equal(e.exist, aOk) - require.False(sOk) - } - } } // commit snapshot 0's state diff --git a/action/protocol/execution/evm/testdata_test.go b/action/protocol/execution/evm/testdata_test.go index a3d8574a3e..8d2a811dfb 100644 --- a/action/protocol/execution/evm/testdata_test.go +++ b/action/protocol/execution/evm/testdata_test.go @@ -41,19 +41,12 @@ type ( hash common.Hash v []byte } - access struct { - addr common.Address - slots []common.Hash - nx []common.Hash - exist bool - } stateDBTest struct { - balance []bal - codes []code - states []evmSet - suicide []sui - preimage []image - accessList []access + balance []bal + codes []code + states []evmSet + suicide []sui + preimage []image } ) From 5a68f1c5edcfcd5e28252aea42e0f154a088094d Mon Sep 17 00:00:00 2001 From: Dustin Xie Date: Wed, 15 Sep 2021 12:53:48 -0700 Subject: [PATCH 3/6] [evm] silence log.Error() in GetCommittedState() --- action/protocol/execution/evm/evmstatedbadapter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/action/protocol/execution/evm/evmstatedbadapter.go b/action/protocol/execution/evm/evmstatedbadapter.go index fcfa0712f4..e8315d7693 100644 --- a/action/protocol/execution/evm/evmstatedbadapter.go +++ b/action/protocol/execution/evm/evmstatedbadapter.go @@ -679,7 +679,7 @@ func (stateDB *StateDBAdapter) GetCommittedState(evmAddr common.Address, k commo } v, err := contract.GetCommittedState(hash.BytesToHash256(k[:])) if err != nil { - log.L().Error("Failed to get committed state.", zap.Error(err)) + log.L().Debug("Failed to get committed state.", zap.Error(err)) stateDB.logError(err) return common.Hash{} } From feb462e7849276e038254766a84582313e4d81e9 Mon Sep 17 00:00:00 2001 From: Ashish Nigam Date: Thu, 16 Sep 2021 04:08:11 +0530 Subject: [PATCH 4/6] [account] LoadAccount() to use address.Address (#2773) --- action/protocol/account/protocol_test.go | 7 +++--- action/protocol/account/transfer.go | 3 +-- action/protocol/account/util/util.go | 9 ++++++-- .../execution/evm/evmstatedbadapter.go | 8 +++---- action/protocol/execution/protocol_test.go | 2 +- action/protocol/rewarding/fund.go | 5 ++-- action/protocol/rewarding/fund_test.go | 3 +-- action/protocol/rewarding/reward_test.go | 9 ++++---- action/protocol/staking/handlers.go | 2 +- action/protocol/staking/handlers_test.go | 23 +++++++++---------- action/protocol/staking/protocol.go | 2 +- api/api_test.go | 2 +- e2etest/native_staking_test.go | 2 +- state/factory/factory_test.go | 12 ++++++---- 14 files changed, 45 insertions(+), 44 deletions(-) diff --git a/action/protocol/account/protocol_test.go b/action/protocol/account/protocol_test.go index 402094bac2..1e245c9de0 100644 --- a/action/protocol/account/protocol_test.go +++ b/action/protocol/account/protocol_test.go @@ -14,7 +14,6 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - "github.com/iotexproject/go-pkgs/hash" "github.com/iotexproject/iotex-address/address" "github.com/iotexproject/iotex-core/action/protocol" accountutil "github.com/iotexproject/iotex-core/action/protocol/account/util" @@ -60,13 +59,13 @@ func TestLoadOrCreateAccountState(t *testing.T) { }).AnyTimes() addrv1 := identityset.Address(27) - s, err := accountutil.LoadAccount(sm, hash.BytesToHash160(addrv1.Bytes())) + s, err := accountutil.LoadAccount(sm, addrv1) require.NoError(err) require.Equal(s.Balance, state.EmptyAccount().Balance) // create account require.NoError(createAccount(sm, addrv1.String(), big.NewInt(5))) - s, err = accountutil.LoadAccount(sm, hash.BytesToHash160(addrv1.Bytes())) + s, err = accountutil.LoadAccount(sm, addrv1) require.NoError(err) require.Equal("5", s.Balance.String()) require.Equal(uint64(0x0), s.Nonce) @@ -128,7 +127,7 @@ func TestProtocol_Initialize(t *testing.T) { ) require.Error(createAccount(sm, identityset.Address(0).String(), big.NewInt(0))) - acc0, err := accountutil.LoadAccount(sm, hash.BytesToHash160(identityset.Address(0).Bytes())) + acc0, err := accountutil.LoadAccount(sm, identityset.Address(0)) require.NoError(err) require.Equal(big.NewInt(100), acc0.Balance) } diff --git a/action/protocol/account/transfer.go b/action/protocol/account/transfer.go index db02de2452..02225c8073 100644 --- a/action/protocol/account/transfer.go +++ b/action/protocol/account/transfer.go @@ -10,7 +10,6 @@ import ( "context" "math/big" - "github.com/iotexproject/go-pkgs/hash" "github.com/iotexproject/iotex-address/address" "github.com/pkg/errors" @@ -69,7 +68,7 @@ func (p *Protocol) handleTransfer(ctx context.Context, act action.Action, sm pro if err != nil { return nil, errors.Wrapf(err, "failed to decode recipient address %s", tsf.Recipient()) } - recipientAcct, err := accountutil.LoadAccount(sm, hash.BytesToHash160(recipientAddr.Bytes())) + recipientAcct, err := accountutil.LoadAccount(sm, recipientAddr) if err == nil && recipientAcct.IsContract() { // update sender Nonce accountutil.SetNonce(tsf, sender) diff --git a/action/protocol/account/util/util.go b/action/protocol/account/util/util.go index da194d707a..c66d9dcf25 100644 --- a/action/protocol/account/util/util.go +++ b/action/protocol/account/util/util.go @@ -53,8 +53,13 @@ func LoadOrCreateAccount(sm protocol.StateManager, encodedAddr string) (*state.A return nil, err } -// LoadAccount loads an account state -func LoadAccount(sr protocol.StateReader, addrHash hash.Hash160) (*state.Account, error) { +// LoadAccount loads an account state by address.Address +func LoadAccount(sr protocol.StateReader, addr address.Address) (*state.Account, error) { + return LoadAccountByHash160(sr, hash.BytesToHash160(addr.Bytes())) +} + +// LoadAccountByHash160 loads an account state by 20-byte address +func LoadAccountByHash160(sr protocol.StateReader, addrHash hash.Hash160) (*state.Account, error) { var account state.Account if _, err := sr.State(&account, protocol.LegacyKeyOption(addrHash)); err != nil { if errors.Cause(err) == state.ErrStateNotExist { diff --git a/action/protocol/execution/evm/evmstatedbadapter.go b/action/protocol/execution/evm/evmstatedbadapter.go index e8315d7693..7f47b77e82 100644 --- a/action/protocol/execution/evm/evmstatedbadapter.go +++ b/action/protocol/execution/evm/evmstatedbadapter.go @@ -595,7 +595,7 @@ func (stateDB *StateDBAdapter) AccountState(encodedAddr string) (*state.Account, if contract, ok := stateDB.cachedContract[addrHash]; ok { return contract.SelfState(), nil } - return accountutil.LoadAccount(stateDB.sm, addrHash) + return accountutil.LoadAccountByHash160(stateDB.sm, addrHash) } //====================================== @@ -610,7 +610,7 @@ func (stateDB *StateDBAdapter) GetCodeHash(evmAddr common.Address) common.Hash { copy(codeHash[:], contract.SelfState().CodeHash) return codeHash } - account, err := accountutil.LoadAccount(stateDB.sm, addr) + account, err := accountutil.LoadAccountByHash160(stateDB.sm, addr) if err != nil { log.L().Error("Failed to get code hash.", zap.Error(err)) // TODO (zhi) not all err should be logged @@ -632,7 +632,7 @@ func (stateDB *StateDBAdapter) GetCode(evmAddr common.Address) []byte { } return code } - account, err := accountutil.LoadAccount(stateDB.sm, addr) + account, err := accountutil.LoadAccountByHash160(stateDB.sm, addr) if err != nil { log.L().Error("Failed to load account state for address.", log.Hex("addrHash", addr[:])) return nil @@ -802,7 +802,7 @@ func (stateDB *StateDBAdapter) getContract(addr hash.Hash160) (Contract, error) } func (stateDB *StateDBAdapter) getNewContract(addr hash.Hash160) (Contract, error) { - account, err := accountutil.LoadAccount(stateDB.sm, addr) + account, err := accountutil.LoadAccountByHash160(stateDB.sm, addr) if err != nil { return nil, errors.Wrapf(err, "failed to load account state for address %x", addr) } diff --git a/action/protocol/execution/protocol_test.go b/action/protocol/execution/protocol_test.go index 7e64e39b4c..a999f291e8 100644 --- a/action/protocol/execution/protocol_test.go +++ b/action/protocol/execution/protocol_test.go @@ -69,7 +69,7 @@ func (eb *ExpectedBalance) Balance() *big.Int { func readCode(sr protocol.StateReader, addr []byte) ([]byte, error) { var c evm.SerializableBytes - account, err := accountutil.LoadAccount(sr, hash.BytesToHash160(addr)) + account, err := accountutil.LoadAccountByHash160(sr, hash.BytesToHash160(addr)) if err != nil { return nil, err } diff --git a/action/protocol/rewarding/fund.go b/action/protocol/rewarding/fund.go index d84873af45..0ce724a017 100644 --- a/action/protocol/rewarding/fund.go +++ b/action/protocol/rewarding/fund.go @@ -13,7 +13,6 @@ import ( "github.com/pkg/errors" "google.golang.org/protobuf/proto" - "github.com/iotexproject/go-pkgs/hash" "github.com/iotexproject/iotex-address/address" "github.com/iotexproject/iotex-proto/golang/iotextypes" @@ -73,7 +72,7 @@ func (p *Protocol) Deposit( return nil, err } // Subtract balance from caller - acc, err := accountutil.LoadAccount(sm, hash.BytesToHash160(actionCtx.Caller.Bytes())) + acc, err := accountutil.LoadAccount(sm, actionCtx.Caller) if err != nil { return nil, err } @@ -130,7 +129,7 @@ func (p *Protocol) assertEnoughBalance( sm protocol.StateReader, amount *big.Int, ) error { - acc, err := accountutil.LoadAccount(sm, hash.BytesToHash160(actionCtx.Caller.Bytes())) + acc, err := accountutil.LoadAccount(sm, actionCtx.Caller) if err != nil { return err } diff --git a/action/protocol/rewarding/fund_test.go b/action/protocol/rewarding/fund_test.go index efc9e0395e..3b932e106d 100644 --- a/action/protocol/rewarding/fund_test.go +++ b/action/protocol/rewarding/fund_test.go @@ -14,7 +14,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/iotexproject/go-pkgs/hash" "github.com/iotexproject/iotex-address/address" "github.com/iotexproject/iotex-proto/golang/iotextypes" @@ -41,7 +40,7 @@ func TestProtocol_Fund(t *testing.T) { availableBalance, _, err := p.AvailableBalance(ctx, sm) require.NoError(t, err) assert.Equal(t, big.NewInt(5), availableBalance) - acc, err := accountutil.LoadAccount(sm, hash.BytesToHash160(actionCtx.Caller.Bytes())) + acc, err := accountutil.LoadAccount(sm, actionCtx.Caller) require.NoError(t, err) assert.Equal(t, big.NewInt(995), acc.Balance) diff --git a/action/protocol/rewarding/reward_test.go b/action/protocol/rewarding/reward_test.go index 0c28a77225..4cb5b6e31b 100644 --- a/action/protocol/rewarding/reward_test.go +++ b/action/protocol/rewarding/reward_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/golang/mock/gomock" - "github.com/iotexproject/go-pkgs/hash" "github.com/iotexproject/iotex-address/address" "github.com/iotexproject/iotex-election/test/mock/mock_committee" "github.com/iotexproject/iotex-proto/golang/iotextypes" @@ -227,7 +226,7 @@ func TestProtocol_ClaimReward(t *testing.T) { claimCtx := protocol.WithActionCtx(ctx, claimActionCtx) // Record the init balance of account - primAcc, err := accountutil.LoadAccount(sm, hash.BytesToHash160(claimActionCtx.Caller.Bytes())) + primAcc, err := accountutil.LoadAccount(sm, claimActionCtx.Caller) require.NoError(t, err) initBalance := primAcc.Balance @@ -240,7 +239,7 @@ func TestProtocol_ClaimReward(t *testing.T) { unclaimedBalance, _, err := p.UnclaimedBalance(ctx, sm, claimActionCtx.Caller) require.NoError(t, err) assert.Equal(t, big.NewInt(5), unclaimedBalance) - primAcc, err = accountutil.LoadAccount(sm, hash.BytesToHash160(claimActionCtx.Caller.Bytes())) + primAcc, err = accountutil.LoadAccount(sm, claimActionCtx.Caller) require.NoError(t, err) initBalance = new(big.Int).Add(initBalance, big.NewInt(5)) assert.Equal(t, initBalance, primAcc.Balance) @@ -259,7 +258,7 @@ func TestProtocol_ClaimReward(t *testing.T) { unclaimedBalance, _, err = p.UnclaimedBalance(ctx, sm, claimActionCtx.Caller) require.NoError(t, err) assert.Equal(t, big.NewInt(5), unclaimedBalance) - primAcc, err = accountutil.LoadAccount(sm, hash.BytesToHash160(claimActionCtx.Caller.Bytes())) + primAcc, err = accountutil.LoadAccount(sm, claimActionCtx.Caller) require.NoError(t, err) assert.Equal(t, initBalance, primAcc.Balance) @@ -278,7 +277,7 @@ func TestProtocol_ClaimReward(t *testing.T) { unclaimedBalance, _, err = p.UnclaimedBalance(ctx, sm, claimActionCtx.Caller) require.NoError(t, err) assert.Equal(t, big.NewInt(0), unclaimedBalance) - primAcc, err = accountutil.LoadAccount(sm, hash.BytesToHash160(claimActionCtx.Caller.Bytes())) + primAcc, err = accountutil.LoadAccount(sm, claimActionCtx.Caller) require.NoError(t, err) initBalance = new(big.Int).Add(initBalance, big.NewInt(5)) assert.Equal(t, initBalance, primAcc.Balance) diff --git a/action/protocol/staking/handlers.go b/action/protocol/staking/handlers.go index 3d059cc2d5..023f4f633c 100644 --- a/action/protocol/staking/handlers.go +++ b/action/protocol/staking/handlers.go @@ -848,7 +848,7 @@ func delBucketAndIndex(sm protocol.StateManager, owner, cand address.Address, in func fetchCaller(ctx context.Context, sr protocol.StateReader, amount *big.Int) (*state.Account, ReceiptError) { actionCtx := protocol.MustGetActionCtx(ctx) - caller, err := accountutil.LoadAccount(sr, hash.BytesToHash160(actionCtx.Caller.Bytes())) + caller, err := accountutil.LoadAccount(sr, actionCtx.Caller) if err != nil { return nil, &handleError{ err: errors.Wrapf(err, "failed to load the account of caller %s", actionCtx.Caller.String()), diff --git a/action/protocol/staking/handlers_test.go b/action/protocol/staking/handlers_test.go index c4a00c5b9c..32fd3aea03 100644 --- a/action/protocol/staking/handlers_test.go +++ b/action/protocol/staking/handlers_test.go @@ -19,7 +19,6 @@ import ( "github.com/stretchr/testify/require" "github.com/iotexproject/go-pkgs/crypto" - "github.com/iotexproject/go-pkgs/hash" "github.com/iotexproject/iotex-address/address" "github.com/iotexproject/iotex-proto/golang/iotextypes" @@ -224,7 +223,7 @@ func TestProtocol_HandleCreateStake(t *testing.T) { require.LessOrEqual(test.amount, candidate.Votes.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(stakerAddr.Bytes())) + caller, err := accountutil.LoadAccount(sm, stakerAddr) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -581,7 +580,7 @@ func TestProtocol_HandleCandidateRegister(t *testing.T) { require.Equal(test.amountStr, candidate.SelfStake.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -893,7 +892,7 @@ func TestProtocol_HandleCandidateUpdate(t *testing.T) { require.Equal(test.amountStr, candidate.SelfStake.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -1122,7 +1121,7 @@ func TestProtocol_HandleUnstake(t *testing.T) { require.Equal(test.afterUnstake, candidate.Votes.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -1336,7 +1335,7 @@ func TestProtocol_HandleWithdrawStake(t *testing.T) { require.Error(err) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, caller) require.NoError(err) withdrawCost, err := withdraw.Cost() require.NoError(err) @@ -1639,7 +1638,7 @@ func TestProtocol_HandleChangeCandidate(t *testing.T) { require.Equal(test.afterChange, cand.Votes.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -1838,7 +1837,7 @@ func TestProtocol_HandleTransferStake(t *testing.T) { require.LessOrEqual(test.afterTransfer, candidate.SelfStake.Uint64()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -2070,7 +2069,7 @@ func TestProtocol_HandleConsignmentTransfer(t *testing.T) { require.LessOrEqual(uint64(0), candidate.SelfStake.Uint64()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -2334,7 +2333,7 @@ func TestProtocol_HandleRestake(t *testing.T) { require.Equal(test.afterRestake, candidate.Votes.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -2553,7 +2552,7 @@ func TestProtocol_HandleDepositToStake(t *testing.T) { require.Equal(test.afterDeposit, candidate.Votes.String()) // test staker's account - caller, err := accountutil.LoadAccount(sm, hash.BytesToHash160(test.caller.Bytes())) + caller, err := accountutil.LoadAccount(sm, test.caller) require.NoError(err) actCost, err := act.Cost() require.NoError(err) @@ -2641,7 +2640,7 @@ func setupAccount(sm protocol.StateManager, addr address.Address, balance int64) func depositGas(ctx context.Context, sm protocol.StateManager, gasFee *big.Int) (*action.TransactionLog, error) { actionCtx := protocol.MustGetActionCtx(ctx) // Subtract balance from caller - acc, err := accountutil.LoadAccount(sm, hash.BytesToHash160(actionCtx.Caller.Bytes())) + acc, err := accountutil.LoadAccount(sm, actionCtx.Caller) if err != nil { return nil, err } diff --git a/action/protocol/staking/protocol.go b/action/protocol/staking/protocol.go index 22decfb100..c583a891d2 100644 --- a/action/protocol/staking/protocol.go +++ b/action/protocol/staking/protocol.go @@ -493,7 +493,7 @@ func (p *Protocol) settleAction( if err != nil { return nil, errors.Wrap(err, "failed to deposit gas") } - acc, err := accountutil.LoadAccount(sm, hash.BytesToHash160(actionCtx.Caller.Bytes())) + acc, err := accountutil.LoadAccount(sm, actionCtx.Caller) if err != nil { return nil, err } diff --git a/api/api_test.go b/api/api_test.go index 420078a106..64d2c6f743 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -2295,7 +2295,7 @@ func TestServer_GetTransactionLogByActionHash(t *testing.T) { } // check implicit transfer receiver balance - state, err := accountutil.LoadAccount(svr.sf, hash.BytesToHash160(identityset.Address(31).Bytes())) + state, err := accountutil.LoadAccount(svr.sf, identityset.Address(31)) require.NoError(err) require.Equal(big.NewInt(5), state.Balance) } diff --git a/e2etest/native_staking_test.go b/e2etest/native_staking_test.go index b24146ba72..f422300639 100644 --- a/e2etest/native_staking_test.go +++ b/e2etest/native_staking_test.go @@ -478,7 +478,7 @@ func checkAccountState( regFee, _ := new(big.Int).SetString(cfg.Genesis.RegistrationConsts.Fee, 10) cost.Add(cost, regFee) } - acct1, err := accountutil.LoadAccount(sr, hash.BytesToHash160(accountAddr.Bytes())) + acct1, err := accountutil.LoadAccount(sr, accountAddr) if err != nil { return err } diff --git a/state/factory/factory_test.go b/state/factory/factory_test.go index ccd3d80f82..9f6228c59a 100644 --- a/state/factory/factory_test.go +++ b/state/factory/factory_test.go @@ -121,7 +121,7 @@ func testRevert(ws *workingSet, t *testing.T) { require := require.New(t) sHash := hash.BytesToHash160(identityset.Address(28).Bytes()) - s, err := accountutil.LoadAccount(ws, sHash) + s, err := accountutil.LoadAccount(ws, identityset.Address(28)) require.NoError(err) require.Equal(big.NewInt(5), s.Balance) s0 := ws.Snapshot() @@ -142,7 +142,7 @@ func testSDBRevert(ws *workingSet, t *testing.T) { require := require.New(t) sHash := hash.BytesToHash160(identityset.Address(28).Bytes()) - s, err := accountutil.LoadAccount(ws, sHash) + s, err := accountutil.LoadAccount(ws, identityset.Address(28)) require.NoError(err) require.Equal(big.NewInt(5), s.Balance) s0 := ws.Snapshot() @@ -162,12 +162,14 @@ func testSDBRevert(ws *workingSet, t *testing.T) { func testSnapshot(ws *workingSet, t *testing.T) { require := require.New(t) sHash := hash.BytesToHash160(identityset.Address(28).Bytes()) + sHashAddr := identityset.Address(28) tHash := hash.BytesToHash160(identityset.Address(29).Bytes()) + tHashAddr := identityset.Address(29) - s, err := accountutil.LoadAccount(ws, tHash) + s, err := accountutil.LoadAccount(ws, tHashAddr) require.NoError(err) require.Equal(big.NewInt(7), s.Balance) - s, err = accountutil.LoadAccount(ws, sHash) + s, err = accountutil.LoadAccount(ws, sHashAddr) require.NoError(err) require.Equal(big.NewInt(5), s.Balance) s0 := ws.Snapshot() @@ -183,7 +185,7 @@ func testSnapshot(ws *workingSet, t *testing.T) { _, err = ws.PutState(s, protocol.LegacyKeyOption(sHash)) require.NoError(err) - s, err = accountutil.LoadAccount(ws, tHash) + s, err = accountutil.LoadAccount(ws, tHashAddr) require.NoError(err) require.Equal(big.NewInt(7), s.Balance) s2 := ws.Snapshot() From d10dabedb3b018c1d6abae9f71ccdde8289ccf38 Mon Sep 17 00:00:00 2001 From: Haaai <55118568+Liuhaai@users.noreply.github.com> Date: Fri, 17 Sep 2021 12:08:33 +0800 Subject: [PATCH 5/6] [api] fix gas estimation calc bug (#2786) * fixed gas estimation bug in api.go --- api/api.go | 4 ++-- api/api_test.go | 34 ++++++++++++++++++++++++++++++++++ go.mod | 2 +- go.sum | 2 +- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/api/api.go b/api/api.go index ced0525afc..385549826e 100644 --- a/api/api.go +++ b/api/api.go @@ -1564,7 +1564,7 @@ func (api *Server) estimateActionGasConsumptionForExecution(exec *iotextypes.Exe } estimatedGas := receipt.GasConsumed enough, _, err = api.isGasLimitEnough(callerAddr, sc, nonce, estimatedGas) - if err != nil { + if err != nil && err != action.ErrOutOfGas { return nil, status.Error(codes.Internal, err.Error()) } if !enough { @@ -1573,7 +1573,7 @@ func (api *Server) estimateActionGasConsumptionForExecution(exec *iotextypes.Exe for low <= high { mid := (low + high) / 2 enough, _, err = api.isGasLimitEnough(callerAddr, sc, nonce, mid) - if err != nil { + if err != nil && err != action.ErrOutOfGas { return nil, status.Error(codes.Internal, err.Error()) } if enough { diff --git a/api/api_test.go b/api/api_test.go index 64d2c6f743..34194c061a 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -2765,3 +2765,37 @@ func TestServer_GetActPoolActions(t *testing.T) { _, err = svr.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: []string{hex.EncodeToString(h3[:])}}) require.Error(err) } + +func TestServer_GetEstimateGasSpecial(t *testing.T) { + require := require.New(t) + cfg := newConfig(t) + + svr, bfIndexFile, err := createServer(cfg, true) + require.NoError(err) + defer func() { + testutil.CleanupPath(t, bfIndexFile) + }() + + // deploy self-desturct contract + contractCode := "608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610196806100606000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c80632e64cec11461004657806343d726d6146100645780636057361d1461006e575b600080fd5b61004e61008a565b60405161005b9190610124565b60405180910390f35b61006c610094565b005b610088600480360381019061008391906100ec565b6100cd565b005b6000600154905090565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b8060018190555050565b6000813590506100e681610149565b92915050565b6000602082840312156100fe57600080fd5b600061010c848285016100d7565b91505092915050565b61011e8161013f565b82525050565b60006020820190506101396000830184610115565b92915050565b6000819050919050565b6101528161013f565b811461015d57600080fd5b5056fea264697066735822122060e7a28baea4232a95074b94b50009d1d7b99302ef6556a1f3ce7f46a49f8cc064736f6c63430008000033" + contract, err := deployContract(svr, identityset.PrivateKey(13), 1, svr.bc.TipHeight(), contractCode) + + require.NoError(err) + require.True(len(contract) > 0) + + // call self-destuct func, which will invoke gas refund policy + data := "43d726d6" + byteCodes, err := hex.DecodeString(data) + require.NoError(err) + execution, err := action.NewExecution(contract, 2, big.NewInt(0), 0, big.NewInt(0), byteCodes) + require.NoError(err) + request := &iotexapi.EstimateActionGasConsumptionRequest{ + Action: &iotexapi.EstimateActionGasConsumptionRequest_Execution{ + Execution: execution.Proto(), + }, + CallerAddress: identityset.Address(13).String(), + } + res, err := svr.EstimateActionGasConsumption(context.Background(), request) + require.NoError(err) + require.Equal(uint64(10777), res.Gas) +} diff --git a/go.mod b/go.mod index 7fb1615537..1b7c9ea64a 100644 --- a/go.mod +++ b/go.mod @@ -49,4 +49,4 @@ require ( replace github.com/ethereum/go-ethereum => github.com/iotexproject/go-ethereum v0.4.0 -replace golang.org/x/xerrors => golang.org/x/xerrors v0.0.0-20190212162355-a5947ffaace3 +replace golang.org/x/xerrors => golang.org/x/xerrors v0.0.0-20190212162355-a5947ffaace3 \ No newline at end of file diff --git a/go.sum b/go.sum index d8e64e222f..584ba4810d 100644 --- a/go.sum +++ b/go.sum @@ -1588,4 +1588,4 @@ rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= -sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= +sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= \ No newline at end of file From 44e0a689183b9c2a683d9396549b9a06ccad6845 Mon Sep 17 00:00:00 2001 From: Haaai <55118568+Liuhaai@users.noreply.github.com> Date: Fri, 17 Sep 2021 15:31:29 +0800 Subject: [PATCH 6/6] Allow ioctl to show the list of actions for an account (#2750) * [ioctl] allow ioctl to show the list of actions for an account --- ioctl/cmd/account/accountactions.go | 181 ++++++++-------------------- ioctl/config/config.go | 21 ++-- ioctl/config/configsetget.go | 26 ++-- 3 files changed, 79 insertions(+), 149 deletions(-) diff --git a/ioctl/cmd/account/accountactions.go b/ioctl/cmd/account/accountactions.go index d82f3338b2..9748bac78d 100644 --- a/ioctl/cmd/account/accountactions.go +++ b/ioctl/cmd/account/accountactions.go @@ -7,25 +7,37 @@ package account import ( - "context" + "bytes" + "encoding/json" "fmt" + "net/http" "strconv" - "strings" - "github.com/golang/protobuf/ptypes" - "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils" "github.com/rodaine/table" "github.com/spf13/cobra" - "google.golang.org/grpc/status" "github.com/iotexproject/iotex-core/ioctl/config" "github.com/iotexproject/iotex-core/ioctl/output" "github.com/iotexproject/iotex-core/ioctl/util" - "github.com/iotexproject/iotex-proto/golang/iotexapi" - "github.com/iotexproject/iotex-proto/golang/iotextypes" ) -var countLimit *uint64 +type ( + allActionsByAddressResult struct { + ActHash string + BlkHeight string + Sender string + Recipient string + ActType string + Amount string + TimeStamp string + RecordType string + } + + allActionsByAddressResponse struct { + Count string + Results []*allActionsByAddressResult + } +) // Multi-language support var ( @@ -37,10 +49,6 @@ var ( config.English: "actions (ALIAS|ADDRESS) [SKIP]", config.Chinese: "actions (ALIAS|ADDRESS) [SKIP]", } - flagCountUsages = map[config.Language]string{ - config.English: "choose a count limit", - config.Chinese: "选择一个计数限制", - } ) // accountActionsCmd represents the account sign command @@ -55,12 +63,8 @@ var accountActionsCmd = &cobra.Command{ }, } -func init() { - countLimit = accountActionsCmd.Flags().Uint64("limit", 15, config.TranslateInLang(flagCountUsages, config.UILanguage)) -} - func accountActions(args []string) error { - var skip uint64 + var skip uint64 = 0 var err error if len(args) == 2 { skip, err = strconv.ParseUint(args[1], 10, 64) @@ -73,130 +77,51 @@ func accountActions(args []string) error { if err != nil { return output.NewError(output.AddressError, "failed to get address", err) } - - conn, err := util.ConnectToEndpoint(config.ReadConfig.SecureConnect && !config.Insecure) - if err != nil { - return output.NewError(output.NetworkError, "failed to connect to endpoint", err) - } - defer conn.Close() - cli := iotexapi.NewAPIServiceClient(conn) - ctx := context.Background() - - jwtMD, err := util.JwtAuth() - if err == nil { - ctx = metautils.NiceMD(jwtMD).ToOutgoing(ctx) + reqData := map[string]string{ + "address": addr, + "offset": fmt.Sprint(skip), } - - requestGetAccount := iotexapi.GetAccountRequest{ - Address: addr, - } - accountResponse, err := cli.GetAccount(ctx, &requestGetAccount) + jsonData, err := json.Marshal(reqData) if err != nil { - return output.NewError(output.APIError, "failed to get account", err) - } - numActions := accountResponse.AccountMeta.GetNumActions() - fmt.Println("Total:", numActions) - requestGetAction := iotexapi.GetActionsRequest{ - Lookup: &iotexapi.GetActionsRequest_ByAddr{ - ByAddr: &iotexapi.GetActionsByAddressRequest{ - Address: addr, - Start: numActions - *countLimit - skip, - Count: *countLimit, - }, - }, + return output.NewError(output.ConvertError, "failed to pack in json", nil) } - response, err := cli.GetActions(ctx, &requestGetAction) + resp, err := http.Post(config.ReadConfig.AnalyserEndpoint+"/api.ActionsService.GetActionsByAddress", "application/json", + bytes.NewBuffer(jsonData)) if err != nil { - sta, ok := status.FromError(err) - if ok { - return output.NewError(output.APIError, sta.Message(), nil) - } - return output.NewError(output.NetworkError, "failed to invoke GetActions api", err) + return output.NewError(output.NetworkError, "failed to send request", nil) } - if len(response.ActionInfo) == 0 { - return output.NewError(output.APIError, "no action info returned", nil) + + var respData allActionsByAddressResponse + err = json.NewDecoder(resp.Body).Decode(&respData) + if err != nil { + return output.NewError(output.SerializationError, "failed to deserialize the response", nil) } + actions := respData.Results + + fmt.Println("Total:", len(actions)) showFields := []interface{}{ - "Hash", - "Time", - "Status", + "ActHash", + "TimeStamp", + "BlkHeight", + "ActCategory", + "ActType", "Sender", - "Type", - "To", - "Contract", + "Recipient", "Amount", } - tbl := table.New(showFields...) - - for i := range response.ActionInfo { - k := len(response.ActionInfo) - 1 - i - actionInfo := response.ActionInfo[k] - requestGetReceipt := &iotexapi.GetReceiptByActionRequest{ActionHash: actionInfo.ActHash} - responseReceipt, err := cli.GetReceiptByAction(ctx, requestGetReceipt) - if err != nil { - sta, ok := status.FromError(err) - if ok { - fmt.Println(output.NewError(output.APIError, sta.Message(), nil)) - } else { - fmt.Println(output.NewError(output.NetworkError, "failed to invoke GetReceiptByAction api", err)) - } - continue - } - amount := "0" - transfer := actionInfo.Action.Core.GetTransfer() - if transfer != nil { - amount, _ = util.StringToIOTX(transfer.Amount) - - } - tbl.AddRow( + tb := table.New(showFields...) + for _, actionInfo := range actions { + tb.AddRow( actionInfo.ActHash, - getActionTime(actionInfo), - iotextypes.ReceiptStatus_name[int32(responseReceipt.ReceiptInfo.Receipt.GetStatus())], + actionInfo.TimeStamp, + actionInfo.BlkHeight, + actionInfo.RecordType, + actionInfo.ActType, actionInfo.Sender, - getActionTypeString(actionInfo), - getActionTo(actionInfo), - getActionContract(responseReceipt), - amount+" IOTX", + actionInfo.Recipient, + actionInfo.Amount+" IOTX", ) } - tbl.Print() + tb.Print() return nil } - -func getActionContract(responseReceipt *iotexapi.GetReceiptByActionResponse) string { - contract := responseReceipt.ReceiptInfo.Receipt.GetContractAddress() - if contract == "" { - contract = "-" - } - return contract -} - -func getActionTypeString(actionInfo *iotexapi.ActionInfo) string { - actionType := fmt.Sprintf("%T", actionInfo.Action.Core.GetAction()) - return strings.TrimLeft(actionType, "*iotextypes.ActionCore_") -} - -func getActionTo(actionInfo *iotexapi.ActionInfo) string { - recipient := "" - switch getActionTypeString(actionInfo) { - case "Transfer": - transfer := actionInfo.Action.Core.GetTransfer() - recipient = transfer.GetRecipient() - case "Execution": - execution := actionInfo.Action.Core.GetExecution() - recipient = execution.GetContract() - } - if recipient == "" { - recipient = "-" - } - return recipient -} - -func getActionTime(actionInfo *iotexapi.ActionInfo) string { - if actionInfo.Timestamp != nil { - if ts, err := ptypes.Timestamp(actionInfo.Timestamp); err == nil { - return ts.String() - } - } - return "" -} diff --git a/ioctl/config/config.go b/ioctl/config/config.go index a8fc3b1844..e4b3ff959f 100644 --- a/ioctl/config/config.go +++ b/ioctl/config/config.go @@ -57,14 +57,15 @@ type Context struct { // Config defines the config schema type Config struct { - Wallet string `json:"wallet" yaml:"wallet"` - Endpoint string `json:"endpoint" yaml:"endpoint"` - SecureConnect bool `json:"secureConnect" yaml:"secureConnect"` - Aliases map[string]string `json:"aliases" yaml:"aliases"` - DefaultAccount Context `json:"defaultAccount" yaml:"defaultAccount"` - Explorer string `json:"explorer" yaml:"explorer"` - Language string `json:"language" yaml:"language"` - Nsv2height uint64 `json:"nsv2height" yaml:"nsv2height"` + Wallet string `json:"wallet" yaml:"wallet"` + Endpoint string `json:"endpoint" yaml:"endpoint"` + SecureConnect bool `json:"secureConnect" yaml:"secureConnect"` + Aliases map[string]string `json:"aliases" yaml:"aliases"` + DefaultAccount Context `json:"defaultAccount" yaml:"defaultAccount"` + Explorer string `json:"explorer" yaml:"explorer"` + Language string `json:"language" yaml:"language"` + Nsv2height uint64 `json:"nsv2height" yaml:"nsv2height"` + AnalyserEndpoint string `json:"analyserEndpoint" yaml:"analyserEndpoint"` } var ( @@ -108,6 +109,10 @@ func init() { if ReadConfig.Nsv2height == 0 { ReadConfig.Nsv2height = config.Default.Genesis.FairbankBlockHeight } + if ReadConfig.AnalyserEndpoint == "" { + ReadConfig.AnalyserEndpoint = defaultAnalyserEndpoint + completeness = false + } if !completeness { err := writeConfig() if err != nil { diff --git a/ioctl/config/configsetget.go b/ioctl/config/configsetget.go index 7af3ede535..d6e6d912fc 100644 --- a/ioctl/config/configsetget.go +++ b/ioctl/config/configsetget.go @@ -22,17 +22,18 @@ import ( // Regexp patterns const ( - ipPattern = `((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)` - domainPattern = `[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}(\.[a-zA-Z0-9][a-zA-Z0-9_-]{0,62})*(\.[a-zA-Z][a-zA-Z0-9]{0,10}){1}` - urlPattern = `[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)` - localPattern = "localhost" - endpointPattern = "(" + ipPattern + "|(" + domainPattern + ")" + "|(" + localPattern + "))" + `(:\d{1,5})?` + ipPattern = `((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)` + domainPattern = `[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}(\.[a-zA-Z0-9][a-zA-Z0-9_-]{0,62})*(\.[a-zA-Z][a-zA-Z0-9]{0,10}){1}` + urlPattern = `[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)` + localPattern = "localhost" + endpointPattern = "(" + ipPattern + "|(" + domainPattern + ")" + "|(" + localPattern + "))" + `(:\d{1,5})?` + defaultAnalyserEndpoint = "https://iotex-analyser-api-mainnet.chainanalytics.org" ) var ( supportedLanguage = []string{"English", "中文"} validArgs = []string{"endpoint", "wallet", "explorer", "defaultacc", "language", "nsv2height"} - validGetArgs = []string{"endpoint", "wallet", "explorer", "defaultacc", "language", "nsv2height", "all"} + validGetArgs = []string{"endpoint", "wallet", "explorer", "defaultacc", "language", "nsv2height", "analyserEndpoint", "all"} validExpl = []string{"iotexscan", "iotxplorer"} endpointCompile = regexp.MustCompile("^" + endpointPattern + "$") ) @@ -133,29 +134,25 @@ func Get(arg string) error { } message := endpointMessage{Endpoint: ReadConfig.Endpoint, SecureConnect: ReadConfig.SecureConnect} fmt.Println(message.String()) - return nil case "wallet": output.PrintResult(ReadConfig.Wallet) - return nil case "defaultacc": if ReadConfig.DefaultAccount.AddressOrAlias == "" { return output.NewError(output.ConfigError, "default account did not set", nil) } fmt.Println(ReadConfig.DefaultAccount.String()) - return nil case "explorer": output.PrintResult(ReadConfig.Explorer) - return nil case "language": output.PrintResult(ReadConfig.Language) - return nil case "nsv2height": fmt.Println(ReadConfig.Nsv2height) - return nil + case "analyserEndpoint": + fmt.Println(ReadConfig.AnalyserEndpoint) case "all": fmt.Println(ReadConfig.String()) - return nil } + return nil } // GetContextAddressOrAlias gets current context @@ -230,6 +227,8 @@ func set(args []string) error { } ReadConfig.Endpoint = args[1] ReadConfig.SecureConnect = !Insecure + case "analyserEndpoint": + ReadConfig.AnalyserEndpoint = args[1] case "wallet": ReadConfig.Wallet = args[1] case "explorer": @@ -293,6 +292,7 @@ func reset() error { ReadConfig.DefaultAccount = *new(Context) ReadConfig.Explorer = "iotexscan" ReadConfig.Language = "English" + ReadConfig.AnalyserEndpoint = defaultAnalyserEndpoint err := writeConfig() if err != nil {