Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[state] convert clean address to zero-nonce type #3991

Merged
merged 6 commits into from
Jan 17, 2024

Conversation

dustinxie
Copy link
Member

Description

If a legacy account has never initiated an outgoing tx, we convert it to a zero-nonce type account. This enables us to do deterministic deployment

Fixes #(issue)

Type of change

Please delete options that are not relevant.

  • [] Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • [] Code refactor or improvement
  • [] Breaking change (fix or feature that would cause a new or changed behavior of existing functionality)
  • [] This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

  • make test
  • fullsync
  • [] Other test (please specify)

Test Configuration:

  • Firmware version:
  • Hardware:
  • Toolchain:
  • SDK:

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

state/account.go Outdated Show resolved Hide resolved
Copy link
Collaborator

@CoderZhi CoderZhi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as discussed, this feature could be deleted after hardfork if the accountType is updated from 0 to 1

@@ -66,6 +66,7 @@ func (p *Protocol) handleTransfer(ctx context.Context, tsf *action.Transfer, sm

if fCtx.FixGasAndNonceUpdate || tsf.Nonce() != 0 {
// update sender Nonce
sender.CheckConvertToZeroNonceType(tsf.Nonce())
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't need a hard-fork flag here, b/c this would only happen after the hard-fork when the nonce of clean address is changed by AdjustNonceForCleanAddress() to 0
for now, the first nonce of a clean address remains == 1, so this does no harm

@dustinxie
Copy link
Member Author

just realized more changes are needed for evmstateadaptor.GetNonce/SetNonce, since inside evm.Create it also calls those 2, will update later

Copy link

codecov bot commented Nov 30, 2023

Codecov Report

Attention: 590 lines in your changes are missing coverage. Please review.

Comparison is base (e1f0636) 75.38% compared to head (122d409) 76.18%.
Report is 156 commits behind head on master.

Files Patch % Lines
blockindex/contractstaking/event_handler.go 67.23% 45 Missing and 13 partials ⚠️
action/protocol/staking/staking_statereader.go 69.76% 35 Missing and 17 partials ⚠️
action/protocol/execution/evm/evm.go 48.38% 47 Missing and 1 partial ⚠️
api/coreservice.go 62.74% 33 Missing and 5 partials ⚠️
api/web3server.go 79.24% 30 Missing and 3 partials ⚠️
action/candidate_endorsement.go 0.00% 31 Missing ⚠️
action/protocol/staking/protocol.go 33.33% 28 Missing ⚠️
action/candidate_activate.go 0.00% 25 Missing ⚠️
...tion/protocol/staking/contractstake_bucket_type.go 0.00% 24 Missing ⚠️
action/protocol/rewarding/fund.go 23.07% 19 Missing and 1 partial ⚠️
... and 36 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3991      +/-   ##
==========================================
+ Coverage   75.38%   76.18%   +0.80%     
==========================================
  Files         303      337      +34     
  Lines       25923    28731    +2808     
==========================================
+ Hits        19541    21888    +2347     
- Misses       5360     5731     +371     
- Partials     1022     1112      +90     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

return nonce, err
}
g := core.Genesis()
if nonce > 1 || !g.IsSumatra(core.TipHeight()) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why IsSumatra? what's the difference from UseZeroNonceForFreshAccount?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IsSumatra() is the same flag as UseZeroNonceForFreshAccount , here we don't have a ctx

API service does not affect past blocks, so after the hard-fork, this check will be removed

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if so, be consistent with g.IsToBeEnabled(core.TipHeight())

@@ -344,6 +345,9 @@ func (stateDB *StateDBAdapter) GetNonce(evmAddr common.Address) uint64 {
}
pendingNonce--
}
if pendingNonce == 1 && stateDB.convertFreshAddress {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we remove pendingNonce == 1? same question for all the other places making a similar check outside of function AdjustNonceForFreshAccount

state/account.go Outdated
@@ -178,6 +187,16 @@ func (st *Account) PendingNonce() uint64 {
}
}

// AdjustNonceForFreshAccount adjust the nonce for a fresh legacy account
func (st *Account) AdjustNonceForFreshAccount(nonce uint64) uint64 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better to be a util function, instead of a struct function

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change the name to make it more correct

action/protocol/staking/protocol.go Outdated Show resolved Hide resolved
@@ -66,6 +66,7 @@ func (p *Protocol) handleTransfer(ctx context.Context, tsf *action.Transfer, sm

if fCtx.FixGasAndNonceUpdate || tsf.Nonce() != 0 {
// update sender Nonce
sender.ConvertFreshAccountToZeroNonceType(tsf.Nonce())
Copy link
Member

@Liuhaai Liuhaai Dec 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if acc.IsNewbieAccount() && acc.AccountType() == 0 && useZeroNonce {
	acc.ConvertFreshAccountToZeroNonceType()
}
// Make sure the value matches if acc.PendingNonce() is called

Other places related to setpendingnonce/pendingnonce are similar

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

acc.IsNewbieAccount() && acc.AccountType() == 0 is duplicate with what's checked inside ConvertFreshAccountToZeroNonceType

added the useZeroNonce flag check

action/protocol/execution/evm/evmstatedbadapter.go Outdated Show resolved Hide resolved
action/protocol/execution/evm/evmstatedbadapter.go Outdated Show resolved Hide resolved
return nonce, err
}
g := core.Genesis()
if nonce > 1 || !g.IsSumatra(core.TipHeight()) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if so, be consistent with g.IsToBeEnabled(core.TipHeight())

@@ -366,7 +370,11 @@ func (ws *workingSet) checkNonceContinuity(ctx context.Context, accountNonceMap
return errors.Wrapf(err, "failed to get the confirmed nonce of address %s", srcAddr)
}
sort.Slice(receivedNonces, func(i, j int) bool { return receivedNonces[i] < receivedNonces[j] })
pendingNonce := confirmedState.PendingNonce()
if useZeroNonce {
pendingNonce = confirmedState.PendingNonceConsideringFreshAccount()
Copy link
Member

@Liuhaai Liuhaai Dec 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PendingNonceConsideringFreshAccount is conditional? The name indicates the judging is done inside the func

@@ -178,6 +187,16 @@ func (st *Account) PendingNonce() uint64 {
}
}

// PendingNonceConsideringFreshAccount return the pending nonce considering fresh legacy account
func (st *Account) PendingNonceConsideringFreshAccount() uint64 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about naming it PendingNonce() and renaming the original LegacyPendingNonce()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SetPendingNonce() should also be updated for this change

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PendingNonce has too many uses in the code
if we want to do this, can do in a separate PR

@@ -175,3 +175,45 @@ func TestClone(t *testing.T) {
require.Equal(big.NewInt(200), ss.Balance)
require.Equal(big.NewInt(200+100), account.Balance)
}

func TestConvertFreshAddress(t *testing.T) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e2etest is also required to check working well in evm

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added in latest commit

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added in latest commit

api/coreservice.go Outdated Show resolved Hide resolved
make([]byte, 4),
uint64(200000), big.NewInt(1),
TsfSuccess, "",
"Transfer with nonce 0",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why behavior changes when this feature not enabled

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the test is "transfer with nonce 0". Before enable this, legacy account first tx has nonce=1, so the test will fail. Now with this feature enabled, the first tx can have nonce=0 so the test can pass

} {
a, err := accountutil.AccountState(ctx, sf, v.a)
require.NoError(err)
require.EqualValues(1, a.AccountType())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add case to check if first tx nonce==1

@@ -66,6 +66,9 @@ func (p *Protocol) handleTransfer(ctx context.Context, tsf *action.Transfer, sm

if fCtx.FixGasAndNonceUpdate || tsf.Nonce() != 0 {
// update sender Nonce
if fCtx.UseZeroNonceForFreshAccount {
sender.ConvertFreshAccountToZeroNonceType(tsf.Nonce())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe can do before protocol.Handle

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see latest commit

return nil, errors.Wrapf(err, "failed to store converted sender %s", actCtx.Caller.String())
}
}
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do the check/conversion before action.Handle()

@@ -66,9 +66,6 @@ func (p *Protocol) handleTransfer(ctx context.Context, tsf *action.Transfer, sm

if fCtx.FixGasAndNonceUpdate || tsf.Nonce() != 0 {
// update sender Nonce
if fCtx.UseZeroNonceForFreshAccount {
sender.ConvertFreshAccountToZeroNonceType(tsf.Nonce())
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert change in 1st commit

@@ -405,9 +405,6 @@ func prepareStateDB(ctx context.Context, sm protocol.StateManager) (*StateDBAdap
if !featureCtx.CorrectGasRefund {
opts = append(opts, ManualCorrectGasRefundOption())
}
if featureCtx.UseZeroNonceForFreshAccount {
opts = append(opts, ConvertFreshAddressOption())
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert change in 1st commit

@@ -373,9 +358,6 @@ func (stateDB *StateDBAdapter) SetNonce(evmAddr common.Address, nonce uint64) {
log.L().Debug("Called SetNonce.",
zap.String("address", addr.String()),
zap.Uint64("nonce", nonce))
if stateDB.convertFreshAddress {
s.ConvertFreshAccountToZeroNonceType(nonce)
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert change in 1st commit

accountCreationOpts = append(accountCreationOpts, state.LegacyNonceAccountTypeOption())
}
acc, err := accountutil.LoadOrCreateAccount(sm, addr, accountCreationOpts...)
if err != nil {
return err
}
if !skipSetNonce {
if fCtx.UseZeroNonceForFreshAccount {
acc.ConvertFreshAccountToZeroNonceType(nonce)
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert change in 1st commit

accountCreationOpts = append(accountCreationOpts, state.LegacyNonceAccountTypeOption())
}
acc, err := accountutil.LoadAccount(sm, actionCtx.Caller, accountCreationOpts...)
if err != nil {
return nil, err
}
if fCtx.UseZeroNonceForFreshAccount {
acc.ConvertFreshAccountToZeroNonceType(actionCtx.Nonce)
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert change in 1st commit

balance = new(big.Int).Set(confirmedState.Balance)
acts = make([]action.SealedEnvelope, 0, len(q.items))
)
q.mu.RLock()
defer q.mu.RUnlock()
if confirmedState.IsLegacyFreshAccount() && nonce == 0 {
// for a legacy fresh account, the nonce of first tx could be either 0 or 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The nonce of 1st tx is undeterministic

Copy link
Member Author

@dustinxie dustinxie Jan 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated in latest commit

Copy link
Collaborator

@CoderZhi CoderZhi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's further simplify the logic to: "the nonce of the first action for a fresh account with legacy type could only be 0 after hard fork no matter how". The only problem for the simplified logic is that a fresh account with legacy type may send an action of nonce 1 may need to resend an action of nonce 0, which is not a big problem.

state/account.go Outdated
@@ -166,6 +171,15 @@ func (st *Account) SetPendingNonce(nonce uint64) error {
return nil
}

// ConvertFreshAccountToZeroNonceType converts a fresh legacy account to zero-nonce account
func (st *Account) ConvertFreshAccountToZeroNonceType(nonce uint64) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete parameter nonce

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is to make sure the conversion only happens for a tx with nonce = 0

@dustinxie
Copy link
Member Author

let's further simplify the logic to: "the nonce of the first action for a fresh account with legacy type could only be 0 after hard fork no matter how". The only problem for the simplified logic is that a fresh account with legacy type may send an action of nonce 1 may need to resend an action of nonce 0, which is not a big problem.

yes updated this in latest commit

return nonce, err
}
g := core.Genesis()
if nonce > 1 || !g.IsToBeEnabled(core.TipHeight()) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nonce returned in line 494 is from ap. if nonce == 1 && after hard fork, shall we return 1?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in latest commit

@@ -166,6 +171,17 @@ func (st *Account) SetPendingNonce(nonce uint64) error {
return nil
}

// ConvertFreshAccountToZeroNonceType converts a fresh legacy account to zero-nonce account
func (st *Account) ConvertFreshAccountToZeroNonceType(nonce uint64) bool {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could this conversion be moved to SetPendingNonce as:

    switch st.accountType {
    case 1: ...
    case 0:
        if st.accountType == 0 && st.nonce == 0 && nonce == 1 {
            st.accountType = 1
        } else {
            ....
        }
    default:
        ...
    }
    st.nonce++

The hard fork feature and nonce has been checked in checkNonceContinuity, thus we can delete this function as well as the place calling it

Copy link
Member Author

@dustinxie dustinxie Jan 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's very hard to do insideSetPendingNonce alone, because EVM use emvstateadaptor's GetNonce and SetNonce to access the nonce value.
In order to achieve nonce == 1 in the example you gave, we'll need add code inside GetNonce and SetNonce -- which is basically the code moved to workingset.go in commit c03396e

@Liuhaai
Copy link
Member

Liuhaai commented Jan 15, 2024

I prefer changes around /action/protocol/account/util/util.go, but the current implementation is acceptable for me

Copy link
Collaborator

@CoderZhi CoderZhi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three places could be changed to achieve the conversion:

  1. When returning a confirmed state of an account, passing the hard fork symbol
  2. Modify account.PendingNonce returns the right pending nonce
  3. SetPendingNonce sets the right pending nonce and modify the account type accordingly

This PR tries to resolve the problem by modifying the process but not the object containing the feature. We need a followup PR to do it in an OO way.

Copy link

sonarcloud bot commented Jan 17, 2024

Quality Gate Passed Quality Gate passed

The SonarCloud Quality Gate passed, but some issues were introduced.

1 New issue
0 Security Hotspots
No data about Coverage
2.4% Duplication on New Code

See analysis details on SonarCloud

@dustinxie dustinxie merged commit dbd7a5b into iotexproject:master Jan 17, 2024
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants