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

implement logic to build genesis state for the sequencer #2371

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

rianhughes
Copy link
Contributor

@rianhughes rianhughes commented Jan 13, 2025

This PR implements the genesis pkg that builds a state diff from declaring classes, deploying contracts and invoking functions. The sequencer can then commit this state diff to state, so that upon startup, a set of account contracts have already been deployed and funded (it is not possible to achieve this from an empty state by submitting transactions, since Starknet requires accounts to be funded to perform any actions on the state - originally this wasn't a requirement in Starknet). This is particularly useful as it allows users to start the sequencer with any number of accounts pre-deployed, and pre-funded, etc, and opens up the possibility of using Juno as a devnet

In essence:

  1. we load classes, then declare them,
  2. execute the constructor functions using the vm, which writes the changes to the pending state
  3. execute any functions of interest (eg token transfers) using the vm (where similarly the vm writes the changes to the pending state)
  4. extract the state-diff and new classes from the pending state.

@rianhughes rianhughes marked this pull request as draft January 13, 2025 12:29
Comment on lines +65 to +71
for k, v := range aux.Contracts {
key, err := new(felt.Felt).SetString(k)
if err != nil {
return err
}
g.Contracts[*key] = v
}
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think we need to do dereferencing? Just do:

	for k, v := range aux.Contracts {
                var key felt.Felt
		key, err = key.SetString(k)
		if err != nil {
			return err
		}
		g.Contracts[key] = v
	}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah right, in your approach key is allocated to the stack and not the heap, whereas in the original case key is allocated to the heap?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is the motivation for this change so that key is allocated to the stack rather than the heap?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The suggested change doesn't work, since SetString only operates on a pointer
func (z *Felt) SetString(number string) (*Felt, error) {
and initialising a nil pointer will result in a panic when calling SetString (ie using var key *felt.Felt)

@rianhughes rianhughes force-pushed the feature/sequencer-genesis branch from fb11e07 to 459db5d Compare January 13, 2025 14:37
@rianhughes rianhughes marked this pull request as ready for review January 13, 2025 14:38
Copy link

codecov bot commented Jan 13, 2025

Codecov Report

Attention: Patch coverage is 65.08475% with 103 lines in your changes missing coverage. Please review.

Project coverage is 74.51%. Comparing base (d99e28b) to head (aad7fc7).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
genesis/genesis.go 64.94% 42 Missing and 19 partials ⚠️
adapters/vm2core/vm2core.go 56.09% 14 Missing and 4 partials ⚠️
sync/pending.go 68.00% 14 Missing and 2 partials ⚠️
core/state_update.go 73.91% 5 Missing and 1 partial ⚠️
node/throttled_vm.go 60.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2371      +/-   ##
==========================================
- Coverage   74.70%   74.51%   -0.19%     
==========================================
  Files         110      111       +1     
  Lines       12021    12313     +292     
==========================================
+ Hits         8980     9175     +195     
- Misses       2349     2419      +70     
- Partials      692      719      +27     

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

genesis/genesis.go Outdated Show resolved Hide resolved
core/state_update.go Outdated Show resolved Hide resolved
@@ -39,3 +40,52 @@ func AdaptOrderedEvents(events []vm.OrderedEvent) []*core.Event {
})
return utils.Map(events, AdaptOrderedEvent)
}

func AdaptStateDiff(trace *vm.TransactionTrace) *core.StateDiff {
Copy link
Contributor

Choose a reason for hiding this comment

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

As I can see we only use trace.StateDiff in this function, why do we pass trace as a parameter?

Comment on lines +100 to +101
newNonce := new(felt.Felt).SetUint64(1)
p.stateDiff.Nonces[*contractAddress] = newNonce.Add(currentNonce, newNonce)
Copy link
Contributor

Choose a reason for hiding this comment

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

We have felt.Zero, can we have felt.One?

Suggested change
newNonce := new(felt.Felt).SetUint64(1)
p.stateDiff.Nonces[*contractAddress] = newNonce.Add(currentNonce, newNonce)
p.stateDiff.Nonces[*contractAddress] = currentNonce.Add(currentNonce, &felt.One)

}

func (p *PendingStateWriter) SetCompiledClassHash(classHash, compiledClassHash *felt.Felt) error {
// assumption: SetContractClass was called for classHash and succeeded
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we make these assumptions a part of the function’s doc comment?

Copy link
Contributor

@AnkushinDaniil AnkushinDaniil left a comment

Choose a reason for hiding this comment

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

I have finished reviewing everything except vm logic. Everything is good, just small changes and questions. I'll continue reviewing vm logic.

return nil
}
stateDiff := trace.StateDiff
newStorageDiffs := make(map[felt.Felt]map[felt.Felt]*felt.Felt)
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we could reduce memory allocation this way

Suggested change
newStorageDiffs := make(map[felt.Felt]map[felt.Felt]*felt.Felt)
newStorageDiffs := make(map[felt.Felt]map[felt.Felt]*felt.Felt, len(stateDiff.StorageDiffs))

Comment on lines +43 to +51
mergeStorageDiffs := func(oldMap, newMap map[felt.Felt]map[felt.Felt]*felt.Felt) {
for addr, newAddrStorage := range newMap {
if oldAddrStorage, exists := oldMap[addr]; exists {
maps.Copy(oldAddrStorage, newAddrStorage)
} else {
oldMap[addr] = newAddrStorage
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Could we just inline this function?

Comment on lines +52 to +59
type auxConfig struct {
Classes []string `json:"classes"` // []path-to-class.json
Contracts map[string]GenesisContractData `json:"contracts"` // address -> {classHash, constructorArgs}
FunctionCalls []FunctionCall `json:"function_calls"` // list of functionCalls to Call()
BootstrapAccounts []Account `json:"bootstrap_accounts"` // accounts to prefund with strk token
Txns []*rpc.Transaction `json:"transactions"` // declare NOT supported
}
var aux auxConfig
Copy link
Contributor

Choose a reason for hiding this comment

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

As I can see, we use auxConfig once.

Suggested change
type auxConfig struct {
Classes []string `json:"classes"` // []path-to-class.json
Contracts map[string]GenesisContractData `json:"contracts"` // address -> {classHash, constructorArgs}
FunctionCalls []FunctionCall `json:"function_calls"` // list of functionCalls to Call()
BootstrapAccounts []Account `json:"bootstrap_accounts"` // accounts to prefund with strk token
Txns []*rpc.Transaction `json:"transactions"` // declare NOT supported
}
var aux auxConfig
var aux struct {
Classes []string `json:"classes"` // []path-to-class.json
Contracts map[string]GenesisContractData `json:"contracts"` // address -> {classHash, constructorArgs}
FunctionCalls []FunctionCall `json:"function_calls"` // list of functionCalls to Call()
BootstrapAccounts []Account `json:"bootstrap_accounts"` // accounts to prefund with strk token
Txns []*rpc.Transaction `json:"transactions"` // declare NOT supported
}

Comment on lines +91 to +92
validate := validator.Validator()
return validate.Struct(g)
Copy link
Contributor

@AnkushinDaniil AnkushinDaniil Jan 16, 2025

Choose a reason for hiding this comment

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

Can we inline validate?

Suggested change
validate := validator.Validator()
return validate.Struct(g)
return validator.Validator().Struct(g)

Comment on lines +115 to +126
for classHash, class := range newClasses {
// Sets pending.newClasses, DeclaredV0Classes, (not DeclaredV1Classes)
if err = genesisState.SetContractClass(&classHash, class); err != nil {
return nil, nil, fmt.Errorf("declare v0 class: %v", err)
}

if cairo1Class, isCairo1 := class.(*core.Cairo1Class); isCairo1 {
if err = genesisState.SetCompiledClassHash(&classHash, cairo1Class.Compiled.Hash()); err != nil {
return nil, nil, fmt.Errorf("set compiled class hash: %v", err)
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Could we use descriptive variable names instead of this comment?

// Sets pending.newClasses, DeclaredV0Classes, (not DeclaredV1Classes)

I don't quite understand why only DeclaredV0Classes in newClasses.

}

default:
panic("transaction type not supported")
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
panic("transaction type not supported")
return nil, nil, fmt.Errorf("unsupported transaction type: %v", txn.Type)

Comment on lines +216 to +218
fmt.Println("==")
fmt.Println(genesisSD)
fmt.Println(traceSD)
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
fmt.Println("==")
fmt.Println(genesisSD)
fmt.Println(traceSD)

Comment on lines +244 to +248
} else if compiledClass, cErr := compiler.Compile(response.V1); cErr != nil {
return nil, cErr
} else if coreClass, err = sn2core.AdaptCairo1Class(response.V1, compiledClass); err != nil {
return nil, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this code is easier to understand

Suggested change
} else if compiledClass, cErr := compiler.Compile(response.V1); cErr != nil {
return nil, cErr
} else if coreClass, err = sn2core.AdaptCairo1Class(response.V1, compiledClass); err != nil {
return nil, err
}
} else {
var compiledClass *starknet.CompiledClass
if compiledClass, err = compiler.Compile(response.V1); err != nil {
return nil, err
}
if coreClass, err = sn2core.AdaptCairo1Class(response.V1, compiledClass); err != nil {
return nil, err
}
}

Comment on lines +137 to +138
// StateDiffAndClasses returns the pending state's internal data. The returned objects will continue to be
// read and modified by the pending state.
Copy link
Contributor

Choose a reason for hiding this comment

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

If so, could we make these fields public?

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.

3 participants