diff --git a/core/client/http.go b/core/client/http.go index 744ce0d4b..4572b366e 100644 --- a/core/client/http.go +++ b/core/client/http.go @@ -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 @@ -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/" @@ -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 diff --git a/core/client/init_node.go b/core/client/init_node.go index 444b33834..d356f2071 100644 --- a/core/client/init_node.go +++ b/core/client/init_node.go @@ -20,6 +20,7 @@ import ( var ( logging = logger.GetLogger() nodeClient *Node + IsAppFlow = false ) // Node Maintains central states of SDK (client's context, network). @@ -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 { diff --git a/core/client/set.go b/core/client/set.go index 3eb4d486e..f0ba52ad4 100644 --- a/core/client/set.go +++ b/core/client/set.go @@ -36,6 +36,23 @@ type Client struct { sign SignFunc } +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 = signHash @@ -326,6 +343,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 } diff --git a/core/conf/config.go b/core/conf/config.go index b3d159f2c..4fae43bec 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -177,6 +177,7 @@ func LoadConfig(v Reader) (Config, error) { cfg.SignatureScheme = v.GetString("signature_scheme") cfg.ChainID = v.GetString("chain_id") cfg.ZauthServer = v.GetString("zauth_server") + cfg.EthereumNode = v.GetString("ethereum_node_url") return cfg, nil } diff --git a/core/conf/vars.go b/core/conf/vars.go index 8551c1cd9..e31cbcd8f 100644 --- a/core/conf/vars.go +++ b/core/conf/vars.go @@ -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() { diff --git a/core/screstapi/http.go b/core/screstapi/http.go new file mode 100644 index 000000000..53f5823b5 --- /dev/null +++ b/core/screstapi/http.go @@ -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", + "/allocation": "/getAllocation", + "/allocations": "/getAllocations", + "/v1/mint_nonce": "/mintNonce", + "client/get/balance": "/balance", + "/v1/not_processed_burn_tickets": "/not_processed_burn_tickets", +} + +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 +} diff --git a/core/transaction/get_data.go b/core/transaction/get_data.go index cf7a60065..7ac58359a 100644 --- a/core/transaction/get_data.go +++ b/core/transaction/get_data.go @@ -2,6 +2,7 @@ package transaction import ( "encoding/json" + "github.com/0chain/errors" coreHttp "github.com/0chain/gosdk/core/client" ) @@ -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:") } diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index eaab794ad..f5dd299c8 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -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 } @@ -155,7 +162,7 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { // - expiration: duration to allocation expiration // - lock: lock write pool with given number of tokens // - blobberAuthTickets: list of blobber auth tickets needed for the restricted blobbers -func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expiration int64, lock string, blobberAuthTickets []string) (*zbox.Allocation, error) { +func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expiration, authRoundExpiry int64, lock string, blobberAuthTickets []string) (*zbox.Allocation, error) { readPrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} writePrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} @@ -174,6 +181,7 @@ func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expira BlobberIds: []string{}, FileOptionsParams: &sdk.FileOptionsParameters{}, BlobberAuthTickets: blobberAuthTickets, + AuthRoundExpiry: authRoundExpiry, } sdkAllocationID, _, _, err := sdk.CreateAllocationWith(options) @@ -196,7 +204,7 @@ func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expira // - lock: lock write pool with given number of tokens // - blobberUrls: concat blobber urls with comma. leave it as empty if you don't have any preferred blobbers // - blobberIds: concat blobber ids with comma. leave it as empty if you don't have any preferred blobbers -func (s *StorageSDK) CreateAllocationWithBlobbers(name string, datashards, parityshards int, size int64, lock string, blobberUrls, blobberIds string, blobberAuthTickets []string) (*zbox.Allocation, error) { +func (s *StorageSDK) CreateAllocationWithBlobbers(name string, datashards, parityshards int, size, authRoundExpiry int64, lock string, blobberUrls, blobberIds string, blobberAuthTickets []string) (*zbox.Allocation, error) { readPrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} writePrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} @@ -213,6 +221,7 @@ func (s *StorageSDK) CreateAllocationWithBlobbers(name string, datashards, parit WritePrice: writePrice, ReadPrice: readPrice, BlobberAuthTickets: blobberAuthTickets, + AuthRoundExpiry: authRoundExpiry, } if blobberUrls != "" { @@ -364,12 +373,12 @@ func (s *StorageSDK) GetVersion() string { // - extend: extend allocation // - allocationID: allocation ID // - lock: Number of tokens to lock to the allocation after the update -func (s *StorageSDK) UpdateAllocation(size int64, extend bool, allocationID string, lock uint64) (hash string, err error) { +func (s *StorageSDK) UpdateAllocation(size, authRoundExpiry int64, extend bool, allocationID string, lock uint64) (hash string, err error) { if lock > math.MaxInt64 { return "", errors.Errorf("int64 overflow in lock") } - hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, "", "", "", "", "", false, &sdk.FileOptionsParameters{}, "") + hash, _, err = sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, lock, "", "", "", "", "", false, &sdk.FileOptionsParameters{}, "") return hash, err } diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index d310b10f6..25aae7861 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -88,7 +88,7 @@ func getAllocationBlobbers(preferredBlobberURLs []string, // - lock is the lock value to add to the allocation. // - blobberIds is the list of blobber ids. // - blobberAuthTickets is the list of blobber auth tickets in case of using restricted blobbers. -func createAllocation(datashards, parityshards int, size int64, +func createAllocation(datashards, parityshards int, size, authRoundExpiry int64, minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, lock int64, blobberIds, blobberAuthTickets []string, setThirdPartyExtendable, IsEnterprise, force bool) ( *transaction.Transaction, error) { @@ -111,6 +111,7 @@ func createAllocation(datashards, parityshards int, size int64, StorageVersion: sdk.StorageV2, BlobberAuthTickets: blobberAuthTickets, Force: force, + AuthRoundExpiry: authRoundExpiry, } sdkLogger.Info(options) @@ -161,7 +162,8 @@ func transferAllocation(allocationID, newOwnerId, newOwnerPublicKey string) erro func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, forbidupdate, forbidmove, forbidcopy, forbidrename bool) (string, error) { hash, _, err := sdk.UpdateAllocation( - 0, //size, + 0, //size, + 0, false, //extend, allocationID, // allocID, 0, //lock, @@ -192,7 +194,8 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for func freezeAllocation(allocationID string) (string, error) { hash, _, err := sdk.UpdateAllocation( - 0, //size, + 0, //size, + 0, false, //extend, allocationID, // allocID, 0, //lock, @@ -245,7 +248,7 @@ func cancelAllocation(allocationID string) (string, error) { // - addBlobberAuthTicket: blobber auth ticket to add to the allocation, in case of restricted blobbers // - removeBlobberId: blobber ID to remove from the allocation func updateAllocationWithRepair(allocationID string, - size int64, + size, authRoundExpiry int64, extend bool, lock int64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, updateAllocTicket, callbackFuncName string) (string, error) { @@ -265,7 +268,7 @@ func updateAllocationWithRepair(allocationID string, } } - alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, false, &sdk.FileOptionsParameters{}, updateAllocTicket) + alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, authRoundExpiry, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, false, &sdk.FileOptionsParameters{}, updateAllocTicket) if err != nil { return hash, err } @@ -299,10 +302,10 @@ func updateAllocationWithRepair(allocationID string, // - removeBlobberId: blobber ID to remove from the allocation // - setThirdPartyExtendable: third party extendable flag, if true, the allocation can be extended (in terms of size) by a non-owner client func updateAllocation(allocationID string, - size int64, extend bool, + size, authRoundExpiry int64, extend bool, lock int64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, setThirdPartyExtendable bool) (string, error) { - hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, &sdk.FileOptionsParameters{}, "") + hash, _, err := sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, &sdk.FileOptionsParameters{}, "") if err == nil { clearAllocation(allocationID) diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index c0b78a2b6..07f9974ad 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -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" @@ -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 @@ -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 } diff --git a/wasmsdk/zcn.go b/wasmsdk/zcn.go index bb3a53a3d..f0272e4b5 100644 --- a/wasmsdk/zcn.go +++ b/wasmsdk/zcn.go @@ -4,7 +4,7 @@ package main import ( - "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/screstapi" "github.com/0chain/gosdk/zcncore" ) @@ -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 } diff --git a/winsdk/wallet.go b/winsdk/wallet.go index 0e72008f8..51762ea61 100644 --- a/winsdk/wallet.go +++ b/winsdk/wallet.go @@ -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" ) @@ -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) diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go index 0ac6e7064..270e18c63 100644 --- a/zboxapi/sdk.go +++ b/zboxapi/sdk.go @@ -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" @@ -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 +} diff --git a/zboxcore/logger/logger.go b/zboxcore/logger/logger.go index 64134eb35..0a78ddab7 100644 --- a/zboxcore/logger/logger.go +++ b/zboxcore/logger/logger.go @@ -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() diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 03209f484..1162f2342 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -465,7 +465,7 @@ func (a *Allocation) generateAndSetOwnerSigningPublicKey() { if a.OwnerSigningPublicKey == "" && !a.Finalized && !a.Canceled && client.Wallet().IsSplit { pubKey := privateSigningKey.Public().(ed25519.PublicKey) a.OwnerSigningPublicKey = hex.EncodeToString(pubKey) - hash, _, err := UpdateAllocation(0, false, a.ID, 0, "", "", "", "", a.OwnerSigningPublicKey, false, nil, "") + hash, _, err := UpdateAllocation(0, 0, false, a.ID, 0, "", "", "", "", a.OwnerSigningPublicKey, false, nil, "") if err != nil { l.Logger.Error("Failed to update owner signing public key ", err, " allocationID: ", a.ID, " hash: ", hash) return @@ -3185,14 +3185,14 @@ func (a *Allocation) SetConsensusThreshold() { // - fileOptionsParams: The file options parameters which control permissions of the files of the allocations. // - statusCB: A callback function to receive status updates during the update operation. func (a *Allocation) UpdateWithRepair( - size int64, + size, authRoundExpiry int64, extend bool, lock uint64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, updateAllocTicket string, statusCB StatusCallback, ) (string, error) { - updatedAlloc, hash, isRepairRequired, err := a.UpdateWithStatus(size, extend, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) + updatedAlloc, hash, isRepairRequired, err := a.UpdateWithStatus(size, authRoundExpiry, extend, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) if err != nil { return hash, err } @@ -3220,7 +3220,7 @@ func (a *Allocation) UpdateWithRepair( // // Returns the updated allocation, hash, and a boolean indicating whether repair is required. func (a *Allocation) UpdateWithStatus( - size int64, + size, authRoundExpiry int64, extend bool, lock uint64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, @@ -3236,7 +3236,7 @@ func (a *Allocation) UpdateWithStatus( } l.Logger.Info("Updating allocation") - hash, _, err := UpdateAllocation(size, extend, a.ID, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) + hash, _, err := UpdateAllocation(size, authRoundExpiry, extend, a.ID, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) if err != nil { return alloc, "", isRepairRequired, err } diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 9caa83686..fa15777d9 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -34,7 +34,7 @@ func CreateAllocationForOwner( owner, ownerpublickey string, datashards, parityshards int, size int64, readPrice, writePrice PriceRange, - lock uint64, preferredBlobberIds, blobberAuthTickets []string, thirdPartyExtendable, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, + lock uint64, preferredBlobberIds, blobberAuthTickets []string, thirdPartyExtendable, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, authRoundExpiry int64, ) (hash string, nonce int64, txn *transaction.Transaction, err error) { if lock > math.MaxInt64 { @@ -71,6 +71,7 @@ func CreateAllocationForOwner( allocationRequest["file_options_changed"], allocationRequest["file_options"] = calculateAllocationFileOptions(63 /*0011 1111*/, fileOptionsParams) allocationRequest["is_enterprise"] = IsEnterprise allocationRequest["storage_version"] = StorageV2 + allocationRequest["auth_round_expiry"] = authRoundExpiry var sn = transaction.SmartContractTxnData{ Name: transaction.NEW_ALLOCATION_REQUEST, @@ -126,7 +127,7 @@ func CreateFreeAllocation(marker string, value uint64) (string, int64, error) { // // returns the hash of the transaction, the nonce of the transaction and an error if any. func UpdateAllocation( - size int64, + size, authRoundExpiry int64, extend bool, allocationID string, lock uint64, @@ -162,6 +163,7 @@ func UpdateAllocation( updateAllocationRequest["set_third_party_extendable"] = setThirdPartyExtendable updateAllocationRequest["owner_signing_public_key"] = ownerSigninPublicKey updateAllocationRequest["file_options_changed"], updateAllocationRequest["file_options"] = calculateAllocationFileOptions(alloc.FileOptions, fileOptionsParams) + updateAllocationRequest["auth_round_expiry"] = authRoundExpiry if ticket != "" { diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index adb6eddbe..a8e3934fb 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -12,6 +12,7 @@ import ( "github.com/0chain/common/core/currency" "github.com/0chain/errors" "github.com/0chain/gosdk/core/logger" + "github.com/0chain/gosdk/core/screstapi" "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/client" @@ -163,7 +164,7 @@ func GetStakePoolInfo(providerType ProviderType, providerID string) (info *Stake } var b []byte - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", map[string]string{"provider_type": strconv.Itoa(int(providerType)), "provider_id": providerID}) if err != nil { return nil, errors.Wrap(err, "error requesting stake pool info:") @@ -204,7 +205,7 @@ func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUs "offset": strconv.FormatInt(int64(offset), 10), "limit": strconv.FormatInt(int64(limit), 10), } - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getUserStakePoolStat", params) if err != nil { return nil, errors.Wrap(err, "error requesting stake pool user info:") @@ -257,7 +258,7 @@ func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { } var b []byte - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getChallengePoolStat", map[string]string{"allocation_id": allocID}) if err != nil { return nil, errors.Wrap(err, "error requesting challenge pool info:") @@ -281,7 +282,7 @@ func GetMptData(key string) ([]byte, error) { } var b []byte - b, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, + b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/get_mpt_key", map[string]string{"key": key}, ) if err != nil { @@ -447,13 +448,9 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe Nodes []*Blobber } - url := fmt.Sprintf("/getblobbers?active=%s&limit=%d&offset=%d&stakable=%s", - strconv.FormatBool(active), - limit, - offset, - strconv.FormatBool(stakable), - ) - b, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, url, nil) + b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getblobbers", map[string]string{"active": strconv.FormatBool(active), "limit": strconv.FormatInt(int64(limit), 10), + "offset": strconv.FormatInt(int64(offset), 10), + "stakable": strconv.FormatBool(stakable)}) var wrap nodes if err != nil { return nil, errors.Wrap(err, "error requesting blobbers:") @@ -511,7 +508,7 @@ func GetBlobber(blobberID string) (blob *Blobber, err error) { return nil, sdkNotInitialized } var b []byte - b, err = client.MakeSCRestAPICall( + b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/getBlobber", map[string]string{"blobber_id": blobberID}, @@ -536,7 +533,7 @@ func GetValidator(validatorID string) (validator *Validator, err error) { return nil, sdkNotInitialized } var b []byte - b, err = client.MakeSCRestAPICall( + b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/get_validator", map[string]string{"validator_id": validatorID}, @@ -561,7 +558,7 @@ func GetValidators(stakable bool) (validators []*Validator, err error) { return nil, sdkNotInitialized } var b []byte - b, err = client.MakeSCRestAPICall( + b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/validators", map[string]string{ @@ -625,10 +622,11 @@ func GetAllocation(allocationID string) (*Allocation, error) { } params := make(map[string]string) params["allocation"] = allocationID - allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) + allocationBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return nil, errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } + allocationObj := &Allocation{} err = json.Unmarshal(allocationBytes, allocationObj) if err != nil { @@ -646,10 +644,11 @@ func GetAllocationForUpdate(allocationID string) (*Allocation, error) { } params := make(map[string]string) params["allocation"] = allocationID - allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) + allocationBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return nil, errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } + allocationObj := &Allocation{} err = json.Unmarshal(allocationBytes, allocationObj) if err != nil { @@ -665,7 +664,7 @@ func GetAllocationUpdates(allocation *Allocation) error { params := make(map[string]string) params["allocation"] = allocation.ID - allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) + allocationBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } @@ -718,10 +717,11 @@ func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, params["client"] = clientID params["limit"] = fmt.Sprint(limit) params["offset"] = fmt.Sprint(offset) - allocationsBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocations", params) + allocationsBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocations", params) if err != nil { return nil, errors.New("allocations_fetch_error", "Error fetching the allocations."+err.Error()) } + allocations := make([]*Allocation, 0) err = json.Unmarshal(allocationsBytes, &allocations) if err != nil { @@ -796,6 +796,7 @@ type CreateAllocationOptions struct { FileOptionsParams *FileOptionsParameters Force bool StorageVersion int + AuthRoundExpiry int64 } // CreateAllocationWith creates a new allocation with the given options for the current client using the SDK. @@ -809,7 +810,7 @@ func CreateAllocationWith(options CreateAllocationOptions) ( return CreateAllocationForOwner(client.Id(), client.PublicKey(), options.DataShards, options.ParityShards, options.Size, options.ReadPrice, options.WritePrice, options.Lock, - options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams) + options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams, options.AuthRoundExpiry) } // GetAllocationBlobbers returns a list of blobber ids that can be used for a new allocation. @@ -847,7 +848,7 @@ func GetAllocationBlobbers( params["force"] = strconv.FormatBool(force[0]) } - allocBlobber, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params) + allocBlobber, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params) if err != nil { return nil, err } @@ -934,7 +935,7 @@ func GetBlobberIds(blobberUrls []string) ([]string, error) { params := make(map[string]string) params["blobber_urls"] = string(urlsStr) - idsStr, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params) + idsStr, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params) if err != nil { return nil, err } @@ -959,7 +960,7 @@ func GetFreeAllocationBlobbers(request map[string]interface{}) ([]string, error) params := make(map[string]string) params["free_allocation_data"] = string(data) - allocBlobber, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params) + allocBlobber, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params) if err != nil { return nil, err } @@ -1405,7 +1406,7 @@ func GetUpdateAllocationMinLock( params := make(map[string]string) params["data"] = string(data) - responseBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params) + responseBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params) if err != nil { return 0, errors.Wrap(err, "failed to request allocation update min lock") } diff --git a/zcnbridge/rest.go b/zcnbridge/rest.go index ab860b16d..f5c12241f 100644 --- a/zcnbridge/rest.go +++ b/zcnbridge/rest.go @@ -3,6 +3,7 @@ package zcnbridge import ( "encoding/json" "fmt" + coreHttp "github.com/0chain/gosdk/core/client" "github.com/0chain/gosdk/core/common" @@ -88,7 +89,7 @@ func GetAuthorizer(id string) (res []byte, err error) { return nil, err } - return coreHttp.MakeSCRestAPICall(zcncore.ZCNSCSmartContractAddress, PathGetAuthorizer, zcncore.Params{ + return coreHttp.MakeSCRestAPICallToSharder(zcncore.ZCNSCSmartContractAddress, PathGetAuthorizer, zcncore.Params{ "id": id, }) } @@ -101,7 +102,7 @@ func GetAuthorizers(active bool) (res []byte, err error) { if err != nil { return nil, err } - return coreHttp.MakeSCRestAPICall(zcncore.ZCNSCSmartContractAddress, fmt.Sprintf(PathGetAuthorizerNodes, active), nil) + return coreHttp.MakeSCRestAPICallToSharder(zcncore.ZCNSCSmartContractAddress, fmt.Sprintf(PathGetAuthorizerNodes, active), nil) } // GetGlobalConfig Returns global config @@ -111,5 +112,5 @@ func GetGlobalConfig() (res []byte, err error) { if err != nil { return nil, err } - return coreHttp.MakeSCRestAPICall(zcncore.ZCNSCSmartContractAddress, PathGetGlobalConfig, nil) + return coreHttp.MakeSCRestAPICallToSharder(zcncore.ZCNSCSmartContractAddress, PathGetGlobalConfig, nil) } diff --git a/zcncore/execute_transactions.go b/zcncore/execute_transactions.go index 45c49a5ad..5a75ddde8 100644 --- a/zcncore/execute_transactions.go +++ b/zcncore/execute_transactions.go @@ -3,6 +3,7 @@ package zcncore import ( "fmt" "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk/zboxcore/sdk" ) // AuthorizerNode represents an authorizer node in the network @@ -220,3 +221,39 @@ func Faucet(tokens uint64, input string, client ...string) (hash, out string, no InputArgs: input, }, tokens, true, client...) } + +func DeleteMiner(id string) (hash, out string, nonce int64, txn *transaction.Transaction, err error) { + return transaction.SmartContractTxn(MinerSmartContractAddress, transaction.SmartContractTxnData{ + Name: "delete_miner", + InputArgs: &MinerSCMinerInfo{ + SimpleMiner: SimpleMiner{ + ID: id, + }, + }, + }, true) +} + +func DeleteSharder(id string) (hash, out string, nonce int64, txn *transaction.Transaction, err error) { + return transaction.SmartContractTxn(MinerSmartContractAddress, transaction.SmartContractTxnData{ + Name: "delete_sharder", + InputArgs: &MinerSCMinerInfo{ + SimpleMiner: SimpleMiner{ + ID: id, + }, + }, + }, true) +} + +func VcRegisterNode(id string, nodeType sdk.ProviderType) (hash, out string, nonce int64, txn *transaction.Transaction, err error) { + type VCAddSCData struct { + ID string + Type int + } + return transaction.SmartContractTxnValueFee(MinerSmartContractAddress, transaction.SmartContractTxnData{ + Name: "vc_add", + InputArgs: VCAddSCData{ + ID: id, + Type: int(nodeType), + }, + }, 0, 10000000000, true) +} diff --git a/zcncore/get_data.go b/zcncore/get_data.go index 6a17f7aff..f6f752e76 100644 --- a/zcncore/get_data.go +++ b/zcncore/get_data.go @@ -10,6 +10,7 @@ import ( "github.com/0chain/gosdk/core/block" "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/screstapi" "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/core/tokenrate" "github.com/0chain/gosdk/core/util" @@ -213,7 +214,7 @@ func withParams(uri string, params Params) string { //nolint:unused // return // } // -// return coreHttp.MakeSCRestAPICall(StorageSmartContractAddress, STORAGE_GET_BLOBBER_SNAPSHOT, Params{ +// return coreHttp.MakeSCRestAPICallToSharder(StorageSmartContractAddress, STORAGE_GET_BLOBBER_SNAPSHOT, Params{ // "round": strconv.FormatInt(round, 10), // "limit": strconv.FormatInt(limit, 10), // "offset": strconv.FormatInt(offset, 10), @@ -228,7 +229,7 @@ func GetMinerSCNodeInfo(id string) ([]byte, error) { return nil, err } - return client.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_NODE, Params{ + return screstapi.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_NODE, Params{ "id": id, }) } @@ -241,7 +242,7 @@ func GetMintNonce() ([]byte, error) { return nil, err } - return client.MakeSCRestAPICall(ZCNSCSmartContractAddress, GET_MINT_NONCE, Params{ + return screstapi.MakeSCRestAPICall(ZCNSCSmartContractAddress, GET_MINT_NONCE, Params{ "client_id": client.Id(), }) } @@ -251,7 +252,7 @@ func GetMiners(active, stakable bool, limit, offset int) ([]byte, error) { return nil, err } - return client.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_MINERS, Params{ + return screstapi.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_MINERS, Params{ "active": strconv.FormatBool(active), "stakable": strconv.FormatBool(stakable), "offset": strconv.FormatInt(int64(offset), 10), @@ -264,7 +265,7 @@ func GetSharders(active, stakable bool, limit, offset int) ([]byte, error) { return nil, err } - return client.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_SHARDERS, Params{ + return screstapi.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_SHARDERS, Params{ "active": strconv.FormatBool(active), "stakable": strconv.FormatBool(stakable), "offset": strconv.FormatInt(int64(offset), 10), @@ -276,7 +277,7 @@ func GetSharders(active, stakable bool, limit, offset int) ([]byte, error) { // - numSharders: number of sharders // - timeout: request timeout func GetLatestFinalizedMagicBlock() (m *block.MagicBlock, err error) { - res, err := client.MakeSCRestAPICall("", GET_LATEST_FINALIZED_MAGIC_BLOCK, nil, "") + res, err := screstapi.MakeSCRestAPICall("", GET_LATEST_FINALIZED_MAGIC_BLOCK, nil, "") if err != nil { return nil, err } @@ -305,7 +306,7 @@ func GetMinerSCUserInfo(clientID string) ([]byte, error) { clientID = client.Id() } - return client.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_USER, Params{ + return screstapi.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_USER, Params{ "client_id": clientID, }) } @@ -317,7 +318,7 @@ func GetMinerSCNodePool(id string) ([]byte, error) { return nil, err } - return client.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_POOL, Params{ + return screstapi.MakeSCRestAPICall(MinerSmartContractAddress, GET_MINERSC_POOL, Params{ "id": id, "pool_id": client.Id(), }) @@ -335,7 +336,7 @@ func GetNotProcessedZCNBurnTickets(ethereumAddress, startNonce string) ([]byte, const GET_NOT_PROCESSED_BURN_TICKETS = `/v1/not_processed_burn_tickets` - return client.MakeSCRestAPICall(ZCNSCSmartContractAddress, GET_NOT_PROCESSED_BURN_TICKETS, Params{ + return screstapi.MakeSCRestAPICall(ZCNSCSmartContractAddress, GET_NOT_PROCESSED_BURN_TICKETS, Params{ "ethereum_address": ethereumAddress, "nonce": startNonce, }) @@ -354,7 +355,7 @@ func GetUserLockedTotal(clientID string) (int64, error) { const GET_USER_LOCKED_TOTAL = `/v1/getUserLockedTotal` - info, err := client.MakeSCRestAPICall(ZCNSCSmartContractAddress, GET_USER_LOCKED_TOTAL, Params{ + info, err := screstapi.MakeSCRestAPICall(ZCNSCSmartContractAddress, GET_USER_LOCKED_TOTAL, Params{ "client_id": clientID, }) @@ -374,3 +375,50 @@ func GetUserLockedTotal(clientID string) (int64, error) { return 0, err } } + +func IsHardforkActivated(name string) (bool, error) { + res, err := screstapi.MakeSCRestAPICall(MinerSmartContractAddress, GET_HARDFORK, Params{ + "name": name, + }) + if err != nil { + return false, fmt.Errorf("error getting hardfork status: %v", err) + } + + var result map[string]string + err = json.Unmarshal(res, &result) + if err != nil { + return false, fmt.Errorf("error unmarshalling hardfork status: %v", err) + } + + roundString, ok := result["round"] + if !ok { + return false, errors.New("hardfork not found") + } + + round, err := strconv.ParseInt(roundString, 10, 64) + if err != nil { + return false, fmt.Errorf("error parsing round: %v", err) + } + + currentRound, err := GetCurrentRound() + if err != nil { + return false, fmt.Errorf("error getting current round: %v", err) + } + + return currentRound >= round, nil +} + +func GetCurrentRound() (int64, error) { + res, err := screstapi.MakeSCRestAPICall("", GET_CURRENT_ROUND, nil, "") + if err != nil { + return 0, err + } + + var round int64 + err = json.Unmarshal(res, &round) + if err != nil { + return 0, fmt.Errorf("error getting current round : %v", err) + } + + return round, nil +} diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index 89111ee59..d8b689ac8 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -45,6 +45,9 @@ const ( GET_MINERSC_USER = "/getUserPools" GET_MINERSC_MINERS = "/getMinerList" GET_MINERSC_SHARDERS = "/getSharderList" + + GET_HARDFORK = "/hardfork" + GET_CURRENT_ROUND = "/v1/current-round" ) const ( diff --git a/zcncore/wallet_mobile.go b/zcncore/wallet_mobile.go index 7fd9b0564..b84955efd 100644 --- a/zcncore/wallet_mobile.go +++ b/zcncore/wallet_mobile.go @@ -5,6 +5,7 @@ package zcncore import ( "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/screstapi" "github.com/0chain/gosdk/core/zcncrypto" ) @@ -31,7 +32,7 @@ func (w *wallet) Sign(hash string) (string, error) { // GetWalletBalance retrieve wallet balance from sharders // - id: client id func GetWalletBalance(id string) (int64, error) { - response, err := client.GetBalance(id) + response, err := screstapi.GetBalance(id) if err != nil { return 0, err }