Skip to content

Commit

Permalink
Merge pull request #1743 from 0chain/revert-1740-revert-1733-gosdk/mi…
Browse files Browse the repository at this point in the history
…g_0box

Revert "Revert "gosdk methods directing to 0box""
  • Loading branch information
dabasov authored Feb 10, 2025
2 parents d56430e + 81661ca commit 1f77050
Show file tree
Hide file tree
Showing 20 changed files with 249 additions and 59 deletions.
13 changes: 7 additions & 6 deletions core/client/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package client
import (
"encoding/json"
"fmt"
"github.com/0chain/errors"
"github.com/0chain/gosdk/core/conf"
"github.com/0chain/gosdk/core/util"
"github.com/shopspring/decimal"
"log"
"net/http"
"net/url"
"sync"

"github.com/0chain/errors"
"github.com/0chain/gosdk/core/conf"
"github.com/0chain/gosdk/core/util"
"github.com/shopspring/decimal"
)

// SCRestAPIHandler is a function type to handle the response from the SC Rest API
Expand All @@ -20,7 +21,7 @@ import (
// `err` - the error if any
type SCRestAPIHandler func(response map[string][]byte, numSharders int, err error)

func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, restApiUrls ...string) ([]byte, error) {
func MakeSCRestAPICallToSharder(scAddress string, relativePath string, params map[string]string, restApiUrls ...string) ([]byte, error) {
const (
consensusThresh = float32(25.0)
ScRestApiUrl = "v1/screst/"
Expand Down Expand Up @@ -159,7 +160,7 @@ func GetBalance(clientIDs ...string) (*GetBalanceResponse, error) {
clientID = Id()
}

if res, err = MakeSCRestAPICall("", GetBalance, map[string]string{
if res, err = MakeSCRestAPICallToSharder("", GetBalance, map[string]string{
"client_id": clientID,
}, "v1/"); err != nil {
return nil, err
Expand Down
5 changes: 5 additions & 0 deletions core/client/init_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
var (
logging = logger.GetLogger()
nodeClient *Node
IsAppFlow = false
)

// Node Maintains central states of SDK (client's context, network).
Expand All @@ -34,6 +35,10 @@ type Node struct {
networkGuard sync.RWMutex
}

func SetIsAppFlow(val bool) {
IsAppFlow = true
}

// GetStableMiners Returns stable miner urls.
// Length of stable miners is depedent on config's MinSubmit and number of miners in network.
func (n *Node) GetStableMiners() []string {
Expand Down
27 changes: 27 additions & 0 deletions core/client/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@ type Client struct {
sign SignFunc

Check failure on line 36 in core/client/set.go

View workflow job for this annotation

GitHub Actions / lint

field `sign` is unused (unused)
}

type InitSdkOptions struct {
WalletJSON string
BlockWorker string
ChainID string
SignatureScheme string
Nonce int64
IsSplitWallet bool
AddWallet bool
TxnFee *int
MinConfirmation *int
MinSubmit *int
ConfirmationChainLength *int
SharderConsensous *int
ZboxHost string
ZboxAppType string
}

func init() {
sys.Sign = signHash
sys.SignWithAuth = signHashWithAuth
Expand Down Expand Up @@ -362,6 +379,16 @@ func InitSDK(walletJSON string,
return nil
}

func InitSDKWithWebApp(params InitSdkOptions) error {
err := InitSDK(params.WalletJSON, params.BlockWorker, params.ChainID, params.SignatureScheme, params.Nonce, params.AddWallet, *params.MinConfirmation, *params.MinSubmit, *params.ConfirmationChainLength, *params.SharderConsensous)
if err != nil {
return err
}
conf.SetZboxAppConfigs(params.ZboxHost, params.ZboxAppType)
SetIsAppFlow(true)
return nil
}

func IsSDKInitialized() bool {
return sdkInitialized
}
Expand Down
5 changes: 5 additions & 0 deletions core/conf/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func GetClientConfig() (*Config, error) {
return cfg, nil
}

func SetZboxAppConfigs(zboxHost, zboxAppType string) {
cfg.ZboxHost = zboxHost
cfg.ZboxAppType = zboxAppType
}

// InitClientConfig set global client config
func InitClientConfig(c *Config) {
onceCfg.Do(func() {
Expand Down
86 changes: 86 additions & 0 deletions core/screstapi/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package screstapi

import (
"context"
"encoding/json"

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

var urlPathSharderToZboxMap = map[string]string{
"/getStakePoolStat": "/getStakePoolStat",
"/getUserStakePoolStat": "/getUserStakePoolStat",
"/getChallengePoolStat": "/getChallengePoolStat",
"/getBlobber": "/blobber",
"/getblobbers": "/blobbers",
"/blobber_ids": "/blobber_ids",
"/alloc_blobbers": "/blobbers/allocation",
"/get_validator": "/validator",
"/validators": "/validators",
"/v1/mint_nonce": "/mintNonce",
"client/get/balance": "/balance",
"/v1/not_processed_burn_tickets": "/not_processed_burn_tickets",
"/allocations": "/getAllocations",
"/allocation": "/getAllocation",
}

func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, restApiUrls ...string) (resp []byte, err error) {
_, ok := urlPathSharderToZboxMap[relativePath]
if client.IsAppFlow && ok {
resp, err = MakeSCRestAPICallToZbox(urlPathSharderToZboxMap[relativePath], params)
if err != nil {
resp, err = client.MakeSCRestAPICallToSharder(scAddress, relativePath, params, restApiUrls...)
}
} else {
resp, err = client.MakeSCRestAPICallToSharder(scAddress, relativePath, params, restApiUrls...)
}

return resp, err
}

func MakeSCRestAPICallToZbox(relativePath string, params map[string]string) ([]byte, error) {
// req, err := http.NewRequest(method, relativePath)
zboxApiClient := zboxapi.NewClient()
configObj, err := conf.GetClientConfig()
if err != nil {
return nil, err
}
zboxApiClient.SetRequest(configObj.ZboxHost, configObj.ZboxAppType)

resp, err := zboxApiClient.MakeRestApiCallToZbox(context.TODO(), relativePath, params)
if err != nil {
return nil, err
}

return resp, nil
}

func GetBalance(clientIDs ...string) (*client.GetBalanceResponse, error) {
var clientID string
if len(clientIDs) > 0 {
clientID = clientIDs[0]
} else {
clientID = client.Id()
}

const GetBalanceUrl = "client/get/balance"
var (
balance client.GetBalanceResponse
err error
resp []byte
)

if resp, err = MakeSCRestAPICall("", GetBalanceUrl, map[string]string{
"client_id": clientID,
}, "v1/"); err != nil {
return nil, err
}

if err = json.Unmarshal(resp, &balance); err != nil {
return nil, err
}

return &balance, err
}
3 changes: 2 additions & 1 deletion core/transaction/get_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package transaction

import (
"encoding/json"

"github.com/0chain/errors"
coreHttp "github.com/0chain/gosdk/core/client"
)
Expand Down Expand Up @@ -45,7 +46,7 @@ func GetConfig(configType string) (conf *InputMap, err error) {
relativePath = GET_MINERSC_CONFIGS
}

b, err = coreHttp.MakeSCRestAPICall(scAddress, relativePath, nil)
b, err = coreHttp.MakeSCRestAPICallToSharder(scAddress, relativePath, nil)
if err != nil {
return nil, errors.Wrap(err, "error requesting storage SC configs:")
}
Expand Down
17 changes: 12 additions & 5 deletions mobilesdk/sdk/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,18 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) {
l.Logger.Info(configObj.ChainID)
l.Logger.Info(configObj.SignatureScheme)
l.Logger.Info(configObj.PreferredBlobbers)
if err = client.InitSDK(clientJson,
configObj.BlockWorker,
configObj.ChainID,
configObj.SignatureScheme,
0, true); err != nil {
params := client.InitSdkOptions{
WalletJSON: clientJson,
BlockWorker: configObj.BlockWorker,
ChainID: configObj.ChainID,
SignatureScheme: configObj.SignatureScheme,
Nonce: int64(0),
AddWallet: true,
ZboxHost: configObj.ZboxHost,
ZboxAppType: configObj.ZboxAppType,
}

if err = client.InitSDKWithWebApp(params); err != nil {
l.Logger.Error(err)
return nil, err
}
Expand Down
1 change: 1 addition & 0 deletions wasmsdk/blobber.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,7 @@ func multiDownload(allocationID, jsonMultiDownloadOptions, authTicket, callbackF
}
}()
sdkLogger.Info("starting multidownload")

wg := &sync.WaitGroup{}
useCallback := false
if callbackFuncName != "" {
Expand Down
20 changes: 18 additions & 2 deletions wasmsdk/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/0chain/gosdk/core/encryption"
"github.com/0chain/gosdk/core/imageutil"
"github.com/0chain/gosdk/core/logger"
"github.com/0chain/gosdk/core/screstapi"
"github.com/0chain/gosdk/zboxcore/sdk"
"github.com/0chain/gosdk/zcncore"

Expand Down Expand Up @@ -40,7 +41,22 @@ func initSDKs(chainID, blockWorker, signatureScheme string,

zboxApiClient.SetRequest(zboxHost, zboxAppType)

err := client.InitSDK("{}", blockWorker, chainID, signatureScheme, 0, false, minConfirmation, minSubmit, confirmationChainLength, sharderConsensous)
params := client.InitSdkOptions{
WalletJSON: "{}",
BlockWorker: blockWorker,
ChainID: chainID,
SignatureScheme: signatureScheme,
Nonce: int64(0),
AddWallet: false,
MinConfirmation: &minConfirmation,
MinSubmit: &minSubmit,
SharderConsensous: &sharderConsensous,
ConfirmationChainLength: &confirmationChainLength,
ZboxHost: zboxHost,
ZboxAppType: zboxAppType,
}

err := client.InitSDKWithWebApp(params)
if err != nil {
fmt.Println("wasm: InitStorageSDK ", err)
return err
Expand Down Expand Up @@ -146,7 +162,7 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro
if err != nil {
sdkLogger.Error(fmt.Sprintf("Error parsing JSON: %v", err))
}
b, err := client.MakeSCRestAPICall(scAddress, relativePath, params)
b, err := screstapi.MakeSCRestAPICall(scAddress, relativePath, params)
return string(b), err
}

Expand Down
4 changes: 2 additions & 2 deletions wasmsdk/zcn.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
package main

import (
"github.com/0chain/gosdk/core/client"
"github.com/0chain/gosdk/core/screstapi"
"github.com/0chain/gosdk/zcncore"
)

Expand All @@ -17,7 +17,7 @@ type Balance struct {
// getWalletBalance retrieves the wallet balance of the client from the network.
// - clientId is the client id
func getWalletBalance(clientId string) (*Balance, error) {
bal, err := client.GetBalance(clientId)
bal, err := screstapi.GetBalance(clientId)
if err != nil {
return nil, err
}
Expand Down
5 changes: 3 additions & 2 deletions winsdk/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ import (
)

import (
"github.com/0chain/gosdk/core/client"
"os"
"path/filepath"

"github.com/0chain/gosdk/core/screstapi"

"github.com/0chain/gosdk/zcncore"
)

Expand Down Expand Up @@ -87,7 +88,7 @@ func RecoverWallet(mnemonic *C.char) *C.char {
//
//export GetWalletBalance
func GetWalletBalance(clientID *C.char) *C.char {
b, err := client.GetBalance(C.GoString(clientID))
b, err := screstapi.GetBalance(C.GoString(clientID))
if err != nil {
log.Error("win: ", err)
return WithJSON(0, err)
Expand Down
33 changes: 32 additions & 1 deletion zboxapi/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/0chain/gosdk/core/client"
"io"
"net/http"
"net/url"
"strconv"
"time"

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

thrown "github.com/0chain/errors"
"github.com/0chain/gosdk/core/encryption"
"github.com/0chain/gosdk/core/logger"
Expand Down Expand Up @@ -371,3 +374,31 @@ func (c *Client) GetSharedToMe(ctx context.Context, phoneNumber, token string) (
return result.Data, nil

}

func (c *Client) MakeRestApiCallToZbox(ctx context.Context, relativePath string, params map[string]string) ([]byte, error) {
urlPath := c.baseUrl + "/v2" + relativePath
u, err := url.Parse(urlPath)
if err != nil {
return nil, fmt.Errorf("error parsing URL: %w", err)
}

// Add query parameters
q := u.Query()
for key, value := range params {
q.Add(key, value)
}
u.RawQuery = q.Encode()

resp, err := http.Get(u.String())
if err != nil {
return nil, fmt.Errorf("error making GET request: %w", err)
}

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
resp.Body.Close()

return body, nil
}
4 changes: 3 additions & 1 deletion zboxcore/logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Proxy for the core logger package.
package logger

import "github.com/0chain/gosdk/core/logger"
import (
"github.com/0chain/gosdk/core/logger"
)

// Logger global logger instance
var Logger = logger.GetLogger()
1 change: 1 addition & 0 deletions zboxcore/sdk/commitworker.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ func (commitreq *CommitRequest) processCommit() {
hasher.Write(decodedHash) //nolint:errcheck
chainHash = hex.EncodeToString(hasher.Sum(nil))
}

err = commitreq.commitBlobber(rootRef, chainHash, lR.LatestWM, size, fileIDMeta)
if err != nil {
commitreq.result = ErrorCommitResult(err.Error())
Expand Down
Loading

0 comments on commit 1f77050

Please sign in to comment.