Skip to content
Open
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
10 changes: 10 additions & 0 deletions tests/sdk_tests/config/sdk_tests_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
block_worker: https://dev.zus.network/dns
default_test_case_timeout: 45s
signature_scheme: bls0chain
chain_id: 0afc093ffb509f059c55478bc1a60351cef7b4e9c008a53a6cc8241ca8617dfe
max_txn_query: 5
query_sleep_time: 5
min_submit: 10
min_confirmation: 10
# Test wallet mnemonics for multi-wallet testing
test_wallet_mnemonics: "cactus panther essence ability copper fox wise actual need cousin boat uncover ride diamond group jacket anchor current float rely tragic omit child payment"
40,018 changes: 40,018 additions & 0 deletions tests/sdk_tests/config/wallets.json

Large diffs are not rendered by default.

106 changes: 106 additions & 0 deletions tests/sdk_tests/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package sdk_tests

import (
"context"
"encoding/json"
"log"
"os"
"path/filepath"
"strconv"
"testing"
"time"

"runtime"

"github.com/0chain/gosdk/core/client"
"github.com/0chain/gosdk/core/conf"

"github.com/0chain/system_test/internal/api/util/config"
"github.com/0chain/system_test/internal/api/util/test"
)

func TestMain(m *testing.M) {
configPath, ok := os.LookupEnv(config.ConfigPathEnv)
if !ok {
configPath = "./config/sdk_tests_config.yaml"
log.Printf("CONFIG_PATH environment variable is not set so has defaulted to [%v]", configPath)
}

// Parse configuration
parsedConfig = parseConfig(configPath)

defaultTestTimeout, err := time.ParseDuration(parsedConfig.DefaultTestTimeout)
if err != nil {
log.Printf("Default test case timeout could not be parsed so has defaulted to [%v]", test.DefaultTestTimeout)
} else {
test.DefaultTestTimeout = defaultTestTimeout
test.SmokeTestMode, _ = strconv.ParseBool(os.Getenv("SMOKE_TEST_MODE"))
log.Printf("Default test case timeout is [%v]", test.DefaultTestTimeout)
}


// t := test.NewSystemTest(new(testing.T))

// Initialize the SDK client
// Initialize the SDK client
err = client.Init(context.Background(), conf.Config{
BlockWorker: parsedConfig.BlockWorker,
SignatureScheme: parsedConfig.SignatureScheme,
ChainID: parsedConfig.ChainID,
MaxTxnQuery: parsedConfig.MaxTxnQuery,
QuerySleepTime: parsedConfig.QuerySleepTime,
MinSubmit: parsedConfig.MinSubmit,
MinConfirmation: parsedConfig.MinConfirmation,
})
// require.NoError(t, err, "Failed to initialize SDK client")
if err != nil {
log.Printf("Failed to initialize SDK client: %v", err)
runtime.Breakpoint() // Force debugger to pause
os.Exit(1)
}
client.SetSdkInitialized(true)
client.SetSignatureScheme(parsedConfig.SignatureScheme)

// Load wallet pool if available
walletMutex.Lock()
walletFilePath := filepath.Join(".", "config", "wallets.json")
if _, err := os.Stat(walletFilePath); err == nil {
fileContent, err := os.ReadFile(walletFilePath)
if err != nil {
log.Printf("Warning: Could not read wallets file: %v", err)
} else {
err = json.Unmarshal(fileContent, &initialisedWallets)
if err != nil {
log.Printf("Warning: Could not parse wallets file: %v", err)
} else {
log.Printf("Loaded %d wallets from pool", len(initialisedWallets))
}
}
} else {
log.Printf("No wallet pool found at %s, tests will create wallets as needed", walletFilePath)
}
walletMutex.Unlock()

os.Exit(m.Run())
}

func parseConfig(configPath string) *SDKTestConfig {
cfg := &SDKTestConfig{
SignatureScheme: "bls0chain",
ChainID: "0afc093ffb509f059c55478bc1a60351cef7b4e9c008a53a6cc8241ca8617dfe",
MaxTxnQuery: 5,
QuerySleepTime: 5,
MinSubmit: 10,
MinConfirmation: 10,
DefaultTestTimeout: "45s",
}

parsed := config.Parse(configPath)
if parsed != nil {
// Map common fields
cfg.BlockWorker = parsed.BlockWorker
cfg.DefaultTestTimeout = parsed.DefaultTestCaseTimeout
}

return cfg
}
128 changes: 128 additions & 0 deletions tests/sdk_tests/multi_wallet_management_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package sdk_tests

import (
"sync"
"testing"

"github.com/0chain/gosdk/core/client"
"github.com/0chain/system_test/internal/api/util/test"
"github.com/stretchr/testify/require"
)

func TestMultiWalletManagement(testSetup *testing.T) {
t := test.NewSystemTest(testSetup)
t.SetSmokeTests("Test multi-wallet management and edge cases")

t.Run("AddWallet and GetWalletByKey", func(t *test.SystemTest) {
wallets, err := LoadWalletsFromPool(1)
require.NoError(t, err)
wallet := wallets[0]

err = AddWalletToSDK(t, wallet)
require.NoError(t, err)

pubkey := GetWalletPublicKey(wallet)

// Verify wallet exists
retrieved := client.GetWalletByKey(pubkey)

Check failure on line 27 in tests/sdk_tests/multi_wallet_management_test.go

View workflow job for this annotation

GitHub Actions / lint

undefined: client.GetWalletByKey
require.NotNil(t, retrieved, "Wallet should exist after adding")
require.Equal(t, wallet.ClientID, retrieved.ClientID)

t.Logf("Successfully verified AddWallet and GetWalletByKey")
})

t.Run("Concurrent wallet operations", func(t *test.SystemTest) {
wallets, err := LoadWalletsFromPool(5)
require.NoError(t, err)

var wg sync.WaitGroup
errors := make(chan error, len(wallets)*2)

// Concurrently add wallets
for i, wallet := range wallets {
wg.Add(1)
go func(w *Wallet, idx int) {
defer wg.Done()
if err := AddWalletToSDK(t, w); err != nil {
errors <- err
}
}(wallet, i)
}

wg.Wait()
close(errors)

// Check for errors
for err := range errors {
require.NoError(t, err, "Concurrent wallet addition should not error")
}

// Verify all wallets are accessible
for _, wallet := range wallets {
pubkey := GetWalletPublicKey(wallet)
retrieved := client.GetWalletByKey(pubkey)

Check failure on line 63 in tests/sdk_tests/multi_wallet_management_test.go

View workflow job for this annotation

GitHub Actions / lint

undefined: client.GetWalletByKey
require.NotNil(t, retrieved, "Wallet should be retrievable after concurrent add")
}

t.Logf("Successfully verified concurrent wallet operations")
})

t.Run("GetWalletByKey with non-existent key", func(t *test.SystemTest) {
fakeKey := "nonexistent_key_12345"
retrieved := client.GetWalletByKey(fakeKey)

Check failure on line 72 in tests/sdk_tests/multi_wallet_management_test.go

View workflow job for this annotation

GitHub Actions / lint

undefined: client.GetWalletByKey
require.Nil(t, retrieved, "GetWalletByKey should return nil for non-existent key")

t.Logf("Successfully verified non-existent key handling")
})

t.Run("PublicKey lookup with specific key", func(t *test.SystemTest) {
wallets, err := LoadWalletsFromPool(1)
require.NoError(t, err)
wallet := wallets[0]

err = AddWalletToSDK(t, wallet)
require.NoError(t, err)

pubkey := GetWalletPublicKey(wallet)

// Lookup using the key
retrievedKey := client.PublicKey(pubkey)
require.Equal(t, wallet.ClientKey, retrievedKey, "PublicKey should return correct client key")

t.Logf("Successfully verified PublicKey lookup with specific key")
})

t.Run("Id lookup with specific key", func(t *test.SystemTest) {
wallets, err := LoadWalletsFromPool(1)
require.NoError(t, err)
wallet := wallets[0]

err = AddWalletToSDK(t, wallet)
require.NoError(t, err)

pubkey := GetWalletPublicKey(wallet)

// Lookup using the key
retrievedID := client.Id(pubkey)
require.Equal(t, wallet.ClientID, retrievedID, "Id should return correct client ID")

t.Logf("Successfully verified Id lookup with specific key")
})

t.Run("IsWalletSplit with specific key", func(t *test.SystemTest) {
wallets, err := LoadWalletsFromPool(1)
require.NoError(t, err)
wallet := wallets[0]

err = AddWalletToSDK(t, wallet)
require.NoError(t, err)

pubkey := GetWalletPublicKey(wallet)

isSplit, err := client.IsWalletSplit(pubkey)

Check failure on line 122 in tests/sdk_tests/multi_wallet_management_test.go

View workflow job for this annotation

GitHub Actions / lint

undefined: client.IsWalletSplit
require.NoError(t, err)
require.False(t, isSplit, "Test wallets should not be split-key wallets")

t.Logf("Successfully verified IsWalletSplit with specific key")
})
}
113 changes: 113 additions & 0 deletions tests/sdk_tests/multi_wallet_storage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package sdk_tests

import (
"os"
"path/filepath"
"testing"
"time"

"github.com/0chain/gosdk/zboxcore/sdk"
"github.com/0chain/system_test/internal/api/util/test"
"github.com/stretchr/testify/require"
)

func TestMultiWalletStorageOperations(testSetup *testing.T) {
t := test.NewSystemTest(testSetup)
t.SetSmokeTests("Test multi-wallet storage operations lifecycle")

t.Run("Full lifecycle: Create -> Upload -> Download with specific key", func(t *test.SystemTest) {

wallets, err := LoadWalletsFromPool(2)
require.NoError(t, err)
wallet := wallets[1] // Use second wallet

err = AddWalletToSDK(t, wallet)
require.NoError(t, err)

key := GetWalletPublicKey(wallet)

// 1. Get Blobbers
storageVersion := 2
priceRange := sdk.PriceRange{Min: 0, Max: 10000000000}
blobbers, err := sdk.GetAllocationBlobbers(storageVersion, 2, 2, 1024*1024, 0, priceRange, priceRange)
if err != nil {
t.Logf("Failed to get blobbers: %v. Skipping test.", err)
return
}
require.NotEmpty(t, blobbers)

// 2. Create Allocation
options := sdk.CreateAllocationOptions{
DataShards: 2,
ParityShards: 2,
Size: 1024*1024,
ReadPrice: sdk.PriceRange{Min: 0, Max: 10000000000},
WritePrice: sdk.PriceRange{Min: 0, Max: 10000000000},
Lock: 1000000000, // 1 ZCN
BlobberIds: blobbers,
AuthRoundExpiry: 100, // Ensure enough time
}

hash, _, _, err := sdk.CreateAllocationWith(options, key)

Check failure on line 51 in tests/sdk_tests/multi_wallet_storage_test.go

View workflow job for this annotation

GitHub Actions / lint

too many arguments in call to sdk.CreateAllocationWith
require.NoError(t, err)
require.NotEmpty(t, hash)
t.Logf("Allocation creation hash: %s", hash)

// 3. Wait for allocation to be visible
var alloc *sdk.Allocation
for i := 0; i < 15; i++ {
time.Sleep(2 * time.Second)
allocs, err := sdk.GetAllocations(key)

Check failure on line 60 in tests/sdk_tests/multi_wallet_storage_test.go

View workflow job for this annotation

GitHub Actions / lint

too many arguments in call to sdk.GetAllocations
if err == nil && len(allocs) > 0 {
alloc = allocs[0]
if alloc.Tx == hash {
break
}
}
}

if alloc == nil {
t.Logf("Allocation not confirmed after waiting. Skipping upload/download verification.")
return
}
t.Logf("Allocation confirmed. ID: %s", alloc.ID)

// Re-fetch allocation to ensure initialized
alloc, err = sdk.GetAllocation(alloc.ID, key)

Check failure on line 76 in tests/sdk_tests/multi_wallet_storage_test.go

View workflow job for this annotation

GitHub Actions / lint

too many arguments in call to sdk.GetAllocation
require.NoError(t, err)

// 4. Create dummy file
tmpDir := os.TempDir()
tmpFile := filepath.Join(tmpDir, "upload_test.txt")
err = os.WriteFile(tmpFile, []byte("Hello Multi-Wallet World"), 0644)
require.NoError(t, err)
defer os.Remove(tmpFile)

// 5. Upload file with secondary wallet
remotePath := "/upload_test.txt"
uploadErr := alloc.StartChunkedUpload(tmpDir, tmpFile, remotePath, nil, false, false, "", false, false, sdk.WithWallet(key))
if uploadErr != nil {
t.Logf("Upload failed: %v (may be expected if wallets not funded)", uploadErr)
return
}
t.Logf("Successfully uploaded file to %s", remotePath)

// 6. Download file to verify
downloadPath := filepath.Join(tmpDir, "download_test.txt")
defer os.Remove(downloadPath)

downloadErr := alloc.DownloadFile(downloadPath, remotePath, false, nil, false)
if downloadErr != nil {
t.Logf("Download failed: %v", downloadErr)
return
}

// Verify content
downloadedContent, err := os.ReadFile(downloadPath)
require.NoError(t, err)
require.Equal(t, "Hello Multi-Wallet World", string(downloadedContent),
"Downloaded content should match uploaded content")

t.Logf("Successfully verified full storage lifecycle with secondary wallet")
})
}
Loading
Loading