Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions persistence/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type PostgresContext struct {
// Need to simply access them via the bus.
blockStore blockstore.BlockStore
txIndexer indexer.TxIndexer
stateTrees *stateTrees
stateTrees modules.TreeStore

networkId string
}
Expand All @@ -50,7 +50,7 @@ func (p *PostgresContext) RollbackToSavePoint(bytes []byte) error {
// IMPROVE(#361): Guarantee the integrity of the state
// Full details in the thread from the PR review: https://github.com/pokt-network/pocket/pull/285#discussion_r1018471719
func (p *PostgresContext) ComputeStateHash() (string, error) {
stateHash, err := p.updateMerkleTrees()
stateHash, err := p.stateTrees.Update(p.tx, p.txIndexer, uint64(p.Height))
if err != nil {
return "", err
}
Expand Down
15 changes: 1 addition & 14 deletions persistence/debug.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package persistence

import (
"crypto/sha256"
"runtime/debug"

"github.com/pokt-network/pocket/persistence/types"
"github.com/pokt-network/pocket/shared/messaging"
"github.com/pokt-network/smt"
)

// A list of functions to clear data from the DB not associated with protocol actors
Expand Down Expand Up @@ -118,16 +116,5 @@ func (p *PostgresContext) clearAllSQLState() error {
}

func (p *PostgresContext) clearAllTreeState() error {
for treeType := merkleTree(0); treeType < numMerkleTrees; treeType++ {
nodeStore := p.stateTrees.nodeStores[treeType]

if err := nodeStore.ClearAll(); err != nil {
return err
}

// Needed in order to make sure the root is re-set correctly after clearing
p.stateTrees.merkleTrees[treeType] = smt.NewSparseMerkleTree(nodeStore, sha256.New())
}

return nil
return p.stateTrees.DebugClearAll()
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The code patch provided removes some imports and modifies the clearAllTreeState function. Here's a brief review:

  1. Removed imports:

    • The "crypto/sha256" and "github.com/pokt-network/smt" imports are removed as they are no longer needed.
  2. Modified clearAllTreeState function:

    • The for loop is removed that iterated over all trees (numMerkleTrees), clearing each node store, and then created a new SparseMerkleTree with the cleared node store.
    • Instead, a single call to p.stateTrees.DebugClearAll() is made, which is presumably the intended refactoring to delegate this job to another function in the stateTrees object.

Potential risks or suggestions for improvement:

  1. Ensure proper implementation of the DebugClearAll() method: Make sure that the DebugClearAll() function within the stateTrees object has the correct implementation and properly clears data as intended, similar to the removed for loop.

  2. Remove magic numbers: Instead of using merkleTree(0) directly, consider introducing a constant or enum to represent the starting tree index more clearly.

  3. Test thoroughly: Thoroughly test the functionality after applying the changes to ensure correctness and stability.

Overall, the code change appears to streamline the process of clearing trees, potentially improving maintainability.

5 changes: 5 additions & 0 deletions persistence/docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.0.0.58] - 2023-06-14

- Refactors the stateTrees implementation off of the PersistenceContext and into its in module
- Implements the new Update and Commit pattern with the SMT trees in the trees module

## [0.0.0.57] - 2023-06-06

- Uses ":memory:" to signify when connecting to an in-memory database
Expand Down
52 changes: 0 additions & 52 deletions persistence/gov.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/pokt-network/pocket/logger"
"github.com/pokt-network/pocket/persistence/types"
"github.com/pokt-network/pocket/runtime/genesis"
coreTypes "github.com/pokt-network/pocket/shared/core/types"
"github.com/pokt-network/pocket/shared/modules"
)

Expand Down Expand Up @@ -156,48 +155,6 @@ func getParamOrFlag[T int | string | []byte](p *PostgresContext, tableName, para
return
}

func (p *PostgresContext) getParamsUpdated(height int64) ([]*coreTypes.Param, error) {
ctx, tx := p.getCtxAndTx()
// Get all parameters / flags at current height
rows, err := tx.Query(ctx, p.getParamsOrFlagsUpdateAtHeightQuery(types.ParamsTableName, height))
if err != nil {
return nil, err
}
defer rows.Close()
var paramSlice []*coreTypes.Param // Store returned rows
// Loop over all rows returned and load them into the ParamOrFlag struct array
for rows.Next() {
param := new(coreTypes.Param)
if err := rows.Scan(&param.Name, &param.Value); err != nil {
return nil, err
}
param.Height = height
paramSlice = append(paramSlice, param)
}
return paramSlice, nil
}

func (p *PostgresContext) getFlagsUpdated(height int64) ([]*coreTypes.Flag, error) {
ctx, tx := p.getCtxAndTx()
// Get all parameters / flags at current height
rows, err := tx.Query(ctx, p.getParamsOrFlagsUpdateAtHeightQuery(types.FlagsTableName, height))
if err != nil {
return nil, err
}
defer rows.Close()
var flagSlice []*coreTypes.Flag // Store returned rows
// Loop over all rows returned and load them into the ParamOrFlag struct array
for rows.Next() {
flag := new(coreTypes.Flag)
if err := rows.Scan(&flag.Name, &flag.Value, &flag.Enabled); err != nil {
return nil, err
}
flag.Height = height
flagSlice = append(flagSlice, flag)
}
return flagSlice, nil
}

// GetAllParams returns a map of the current latest updated values for all parameters
// and their values in the form map[parameterName] = parameterValue
func (p *PostgresContext) GetAllParams() ([][]string, error) {
Expand All @@ -219,15 +176,6 @@ func (p *PostgresContext) GetAllParams() ([][]string, error) {
return paramSlice, nil
}

func (p *PostgresContext) getParamsOrFlagsUpdateAtHeightQuery(tableName string, height int64) string {
fields := "name,value"
if tableName == types.FlagsTableName {
fields += ",enabled"
}
// Build correct query to get all Params/Flags at certain height ordered by their name values
return fmt.Sprintf("SELECT %s FROM %s WHERE height=%d ORDER BY name ASC", fields, tableName, height)
}

func (p *PostgresContext) getLatestParamsOrFlagsQuery(tableName string) string {
fields := "name,value"
if tableName == types.FlagsTableName {
Expand Down
19 changes: 13 additions & 6 deletions persistence/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/pokt-network/pocket/logger"
"github.com/pokt-network/pocket/persistence/blockstore"
"github.com/pokt-network/pocket/persistence/indexer"
"github.com/pokt-network/pocket/persistence/trees"
"github.com/pokt-network/pocket/runtime/configs"
"github.com/pokt-network/pocket/runtime/genesis"
"github.com/pokt-network/pocket/shared/modules"
Expand Down Expand Up @@ -36,13 +37,14 @@ type persistenceModule struct {
// A key-value store mapping heights to blocks. Needed for block synchronization.
blockStore blockstore.BlockStore

// A tx indexer (i.e. key-value store) mapping transaction hashes to transactions. Needed for
// avoiding tx replays attacks, and is also used as the backing database for the transaction
// tx merkle tree.
// txIndexer is a key-value store mapping transaction hashes to `IndexedTransaction` protos.
// It is needed to avoid tx replay attacks and for business logic around transaction validation.
// IMPORTANT: It doubles as the data store for the transaction tree in state tree set.
txIndexer indexer.TxIndexer

// A list of all the merkle trees maintained by the persistence module that roll up into the state commitment.
stateTrees *stateTrees
// stateTrees manages all of the merkle trees maintained by the
// persistence module that roll up into the state commitment.
stateTrees modules.TreeStore

// Only one write context is allowed at a time
writeContext *PostgresContext
Expand Down Expand Up @@ -102,7 +104,8 @@ func (*persistenceModule) Create(bus modules.Bus, options ...modules.ModuleOptio
return nil, err
}

stateTrees, err := newStateTrees(persistenceCfg.TreesStoreDir)
// TECHDEBT (#808): Make TreeStore into a full Module
stateTrees, err := trees.NewStateTrees(persistenceCfg.TreesStoreDir)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -234,6 +237,10 @@ func (m *persistenceModule) GetTxIndexer() indexer.TxIndexer {
return m.txIndexer
}

func (m *persistenceModule) GetTreeStore() modules.TreeStore {
return m.stateTrees
}

func (m *persistenceModule) GetNetworkID() string {
return m.networkId
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Overall, the code patch seems to make reasonable updates to the persistenceModule struct and its functions. However, below are a few suggestions that might improve maintainability and reduce risks:

  1. Documentation: Ensure that comments accurately reflect any changes made in the code. For instance, the addition of the new import statement can be documented.

  2. Verify the designed behavior: Double-check that the modification of the stateTrees definition from type *stateTrees to modules.TreeStore is consistent with other parts of the application dealing with stateTrees.

  3. Keep naming conventions consistent: The naming convention for some variables may not be consistent. Consider renaming networkId to networkID, which follows Go's initialism casing recommendations.

  4. Test coverage: Ensure that the existing tests are updated to cover new changes adequately, or add new test cases for this refactored code path if necessary.

Remember that these suggestions only serve as general guidelines. To ensure the stability of your project, you should always have a thorough understanding of the entire codebase and perform proper risk assessment for potential bugs or issues.

Expand Down
35 changes: 35 additions & 0 deletions persistence/sql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# SQL Package

The SQL package is a library of functions that all take a `pgx.Tx` as an argument and execute SQL queries on it.

- GetAccountsUpdated
- GetActors
- GetTransactions
- GetPools
- GetAccounts
- GetFlags
- GetParams

These functions are meant to abstract away the SQL row and error handling for components of the persistence package.

GetActors is used to get each of the actor types in the system: Applications, Validators, Watchers, and Servicers.

## Why a whole package?

If the SQL handling lives in the persistence package, the package submodules will run into import cycle errors when attempting to use the SQL handlers. Putting the SQL helpers into a package inside persistence avoids the import cycle.

```mermaid
flowchart TD
subgraph pers[persistence]
subgraph p[ without sql package - import cycle error ]
persistenceContext1[PersistenceContext]
treeStore1[TreeStore]
treeStore1 -- Tx --> persistenceContext1
persistenceContext1 -- Tx --> treeStore1
end
subgraph p2[ with sql package - refactored ]
persistenceContext -- Tx --> sql
treeStore2 -- Tx --> sql
end
end
```
Comment on lines +21 to +35
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@Olshansk the import cycle issue is described here.

Copy link
Copy Markdown
Collaborator

@Olshansk Olshansk Jun 16, 2023

Choose a reason for hiding this comment

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

Screenshot 2023-06-16 at 4 18 32 PM

I'm in full support of this :)

Loading