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

feat: move standard library initialization to genesis transactions #3168

Draft
wants to merge 118 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
118 commits
Select commit Hold shift + click to select a range
a57e99f
refactor test package
thehowl Nov 13, 2024
80a0420
fixup
thehowl Nov 13, 2024
947435d
ensure to only update correct files
thehowl Nov 13, 2024
530c659
finish up everything
thehowl Nov 13, 2024
30c0ef5
re-enable and simplify debugger tests
thehowl Nov 13, 2024
98b3c91
shrink test execution time to 2 seconds
thehowl Nov 13, 2024
a7f0e84
remove native type mappings
thehowl Nov 13, 2024
63565df
fixup
thehowl Nov 13, 2024
e80c354
Merge branch 'master' of github.com:gnolang/gno into dev/morgan/big-t…
thehowl Nov 13, 2024
197a01c
fixup stuff
thehowl Nov 13, 2024
2f65112
add short flag in gnovm test
thehowl Nov 14, 2024
6c9b5b6
run full tests on master
thehowl Nov 14, 2024
3bf22fb
wat
thehowl Nov 14, 2024
6f90e23
update tests
thehowl Nov 14, 2024
94b2197
fixup fixup
thehowl Nov 14, 2024
dad6992
update example filetests
thehowl Nov 14, 2024
dda4c7c
oopsie
thehowl Nov 14, 2024
d41d5ed
reverting back
thehowl Nov 14, 2024
59d9008
Merge branch 'master' of github.com:gnolang/gno into dev/morgan/big-t…
thehowl Nov 15, 2024
3223bf2
revert back to master examples
thehowl Nov 15, 2024
bcbc211
fixup test
thehowl Nov 15, 2024
d191eed
less strict matching of output
thehowl Nov 15, 2024
5389cf6
avoid eagerly loading realms
thehowl Nov 15, 2024
f6aaa29
finishup
thehowl Nov 16, 2024
c603537
fixup
thehowl Nov 16, 2024
2f65631
fixup
thehowl Nov 18, 2024
ee2b0da
maybe fix all tests?
thehowl Nov 18, 2024
3f9abe1
remove useless test
thehowl Nov 19, 2024
d351434
Merge branch 'master' of github.com:gnolang/gno into dev/morgan/big-t…
thehowl Nov 19, 2024
b236499
add stdlib tests back
thehowl Nov 19, 2024
f497d05
add stdlibs tests back
thehowl Nov 19, 2024
50ff186
oopsie
thehowl Nov 19, 2024
b6f54c2
fixup workflow
thehowl Nov 19, 2024
694ec88
wrong dir
thehowl Nov 19, 2024
9c2f3c2
fix #1084
thehowl Nov 19, 2024
be153b1
remove deadcode
thehowl Nov 19, 2024
f832188
improvements
thehowl Nov 19, 2024
359585a
revert to master state for machine_test.go
thehowl Nov 19, 2024
d98aded
typo fixes
thehowl Nov 19, 2024
c12f6b3
move testing system to pkg/test as well
thehowl Nov 19, 2024
c106800
lint fixes
thehowl Nov 19, 2024
fd3286c
remove more redundancy
thehowl Nov 19, 2024
2e6f1f2
Merge branch 'master' of github.com:gnolang/gno into dev/morgan/big-t…
thehowl Nov 19, 2024
a15aa7b
update txtars
thehowl Nov 19, 2024
d96766d
skip some stdlib testing for now
thehowl Nov 19, 2024
98e4e4f
skip stdlib test in examples workflow
thehowl Nov 19, 2024
f1cfc8e
oopsie
thehowl Nov 19, 2024
8aa9b24
tmp
n0izn0iz Nov 20, 2024
66d3e70
feat: add embedded stdlibs
n0izn0iz Nov 20, 2024
ce564b4
Merge branch 'master' into embed-stdlibs
n0izn0iz Nov 20, 2024
f4138d8
chore: add doc
n0izn0iz Nov 20, 2024
df80f36
chore: rename stuff
n0izn0iz Nov 20, 2024
60c5eeb
Merge branch 'embed-stdlibs' into genesis-stdlibs
n0izn0iz Nov 20, 2024
435a98c
tmp
n0izn0iz Nov 20, 2024
32a47c8
tmp
n0izn0iz Nov 20, 2024
e0f96c1
tmp
n0izn0iz Nov 20, 2024
62f4f21
tmp
n0izn0iz Nov 20, 2024
57749ce
tmp
n0izn0iz Nov 21, 2024
34a52d2
tmp: finish TestStore embed integrationg
n0izn0iz Nov 21, 2024
54d6376
chore: revert test removal
n0izn0iz Nov 21, 2024
f7c4af1
Merge branch 'master' into genesis-stdlibs
n0izn0iz Nov 21, 2024
d776227
tmp
n0izn0iz Nov 21, 2024
1054240
feat: inject stdlibs in testscripts
n0izn0iz Nov 21, 2024
d94c226
fix: properly inject stdlibs txs in testscripts
n0izn0iz Nov 21, 2024
44056eb
chore: update tests
n0izn0iz Nov 21, 2024
fca5da2
chore: update tests
n0izn0iz Nov 21, 2024
4674563
fix: disable namespace check for stdlibs during genesis
n0izn0iz Nov 21, 2024
f9d214e
fix: lint import
n0izn0iz Nov 21, 2024
c2acb22
chore: add blockheight in debug print
n0izn0iz Nov 21, 2024
c83ecd8
fix: give enough gnots to test1 to deploy stdlibs
n0izn0iz Nov 21, 2024
88996bc
fix: use embedded stdlibs in more tests
n0izn0iz Nov 21, 2024
ef0d05f
Merge remote-tracking branch 'origin/master' into genesis-stdlibs
n0izn0iz Nov 21, 2024
1e333e2
fix: txtar tests with injected stdlibs
n0izn0iz Nov 21, 2024
0f9eb5c
chore: revert gnoweb changes
n0izn0iz Nov 21, 2024
3247301
chore: correct comment
n0izn0iz Nov 21, 2024
17ac56b
tmp: increase test timeout
n0izn0iz Nov 21, 2024
b676fc5
fix: gnodev tests
n0izn0iz Nov 21, 2024
b31dac0
tmp: increase gnodev test timeout
n0izn0iz Nov 21, 2024
883b1b0
chore: increase startup delay
n0izn0iz Nov 21, 2024
ab76537
feat: use embedded stdlibs in testenv
n0izn0iz Nov 21, 2024
03965b0
tmp: stricter pkgpath check during genesis
n0izn0iz Nov 22, 2024
b58b9e0
Merge branch 'master' into genesis-stdlibs
n0izn0iz Nov 22, 2024
4f6686f
Merge branch 'master' into genesis-stdlibs
n0izn0iz Nov 23, 2024
73ad347
chore: Merge remote-tracking branch 'morgan/dev/morgan/big-test-refac…
n0izn0iz Nov 23, 2024
8b3f1a4
tmp: fix post merge opti
n0izn0iz Nov 24, 2024
b39cb20
Merge branch 'master' into genesis-stdlibs
n0izn0iz Nov 24, 2024
f936f6c
fix: gnodev mempkg validate
n0izn0iz Nov 24, 2024
3e506b6
feat: only allow stdlib paths for stdlibs
n0izn0iz Nov 24, 2024
d59dd88
tmp: trigger ci
n0izn0iz Nov 24, 2024
37eecb1
Merge branch 'master' of github.com:gnolang/gno into dev/morgan/big-t…
thehowl Nov 25, 2024
9f128d5
Apply code-review changes
thehowl Nov 25, 2024
2e1b5df
better doc
thehowl Nov 25, 2024
d43e5b2
chore: Merge remote-tracking branch 'origin/master' into genesis-stdlibs
n0izn0iz Nov 26, 2024
606a741
chore: Merge remote-tracking branch 'morgan/dev/morgan/big-test-refac…
n0izn0iz Nov 26, 2024
10c4cf4
feat: cache embedded stdlibs mempackages
n0izn0iz Nov 26, 2024
b88761c
feat: use map cache
n0izn0iz Nov 26, 2024
82c4769
tmp: increase test timeout
n0izn0iz Nov 26, 2024
8943a68
Merge branch 'master' into genesis-stdlibs
n0izn0iz Nov 26, 2024
1231f81
chore: Merge remote-tracking branch 'origin/master' into genesis-stdlibs
n0izn0iz Nov 26, 2024
c885024
chore: preallocate slice
n0izn0iz Nov 26, 2024
6ad727e
chore: Merge remote-tracking branch 'origin/master' into genesis-stdlibs
n0izn0iz Dec 1, 2024
53fa02b
fix: remove empty tx
n0izn0iz Dec 1, 2024
1c22718
chore: use constant for testing lib name
n0izn0iz Dec 1, 2024
868f941
chore: preallocate slice
n0izn0iz Dec 1, 2024
6200b27
chore: move constant to a more appropriate place
n0izn0iz Dec 1, 2024
cea9a05
chore: correct doc
n0izn0iz Dec 1, 2024
b934ab2
chore: move fixed values out of loop
n0izn0iz Dec 1, 2024
8539d18
Merge branch 'master' into genesis-stdlibs
n0izn0iz Dec 3, 2024
57acd8e
chore: update embedded test
n0izn0iz Dec 3, 2024
b65420d
feat: optimize stdlibs loading in tests
n0izn0iz Dec 4, 2024
da28696
chore: Merge remote-tracking branch 'origin/master' into genesis-stdlibs
n0izn0iz Dec 4, 2024
a6cbccf
fix: break infinite loop
n0izn0iz Dec 4, 2024
aeff181
chore: Merge remote-tracking branch 'origin/master' into genesis-stdlibs
n0izn0iz Dec 8, 2024
a7939bc
fix: usage after merge
n0izn0iz Dec 8, 2024
80da996
chore: update test
n0izn0iz Dec 8, 2024
50f9cad
fix: domain check
n0izn0iz Dec 8, 2024
a509eee
chore: revert test timeout change
n0izn0iz Dec 8, 2024
2d7d762
fix: correctly check domain for non-stdlibs
n0izn0iz Dec 8, 2024
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
18 changes: 13 additions & 5 deletions contribs/gnodev/pkg/dev/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/gnolang/gno/gno.land/pkg/gnoland/ugnot"
"github.com/gnolang/gno/gno.land/pkg/integration"
"github.com/gnolang/gno/gnovm/pkg/gnomod"
"github.com/gnolang/gno/gnovm/stdlibs"
"github.com/gnolang/gno/tm2/pkg/amino"
tmcfg "github.com/gnolang/gno/tm2/pkg/bft/config"
"github.com/gnolang/gno/tm2/pkg/bft/node"
Expand Down Expand Up @@ -98,6 +99,9 @@ type Node struct {
var DefaultFee = std.NewFee(50000, std.MustParseCoin(ugnot.ValueString(1000000)))

func NewDevNode(ctx context.Context, cfg *NodeConfig) (*Node, error) {
stdlibsDeployer := crypto.MustAddressFromString("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5") // test1, FIXME: replace
Copy link
Member

Choose a reason for hiding this comment

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

This is fixable I think with @Villaquiranm's PR

Copy link
Contributor Author

@n0izn0iz n0izn0iz Nov 26, 2024

Choose a reason for hiding this comment

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

Yeah I think I'll wait on it
EDIT: actually I should probably use the same address as other packages, I will address this before merge

stdlibsTxs := gnoland.LoadEmbeddedStdlibs(stdlibsDeployer, DefaultFee)

mpkgs, err := NewPackagesMap(cfg.PackagesPathList)
if err != nil {
return nil, fmt.Errorf("unable map pkgs list: %w", err)
Expand Down Expand Up @@ -126,7 +130,7 @@ func NewDevNode(ctx context.Context, cfg *NodeConfig) (*Node, error) {
// generate genesis state
genesis := gnoland.GnoGenesisState{
Balances: cfg.BalancesList,
Txs: append(pkgsTxs, cfg.InitialTxs...),
Txs: append(stdlibsTxs, append(pkgsTxs, cfg.InitialTxs...)...),
}

if err := devnode.rebuildNode(ctx, genesis); err != nil {
Expand Down Expand Up @@ -280,14 +284,18 @@ func (n *Node) Reset(ctx context.Context) error {
// Reset starting time
startTime := time.Now()

// Load stdlibs
stdlibsDeployer := crypto.MustAddressFromString("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5") // test1, FIXME: replace
stdlibsTxs := gnoland.LoadEmbeddedStdlibs(stdlibsDeployer, DefaultFee)

// Generate a new genesis state based on the current packages
pkgsTxs, err := n.pkgs.Load(DefaultFee, startTime)
if err != nil {
return fmt.Errorf("unable to load pkgs: %w", err)
}

// Append initialTxs
txs := append(pkgsTxs, n.initialState...)
txs := append(stdlibsTxs, append(pkgsTxs, n.initialState...)...)
genesis := gnoland.GnoGenesisState{
Balances: n.config.BalancesList,
Txs: txs,
Expand Down Expand Up @@ -370,7 +378,9 @@ func (n *Node) getBlockStoreState(ctx context.Context) ([]gnoland.TxWithMetadata
// get current genesis state
genesis := n.GenesisDoc().AppState.(gnoland.GnoGenesisState)

initialTxs := genesis.Txs[n.loadedPackages:] // ignore previously loaded packages
numStdLibs := len(stdlibs.InitOrder()) - 1 // stdlibs count minus testing lib
initialTxs := genesis.Txs[n.loadedPackages+numStdLibs:] // ignore previously loaded packages

state := append([]gnoland.TxWithMetadata{}, initialTxs...)

lastBlock := n.getLatestBlockNumber()
Expand Down Expand Up @@ -491,8 +501,6 @@ func (n *Node) rebuildNode(ctx context.Context, genesis gnoland.GnoGenesisState)
// Setup node config
nodeConfig := newNodeConfig(n.config.TMConfig, n.config.ChainID, n.config.ChainDomain, genesis)
nodeConfig.GenesisTxResultHandler = n.genesisTxResultHandler
// Speed up stdlib loading after first start (saves about 2-3 seconds on each reload).
nodeConfig.CacheStdlibLoad = true
nodeConfig.Genesis.ConsensusParams.Block.MaxGas = n.config.MaxGasPerBlock

// recoverFromError handles panics and converts them to errors.
Expand Down
7 changes: 6 additions & 1 deletion contribs/gnodev/pkg/dev/node_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/gnolang/gno/contribs/gnodev/pkg/events"
"github.com/gnolang/gno/gno.land/pkg/gnoland"
bft "github.com/gnolang/gno/tm2/pkg/bft/types"
"github.com/gnolang/gno/tm2/pkg/crypto"
)

var ErrEmptyState = errors.New("empty state")
Expand Down Expand Up @@ -83,6 +84,10 @@ func (n *Node) MoveBy(ctx context.Context, x int) error {
return nil
}

// Load stdlibs
stdlibsDeployer := crypto.MustAddressFromString("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5") // test1, FIXME: replace
stdlibsTxs := gnoland.LoadEmbeddedStdlibs(stdlibsDeployer, DefaultFee)

// Load genesis packages
pkgsTxs, err := n.pkgs.Load(DefaultFee, n.startTime)
if err != nil {
Expand All @@ -94,7 +99,7 @@ func (n *Node) MoveBy(ctx context.Context, x int) error {
// Create genesis with loaded pkgs + previous state
genesis := gnoland.GnoGenesisState{
Balances: n.config.BalancesList,
Txs: append(pkgsTxs, newState...),
Txs: append(stdlibsTxs, append(pkgsTxs, newState...)...),
}

// Reset the node with the new genesis state.
Expand Down
2 changes: 1 addition & 1 deletion contribs/gnodev/pkg/dev/node_state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func Render(_ string) string { return strconv.Itoa(value) }
func testingContext(t *testing.T) context.Context {
t.Helper()

ctx, cancel := context.WithTimeout(context.Background(), time.Second*7)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
t.Cleanup(cancel)
return ctx
}
2 changes: 1 addition & 1 deletion contribs/gnodev/pkg/dev/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func (pm PackagesMap) Load(fee std.Fee, start time.Time) ([]gnoland.TxWithMetada

// Open files in directory as MemPackage.
memPkg := gno.MustReadMemPackage(modPkg.Dir, modPkg.Name)
if err := memPkg.Validate(); err != nil {
if err := memPkg.Validate(true); err != nil {
return nil, fmt.Errorf("invalid package: %w", err)
}

Expand Down
5 changes: 4 additions & 1 deletion gno.land/cmd/gnoland/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,9 @@ func generateGenesisFile(genesisFile string, pk crypto.PubKey, c *startCfg) erro
return fmt.Errorf("unable to load genesis balances file %q: %w", c.genesisBalancesFile, err)
}

// Load embedded stdlibs
stdlibsTxs := gnoland.LoadEmbeddedStdlibs(genesisDeployAddress, genesisDeployFee)

// Load examples folder
examplesDir := filepath.Join(c.gnoRootDir, "examples")
pkgsTxs, err := gnoland.LoadPackagesFromDir(examplesDir, genesisDeployAddress, genesisDeployFee)
Expand All @@ -407,7 +410,7 @@ func generateGenesisFile(genesisFile string, pk crypto.PubKey, c *startCfg) erro
return fmt.Errorf("unable to load genesis txs file: %w", err)
}

genesisTxs = append(pkgsTxs, genesisTxs...)
genesisTxs = append(stdlibsTxs, append(pkgsTxs, genesisTxs...)...)

// Construct genesis AppState.
gen.AppState = gnoland.GnoGenesisState{
Expand Down
4 changes: 2 additions & 2 deletions gno.land/cmd/gnoland/start_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func TestStart_Lazy(t *testing.T) {
io.SetErr(commands.WriteNopCloser(mockErr))

// Create and run the command
ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancelFn := context.WithTimeout(context.Background(), 20*time.Second)
Copy link
Member

Choose a reason for hiding this comment

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

I organically hate this test :)

Copy link
Member

Choose a reason for hiding this comment

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

It's a constant reminder of the insane tech debt we have, that's preventing us from easily spinning up configurable clusters in unit tests

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As long as it's organic 🥬 ;)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I will try to restore the master value on this with opti

defer cancelFn()

// Set up the command ctx
Expand All @@ -128,7 +128,7 @@ func TestStart_Lazy(t *testing.T) {
})

// Set up the retry ctx
retryCtx, retryCtxCancelFn := context.WithTimeout(ctx, 5*time.Second)
retryCtx, retryCtxCancelFn := context.WithTimeout(ctx, 10*time.Second)
defer retryCtxCancelFn()

// This is a very janky way to verify the node has started.
Expand Down
40 changes: 4 additions & 36 deletions gno.land/pkg/gnoland/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"time"

"github.com/gnolang/gno/gno.land/pkg/sdk/vm"
"github.com/gnolang/gno/gnovm/pkg/gnoenv"
abci "github.com/gnolang/gno/tm2/pkg/bft/abci/types"
"github.com/gnolang/gno/tm2/pkg/bft/config"
bft "github.com/gnolang/gno/tm2/pkg/bft/types"
Expand Down Expand Up @@ -50,8 +49,6 @@ func TestAppOptions(db dbm.DB) *AppOptions {
EventSwitch: events.NewEventSwitch(),
InitChainerConfig: InitChainerConfig{
GenesisTxResultHandler: PanicOnFailingTxResultHandler,
StdlibDir: filepath.Join(gnoenv.RootDir(), "gnovm", "stdlibs"),
CacheStdlibLoad: true,
},
}
}
Expand Down Expand Up @@ -183,7 +180,6 @@ func NewApp(
EventSwitch: evsw,
InitChainerConfig: InitChainerConfig{
GenesisTxResultHandler: PanicOnFailingTxResultHandler,
StdlibDir: filepath.Join(gnoenv.RootDir(), "gnovm", "stdlibs"),
},
}
if skipFailingGenesisTxs {
Expand Down Expand Up @@ -221,14 +217,6 @@ type InitChainerConfig struct {
// Handles the results of each genesis transaction.
GenesisTxResultHandler

// Standard library directory.
StdlibDir string
// Whether to keep a record of the DB operations to load standard libraries,
// so they can be quickly replicated on additional genesis executions.
// This should be used for integration testing, where InitChainer will be
// called several times.
CacheStdlibLoad bool

// These fields are passed directly by NewAppWithOptions, and should not be
// configurable by end-users.
baseApp *sdk.BaseApp
Expand All @@ -243,12 +231,6 @@ func (cfg InitChainerConfig) InitChainer(ctx sdk.Context, req abci.RequestInitCh
start := time.Now()
ctx.Logger().Debug("InitChainer: started")

// load standard libraries; immediately committed to store so that they are
// available for use when processing the genesis transactions below.
cfg.loadStdlibs(ctx)
ctx.Logger().Debug("InitChainer: standard libraries loaded",
"elapsed", time.Since(start))

// load app state. AppState may be nil mostly in some minimal testing setups;
// so log a warning when that happens.
txResponses, err := cfg.loadAppState(ctx, req.AppState)
Expand All @@ -270,24 +252,6 @@ func (cfg InitChainerConfig) InitChainer(ctx sdk.Context, req abci.RequestInitCh
}
}

func (cfg InitChainerConfig) loadStdlibs(ctx sdk.Context) {
// cache-wrapping is necessary for non-validator nodes; in the tm2 BaseApp,
// this is done using BaseApp.cacheTxContext; so we replicate it here.
ms := ctx.MultiStore()
msCache := ms.MultiCacheWrap()

stdlibCtx := cfg.vmKpr.MakeGnoTransactionStore(ctx)
stdlibCtx = stdlibCtx.WithMultiStore(msCache)
if cfg.CacheStdlibLoad {
cfg.vmKpr.LoadStdlibCached(stdlibCtx, cfg.StdlibDir)
} else {
cfg.vmKpr.LoadStdlib(stdlibCtx, cfg.StdlibDir)
}
cfg.vmKpr.CommitGnoTransactionStore(stdlibCtx)

msCache.MultiWrite()
}

func (cfg InitChainerConfig) loadAppState(ctx sdk.Context, appState any) ([]abci.ResponseDeliverTx, error) {
state, ok := appState.(GnoGenesisState)
if !ok {
Expand Down Expand Up @@ -351,6 +315,10 @@ func (cfg InitChainerConfig) loadAppState(ctx sdk.Context, appState any) ([]abci
GasUsed: res.GasUsed,
})

if res.IsErr() {
fmt.Println("failed to exec genesis tx, height", ctx.BlockHeight(), "tx", stdTx, "res", res)
}

cfg.GenesisTxResultHandler(ctx, stdTx, res)
}
return txResponses, nil
Expand Down
112 changes: 14 additions & 98 deletions gno.land/pkg/gnoland/app_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package gnoland

import (
"context"
"errors"
"fmt"
"strings"
Expand All @@ -20,9 +19,6 @@ import (
"github.com/gnolang/gno/tm2/pkg/log"
"github.com/gnolang/gno/tm2/pkg/sdk"
"github.com/gnolang/gno/tm2/pkg/std"
"github.com/gnolang/gno/tm2/pkg/store"
"github.com/gnolang/gno/tm2/pkg/store/dbadapter"
"github.com/gnolang/gno/tm2/pkg/store/iavl"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -147,87 +143,6 @@ func TestNewApp(t *testing.T) {
assert.True(t, resp.IsOK(), "resp is not OK: %v", resp)
}

// Test whether InitChainer calls to load the stdlibs correctly.
func TestInitChainer_LoadStdlib(t *testing.T) {
t.Parallel()

t.Run("cached", func(t *testing.T) { testInitChainerLoadStdlib(t, true) })
t.Run("uncached", func(t *testing.T) { testInitChainerLoadStdlib(t, false) })
}

func testInitChainerLoadStdlib(t *testing.T, cached bool) { //nolint:thelper
t.Parallel()

type gsContextType string
const (
stdlibDir = "test-stdlib-dir"
gnoStoreKey gsContextType = "gno-store-key"
gnoStoreValue gsContextType = "gno-store-value"
)
db := memdb.NewMemDB()
ms := store.NewCommitMultiStore(db)
baseCapKey := store.NewStoreKey("baseCapKey")
iavlCapKey := store.NewStoreKey("iavlCapKey")

ms.MountStoreWithDB(baseCapKey, dbadapter.StoreConstructor, db)
ms.MountStoreWithDB(iavlCapKey, iavl.StoreConstructor, db)
ms.LoadLatestVersion()
testCtx := sdk.NewContext(sdk.RunTxModeDeliver, ms.MultiCacheWrap(), &bft.Header{ChainID: "test-chain-id"}, log.NewNoopLogger())

// mock set-up
var (
makeCalls int
commitCalls int
loadStdlibCalls int
loadStdlibCachedCalls int
)
containsGnoStore := func(ctx sdk.Context) bool {
return ctx.Context().Value(gnoStoreKey) == gnoStoreValue
}
// ptr is pointer to either loadStdlibCalls or loadStdlibCachedCalls
loadStdlib := func(ptr *int) func(ctx sdk.Context, dir string) {
return func(ctx sdk.Context, dir string) {
assert.Equal(t, stdlibDir, dir, "stdlibDir should match provided dir")
assert.True(t, containsGnoStore(ctx), "should contain gno store")
*ptr++
}
}
mock := &mockVMKeeper{
makeGnoTransactionStoreFn: func(ctx sdk.Context) sdk.Context {
makeCalls++
assert.False(t, containsGnoStore(ctx), "should not already contain gno store")
return ctx.WithContext(context.WithValue(ctx.Context(), gnoStoreKey, gnoStoreValue))
},
commitGnoTransactionStoreFn: func(ctx sdk.Context) {
commitCalls++
assert.True(t, containsGnoStore(ctx), "should contain gno store")
},
loadStdlibFn: loadStdlib(&loadStdlibCalls),
loadStdlibCachedFn: loadStdlib(&loadStdlibCachedCalls),
}

// call initchainer
cfg := InitChainerConfig{
StdlibDir: stdlibDir,
vmKpr: mock,
CacheStdlibLoad: cached,
}
cfg.InitChainer(testCtx, abci.RequestInitChain{
AppState: GnoGenesisState{},
})

// assert number of calls
assert.Equal(t, 1, makeCalls, "should call MakeGnoTransactionStore once")
assert.Equal(t, 1, commitCalls, "should call CommitGnoTransactionStore once")
if cached {
assert.Equal(t, 0, loadStdlibCalls, "should call LoadStdlib never")
assert.Equal(t, 1, loadStdlibCachedCalls, "should call LoadStdlibCached once")
} else {
assert.Equal(t, 1, loadStdlibCalls, "should call LoadStdlib once")
assert.Equal(t, 0, loadStdlibCachedCalls, "should call LoadStdlibCached never")
}
}

// generateValidatorUpdates generates dummy validator updates
func generateValidatorUpdates(t *testing.T, count int) []abci.ValidatorUpdate {
t.Helper()
Expand Down Expand Up @@ -287,30 +202,31 @@ func TestInitChainer_MetadataTxs(t *testing.T) {
var (
currentTimestamp = time.Now()
laterTimestamp = currentTimestamp.Add(10 * 24 * time.Hour) // 10 days
stdlibsDeployFee = std.NewFee(50000, std.NewCoin("ugnot", 1000000))

getMetadataState = func(tx std.Tx, balances []Balance) GnoGenesisState {
stdlibs := LoadEmbeddedStdlibs(balances[0].Address, stdlibsDeployFee)

return GnoGenesisState{
// Set the package deployment as the genesis tx
Txs: []TxWithMetadata{
{
Tx: tx,
Metadata: &GnoTxMetadata{
Timestamp: laterTimestamp.Unix(),
},
Txs: append(stdlibs, TxWithMetadata{
Tx: tx,
Metadata: &GnoTxMetadata{
Timestamp: laterTimestamp.Unix(),
},
},
}),
// Make sure the deployer account has a balance
Balances: balances,
}
}

getNonMetadataState = func(tx std.Tx, balances []Balance) GnoGenesisState {
stdlibs := LoadEmbeddedStdlibs(balances[0].Address, stdlibsDeployFee)

return GnoGenesisState{
Txs: []TxWithMetadata{
{
Tx: tx,
},
},
Txs: append(stdlibs, TxWithMetadata{
Tx: tx,
}),
Balances: balances,
}
}
Expand Down Expand Up @@ -396,7 +312,7 @@ func TestInitChainer_MetadataTxs(t *testing.T) {
{
// Make sure the deployer account has a balance
Address: key.PubKey().Address(),
Amount: std.NewCoins(std.NewCoin("ugnot", 20_000_000)),
Amount: std.NewCoins(std.NewCoin("ugnot", 20_000_000_000)),
},
}),
})
Expand Down
Loading
Loading