From 4273608f9787351602d44233d7fc46e2695a713a Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 16 Jan 2025 21:09:45 +0530 Subject: [PATCH] wasm refactor --- wasmsdk/README.md | 2 +- wasmsdk/allocation.go | 50 ++++++++++++++------- wasmsdk/auth_txn.go | 6 +-- wasmsdk/blobber.go | 35 ++++++++++----- wasmsdk/bridge.go | 28 ++++++------ wasmsdk/cache.go | 4 +- wasmsdk/chunked_upload_progress_storer.go | 2 +- wasmsdk/common.go | 10 +---- wasmsdk/demo/index.html | 6 ++- wasmsdk/demo/main.go | 4 +- wasmsdk/demo/zcn.js | 9 ++-- wasmsdk/ethwallet.go | 5 +-- wasmsdk/player_file.go | 2 +- wasmsdk/player_stream.go | 6 +-- wasmsdk/proxy.go | 52 ++++++++++++---------- wasmsdk/sdk.go | 53 +++++++++++++++-------- wasmsdk/statusbar.go | 2 +- wasmsdk/tokenrate.go | 2 +- wasmsdk/wallet.go | 17 +++++--- wasmsdk/wallet_base.go | 2 +- wasmsdk/zbox.go | 2 +- wasmsdk/zcn.go | 8 ++-- 22 files changed, 180 insertions(+), 127 deletions(-) diff --git a/wasmsdk/README.md b/wasmsdk/README.md index 58365f118..c4b52b221 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -3,7 +3,7 @@ # wasmsdk ```go -import "github.com/0chain/gosdk_common/wasmsdk" +import "github.com/0chain/gosdk/wasmsdk" ``` ## Index diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index f3788666c..25aae7861 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -13,9 +13,9 @@ import ( "sync" "syscall/js" + "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) const TOKEN_UNIT int64 = 1e10 @@ -68,7 +68,7 @@ func getAllocationBlobbers(preferredBlobberURLs []string, return sdk.GetBlobberIds(preferredBlobberURLs) } - return sdk.GetAllocationBlobbers(dataShards, parityShards, size, isRestricted, sdk.PriceRange{ + return sdk.GetAllocationBlobbers(sdk.StorageV2, dataShards, parityShards, size, isRestricted, sdk.PriceRange{ Min: uint64(minReadPrice), Max: uint64(maxReadPrice), }, sdk.PriceRange{ @@ -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) { @@ -108,8 +108,10 @@ func createAllocation(datashards, parityshards int, size int64, BlobberIds: blobberIds, ThirdPartyExtendable: setThirdPartyExtendable, IsEnterprise: IsEnterprise, + StorageVersion: sdk.StorageV2, BlobberAuthTickets: blobberAuthTickets, Force: force, + AuthRoundExpiry: authRoundExpiry, } sdkLogger.Info(options) @@ -160,14 +162,17 @@ 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, "", //addBlobberId, "", //addBlobberAuthTicket "", //removeBlobberId, - false, //thirdPartyExtendable, + "", //owner, + "", //ownerSigninPublicKey + false, // thirdPartyExtendable &sdk.FileOptionsParameters{ ForbidUpload: sdk.FileOptionParam{Changed: forbidupload, Value: forbidupload}, ForbidDelete: sdk.FileOptionParam{Changed: forbiddelete, Value: forbiddelete}, @@ -176,6 +181,7 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for ForbidCopy: sdk.FileOptionParam{Changed: forbidcopy, Value: forbidcopy}, ForbidRename: sdk.FileOptionParam{Changed: forbidrename, Value: forbidrename}, }, + "", ) return hash, err @@ -188,14 +194,17 @@ 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, "", //addBlobberId, "", //addBlobberAuthTicket "", //removeBlobberId, - false, //thirdPartyExtendable, + "", //owner, + "", //ownerSigninPublicKey + false, // thirdPartyExtendable &sdk.FileOptionsParameters{ ForbidUpload: sdk.FileOptionParam{Changed: true, Value: true}, ForbidDelete: sdk.FileOptionParam{Changed: true, Value: true}, @@ -204,6 +213,7 @@ func freezeAllocation(allocationID string) (string, error) { ForbidCopy: sdk.FileOptionParam{Changed: true, Value: true}, ForbidRename: sdk.FileOptionParam{Changed: true, Value: true}, }, + "", ) if err == nil { @@ -238,10 +248,10 @@ 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, callbackFuncName string) (string, error) { + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, updateAllocTicket, callbackFuncName string) (string, error) { sdk.SetWasm() allocationObj, err := sdk.GetAllocation(allocationID) if err != nil { @@ -258,7 +268,7 @@ func updateAllocationWithRepair(allocationID string, } } - alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, false, &sdk.FileOptionsParameters{}, statusBar) + 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 } @@ -292,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 string, setThirdPartyExtendable bool) (string, error) { - hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, setThirdPartyExtendable, &sdk.FileOptionsParameters{}) + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, setThirdPartyExtendable bool) (string, error) { + hash, _, err := sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, &sdk.FileOptionsParameters{}, "") if err == nil { clearAllocation(allocationID) @@ -304,6 +314,14 @@ func updateAllocation(allocationID string, return hash, err } +func getUpdateAllocTicket(allocationID, userID, operationType string, roundExpiry int64) (string, error) { + sign, err := sdk.GetUpdateAllocTicket(allocationID, userID, operationType, roundExpiry) + if err != nil { + return "", err + } + return sign, err +} + // getAllocationMinLock retrieves the minimum lock value for the allocation creation, as calculated by the network. // Lock value is the amount of tokens that the client needs to lock in the allocation's write pool // to be able to pay for the write operations. @@ -398,8 +416,8 @@ func lockStakePool(providerType, tokens, fee uint64, providerID string) (string, // - providerType: provider type (1: miner, 2:sharder, 3:blobber, 4:validator, 5:authorizer) // - fee: transaction fees (in SAS) // - providerID: provider id -func unlockStakePool(providerType, fee uint64, providerID string) (int64, error) { - unstake, _, err := sdk.StakePoolUnlock(sdk.ProviderType(providerType), providerID, fee) +func unlockStakePool(providerType, fee uint64, providerID, clientID string) (int64, error) { + unstake, _, err := sdk.StakePoolUnlock(sdk.ProviderType(providerType), providerID, clientID, fee) return unstake, err } diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 42bac292a..cd34f925c 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,9 +7,9 @@ import ( "fmt" "syscall/js" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zcncore" ) type AuthCallbackFunc func(msg string) string diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 40025ddcf..487e05457 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -15,18 +15,19 @@ import ( "syscall/js" "time" - "github.com/0chain/gosdk_common/constants" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/pathutil" - "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk/constants" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/pathutil" + "github.com/0chain/gosdk/core/sys" "github.com/hack-pad/safejs" + "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" + "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" ) @@ -478,7 +479,9 @@ func multiDownload(allocationID, jsonMultiDownloadOptions, authTicket, callbackF } var mf sys.File if option.DownloadToDisk { - terminateWorkersWithAllocation(alloc) + if option.SuggestedName != "" { + fileName = option.SuggestedName + } mf, err = jsbridge.NewFileWriter(fileName) if err != nil { PrintError(err.Error()) @@ -589,6 +592,7 @@ type MultiDownloadOption struct { RemoteFileName string `json:"remoteFileName"` //Required only for file download with auth ticket RemoteLookupHash string `json:"remoteLookupHash,omitempty"` //Required only for file download with auth ticket DownloadToDisk bool `json:"downloadToDisk"` + SuggestedName string `json:"suggestedName,omitempty"` //Suggested name for the file when downloading to disk, if empty will use base of remote path } // MultiOperation do copy, move, delete and createdir operation together @@ -1133,6 +1137,9 @@ func checkAllocStatus(allocationID string) (string, error) { if err != nil { return "", err } + if client.Wallet().ClientID != alloc.Owner { + return "", errors.New("client id does not match with the allocation owner") + } status, blobberStatus, err := alloc.CheckAllocStatus() var statusStr string switch status { @@ -1245,6 +1252,14 @@ func cancelDownloadDirectory(remotePath string) { downloadDirLock.Unlock() } +func cancelDownloadBlocks(allocationID, remotePath string, start, end int64) error { + alloc, err := getAllocation(allocationID) + if err != nil { + return err + } + return alloc.CancelDownloadBlocks(remotePath, start, end) +} + func startListener(respChan chan string) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 45a14ba60..f0f655e12 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -4,18 +4,17 @@ import ( "context" "encoding/base64" "encoding/json" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/zcnbridge" + "github.com/0chain/gosdk/zcnbridge/errors" + "github.com/0chain/gosdk/zcnbridge/log" + "github.com/0chain/gosdk/zcncore" + "github.com/ethereum/go-ethereum/ethclient" "path" "strconv" - - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/zcnbridge" - "github.com/0chain/gosdk_common/zcnbridge/errors" - "github.com/0chain/gosdk_common/zcnbridge/log" - "github.com/0chain/gosdk_common/zcncore" - "github.com/ethereum/go-ethereum/ethclient" ) -var bridge *zcnbridge.BridgeClient +var bridge *zcnbridge.BridgeClient //nolint:unused // initBridge initializes the bridge client // - ethereumAddress: ethereum address of the wallet owner @@ -26,7 +25,7 @@ var bridge *zcnbridge.BridgeClient // - gasLimit: gas limit for the transactions // - value: value to be sent with the transaction (unused) // - consensusThreshold: consensus threshold for the transactions -func initBridge( +func initBridge( //nolint:unused ethereumAddress string, bridgeAddress string, authorizersAddress string, @@ -84,7 +83,9 @@ func burnZCN(amount uint64) string { //nolint // - burnTrxHash: hash of the burn transaction // - timeout: timeout in seconds func mintZCN(burnTrxHash string, timeout int) string { //nolint - mintPayload, err := bridge.QueryZChainMintPayload(burnTrxHash) + mintPayload, + + err := bridge.QueryZChainMintPayload(burnTrxHash) if err != nil { return errors.Wrap("mintZCN", "failed to QueryZChainMintPayload", err).Error() } @@ -114,19 +115,18 @@ func getMintWZCNPayload(burnTrxHash string) string { //nolint:unused } // getNotProcessedWZCNBurnEvents returns all not processed WZCN burn events from the Ethereum network -func getNotProcessedWZCNBurnEvents() string { +func getNotProcessedWZCNBurnEvents() string { //nolint:unused var ( mintNonce int64 res []byte err error ) - if res, err = zcncore.GetMintNonce(); err != nil { return errors.Wrap("getNotProcessedWZCNBurnEvents", "failed to retreive last ZCN processed mint nonce", err).Error() } if err = json.Unmarshal(res, &mintNonce); err != nil { - return errors.New("getNotProcessedWZCNBurnEvents", "failed to unmarshall last ZCN processed mint nonce").Error() + return errors.Wrap("getNotProcessedWZCNBurnEvents", "failed to unmarshal last ZCN processed mint nonce", err).Error() } log.Logger.Debug("MintNonce = " + strconv.Itoa(int(mintNonce))) @@ -162,7 +162,7 @@ func getNotProcessedZCNBurnTickets() string { //nolint:unused } if err = json.Unmarshal(res, &burnTickets); err != nil { - return errors.New("getNotProcessedZCNBurnTickets", "failed to unmarshall ZCN burn tickets").Error() + return errors.Wrap("getNotProcessedZCNBurnTickets", "failed to unmarshal ZCN burn tickets", err).Error() } var result []byte diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 9e0d8c9e1..9089015b3 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -8,9 +8,9 @@ import ( "errors" "time" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/wasmsdk/chunked_upload_progress_storer.go b/wasmsdk/chunked_upload_progress_storer.go index a3435b4ee..d839d5be0 100644 --- a/wasmsdk/chunked_upload_progress_storer.go +++ b/wasmsdk/chunked_upload_progress_storer.go @@ -7,7 +7,7 @@ import ( "sync" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" + "github.com/0chain/gosdk/zboxcore/zboxutil" ) // chunkedUploadProgressStorer load and save upload progress diff --git a/wasmsdk/common.go b/wasmsdk/common.go index a5f22744c..ba2bfe408 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -7,8 +7,8 @@ import ( "errors" "syscall/js" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) // PrintError is to print to stderr @@ -89,11 +89,3 @@ func (h *hasher) WriteToValidationMT(_ []byte) error { func (h *hasher) Finalize() error { return nil } - -func (h *hasher) GetBlockHash() (string, error) { - return "", nil -} - -func (h *hasher) WriteToBlockHasher(buf []byte) error { - return nil -} diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index b73e91cde..e6846532f 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -241,6 +241,8 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates await wasm.setWallet(bls, clientID, publicKey, "", privateKey, publicKey, mnemonic, false); goWasm = wasm + }).catch(e => { + console.log(e) }) onClick('btnSetWallet', async () => { @@ -821,7 +823,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates } objects.push({ - //remotePath: path, + remotePath: path, downloadOp: 1, numBlocks: 0, downloadToDisk: true, @@ -829,7 +831,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates let stringifiedArray = JSON.stringify(objects); try { - const results = await goWasm.sdk.multiDownload('', stringifiedArray, 'eyJjbGllbnRfaWQiOiIiLCJvd25lcl9pZCI6IjI2ZTIzMjFhZWMxZmEyZDY1NGQ1MDQ5OWY3ZjhmYWJhNjNkYWMxYTExYTQwZDU3NDJkNDAzMWJmMzEzMzAxMTYiLCJhbGxvY2F0aW9uX2lkIjoiMDAwMzAzOTA1MGI3ZDdiM2FlNmI3MGEwZTVjMWU4ZjRhOTkxNzc1YWJiOTQ2NjljMDg4YzczNzJlMzYwMzkyYiIsImZpbGVfcGF0aF9oYXNoIjoiYWEzODE0NTM2ZWI2OWQwNjU4ZWM0OTgyZmE3ZTIwM2I2ZGI2ZWExYmU4ZmMxODRiMWJhOTZhMTk3NmMwM2JlOCIsImFjdHVhbF9maWxlX2hhc2giOiIxMjUwMjJhZGRiZTIwZDNhOWUzYjcxZTA0NjUzZjY3YiIsImZpbGVfbmFtZSI6InVidW50dS0yMi4wNC40LWxpdmUtc2VydmVyLWFtZDY0LmlzbyIsInJlZmVyZW5jZV90eXBlIjoiZiIsImV4cGlyYXRpb24iOjAsInRpbWVzdGFtcCI6MTcxNjM3ODIxNiwiZW5jcnlwdGVkIjpmYWxzZSwic2lnbmF0dXJlIjoiYmEzNzQ1NzlmZTczZDc1MWIwMTNiMjM2NjUzZDRiMGYyYzNjZDJlYTMyNTFkODg0MmRiNWQxNTlhNjBiN2ExMiJ9', '') + const results = await goWasm.sdk.multiDownload('', stringifiedArray, '', '') console.log(JSON.stringify(results)) } catch (e) { alert(e) diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 02c903934..64934403a 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,8 +7,8 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zcncore" "github.com/uptrace/bunrouter" ) diff --git a/wasmsdk/demo/zcn.js b/wasmsdk/demo/zcn.js index d64388d24..63585cfb9 100644 --- a/wasmsdk/demo/zcn.js +++ b/wasmsdk/demo/zcn.js @@ -308,7 +308,7 @@ async function createWasm() { (_, key) => (...args) => // eslint-disable-next-line - new Promise(async (resolve, reject) => { + new Promise(async (resolve, reject) => { if (!go || go.exited) { return reject(new Error('The Go instance is not active.')) } @@ -368,8 +368,11 @@ async function createWasm() { ) const proxy = { - bulkUpload: bulkUpload, - setWallet: setWallet, + bulkUpload, + setWallet, + getWalletId, + getPrivateKey, + getPeerPublicKey, sdk: sdkProxy, //expose sdk methods for js jsProxy, //expose js methods for go } diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index f5ad11610..bc2dbc40b 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -1,4 +1,3 @@ -//go:build js && wasm // +build js,wasm package main @@ -9,7 +8,7 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) // JS does not have int64 so we must take a string instead of int64. @@ -115,7 +114,7 @@ func TransferEthTokens(this js.Value, p []js.Value) interface{} { return promiseConstructor.New(handler) } -// Exports public functions in github.com/0chain/gosdk_common/zcncore/ethwallet.go +// Exports public functions in github.com/0chain/gosdk/zcncore/ethwallet.go func IsValidEthAddress(this js.Value, p []js.Value) interface{} { ethAddr := p[0].String() success, err := zcncore.IsValidEthAddress(ethAddr) diff --git a/wasmsdk/player_file.go b/wasmsdk/player_file.go index 7d847adb5..82de0d4c8 100644 --- a/wasmsdk/player_file.go +++ b/wasmsdk/player_file.go @@ -7,8 +7,8 @@ import ( "context" "fmt" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/zboxcore/marker" ) type FilePlayer struct { diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index fa81be29d..51c844e20 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,10 +11,10 @@ import ( "sync" "time" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zboxcore/marker" ) type StreamPlayer struct { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 28fad754c..5ad947fd4 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -13,13 +13,13 @@ import ( "sync" "time" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/version" + "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/core/version" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" "github.com/hack-pad/safejs" @@ -59,18 +59,20 @@ func main() { if c == nil || len(c.Keys) == 0 { return "", errors.New("no keys found") } + pk := c.Keys[0].PrivateKey result, err := jsbridge.Await(jsSign.Invoke(hash, pk)) if len(err) > 0 && !err[0].IsNull() { return "", errors.New("sign: " + err[0].String()) } + return result[0].String(), nil } //update sign with js sign zcncrypto.Sign = signFunc - zcncore.SignFn = signFunc + client.SignFn = signFunc sys.Sign = func(hash, signatureScheme string, keys []sys.KeyPair) (string, error) { // js already has signatureScheme and keys return signFunc(hash) @@ -85,7 +87,7 @@ func main() { data, err := json.Marshal(zcncore.AuthMessage{ Hash: hash, Signature: sig, - ClientID: client.GetClient().ClientID, + ClientID: client.Wallet().ClientID, }) if err != nil { return "", err @@ -201,18 +203,20 @@ func main() { if !(sdk.IsNull() || sdk.IsUndefined()) { jsbridge.BindAsyncFuncs(sdk, map[string]interface{}{ //sdk - "init": initSDKs, - "setWallet": setWallet, - "getPublicEncryptionKey": zcncore.GetPublicEncryptionKey, - "hideLogs": hideLogs, - "showLogs": showLogs, - "getUSDRate": getUSDRate, - "isWalletID": isWalletID, - "getVersion": getVersion, - "getLookupHash": getLookupHash, - "createThumbnail": createThumbnail, - "makeSCRestAPICall": makeSCRestAPICall, - "getWasmType": getWasmType, + "init": initSDKs, + "setWallet": setWallet, + "setWalletMode": setWalletMode, + "getPublicEncryptionKey": zcncore.GetPublicEncryptionKey, + "getPublicEncryptionKeyV2": zcncore.GetPublicEncryptionKeyV2, + "hideLogs": hideLogs, + "showLogs": showLogs, + "getUSDRate": getUSDRate, + "isWalletID": isWalletID, + "getVersion": getVersion, + "getLookupHash": getLookupHash, + "createThumbnail": createThumbnail, + "makeSCRestAPICall": makeSCRestAPICall, + "wasmType": getWasmType, //blobber "delete": Delete, @@ -245,6 +249,7 @@ func main() { "getFileMetaByName": getFileMetaByName, "downloadDirectory": downloadDirectory, "cancelDownloadDirectory": cancelDownloadDirectory, + "cancelDownloadBlocks": cancelDownloadBlocks, // player "play": play, @@ -267,6 +272,7 @@ func main() { "getUpdateAllocationMinLock": getUpdateAllocationMinLock, "getAllocationWith": getAllocationWith, "createfreeallocation": createfreeallocation, + "getUpdateAllocTicket": getUpdateAllocTicket, // claim rewards "collectRewards": collectRewards, @@ -330,7 +336,7 @@ func main() { fmt.Println("__wasm_initialized__ = true;") zcn.Set("__wasm_initialized__", true) - zcn.Set("wasmType", "enterprise") + zcn.Set("wasmType", "normal") } else { PrintError("__zcn_wasm__.sdk is not installed yet") } @@ -341,7 +347,6 @@ func main() { } if mode != "" { - fmt.Println("enterprise wasm sdk") respChan := make(chan string, 1) jsProxy := window.Get("__zcn_worker_wasm__") if !(jsProxy.IsNull() || jsProxy.IsUndefined()) { @@ -352,6 +357,7 @@ func main() { if c == nil || len(c.Keys) == 0 { return "", errors.New("no keys found") } + pk := c.Keys[0].PrivateKey result, err := jsbridge.Await(jsSign.Invoke(hash, pk)) @@ -362,7 +368,7 @@ func main() { } //update sign with js sign zcncrypto.Sign = signFunc - zcncore.SignFn = signFunc + client.SignFn = signFunc sys.Sign = func(hash, signatureScheme string, keys []sys.KeyPair) (string, error) { // js already has signatureScheme and keys return signFunc(hash) diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 036d043d6..07f9974ad 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -7,15 +7,17 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io" - "os" + "github.com/0chain/gosdk/core/client" + "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_common/core/client" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/imageutil" - "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" + + "io" + "os" ) var CreateObjectURL func(buf []byte, mimeType string) string @@ -32,21 +34,34 @@ var CreateObjectURL func(buf []byte, mimeType string) string // - sharderconsensous is the number of sharders to reach consensus func initSDKs(chainID, blockWorker, signatureScheme string, minConfirmation, minSubmit, confirmationChainLength int, - zboxHost, zboxAppType string, sharderconsensous int, isSplit bool) error { + zboxHost, zboxAppType string, sharderConsensous int) error { // Print the parameters beautified - fmt.Printf("{ chainID: %s, blockWorker: %s, signatureScheme: %s, minConfirmation: %d, minSubmit: %d, - confirmationChainLength: %d, zboxHost: %s, zboxAppType: %s, sharderConsensous: %d, isSplit: %t }\n", chainID, - blockWorker, signatureScheme, minConfirmation, minSubmit, - confirmationChainLength, zboxHost, zboxAppType, - sharderConsensous, isSplit) + fmt.Printf("{ chainID: %s, blockWorker: %s, signatureScheme: %s, minConfirmation: %d, minSubmit: %d, confirmationChainLength: %d, zboxHost: %s, zboxAppType: %s, sharderConsensous: %d }\n", chainID, blockWorker, signatureScheme, minConfirmation, minSubmit, confirmationChainLength, zboxHost, zboxAppType, sharderConsensous) + zboxApiClient.SetRequest(zboxHost, zboxAppType) - err := client.InitSDK("{}", blockWorker, chainID, signatureScheme, 0, false, 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 } + sdk.SetWasm() return nil } @@ -57,7 +72,7 @@ func getVersion() string { } func getWasmType() string { - return "enterprise" + return "normal" } var sdkLogger *logger.Logger @@ -118,6 +133,7 @@ func getLookupHash(allocationID string, path string) string { // createThumbnail create thumbnail of an image buffer. It supports // - png + // - jpeg // - gif // - bmp @@ -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 } @@ -156,10 +172,9 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro // - fee is the transaction fee // - desc is the description of the transaction func send(toClientID string, tokens uint64, fee uint64, desc string) (string, error) { - hash, _, _, _, err := zcncore.Send(toClientID, tokens, desc) + _, _, _, txn, err := zcncore.Send(toClientID, tokens, desc) if err != nil { return "", err } - - return hash, nil + return txn.TransactionOutput, nil } diff --git a/wasmsdk/statusbar.go b/wasmsdk/statusbar.go index 000cc20fc..526e2e4f7 100644 --- a/wasmsdk/statusbar.go +++ b/wasmsdk/statusbar.go @@ -7,8 +7,8 @@ import ( "path" "sync" + "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/sys" "gopkg.in/cheggaaa/pb.v1" ) diff --git a/wasmsdk/tokenrate.go b/wasmsdk/tokenrate.go index 456206331..dd5897657 100644 --- a/wasmsdk/tokenrate.go +++ b/wasmsdk/tokenrate.go @@ -3,7 +3,7 @@ package main import ( "context" - "github.com/0chain/gosdk_common/core/tokenrate" + "github.com/0chain/gosdk/core/tokenrate" ) // getUSDRate gets the USD rate for the given crypto symbol diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index c3f0ef305..278a0913f 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -10,9 +10,9 @@ import ( "os" "strconv" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk/wasmsdk/jsbridge" ) func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error { @@ -36,11 +36,10 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon Keys: keys, IsSplit: isSplit, } - client.SetWallet(*w) - fmt.Println("set Wallet, is split:", isSplit) + client.SetWallet(*w) - zboxApiClient.SetWallet(clientID, privateKey, publicKey) + zboxApiClient.SetWallet(clientID, privateKey, clientKey) if mode == "" { // main thread, need to notify the web worker to update wallet // notify the web worker to update wallet if err := jsbridge.PostMessageToAllWorkers(jsbridge.MsgTypeUpdateWallet, map[string]string{ @@ -58,3 +57,9 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon return nil } + +func setWalletMode(mode bool) { + client.SetWalletMode(mode) + + fmt.Println("gosdk setWalletMode: ", "is split:", mode) +} diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index eb30044d7..3f7e1be44 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -1,7 +1,7 @@ package main import ( - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) // Split keys from the primary master key diff --git a/wasmsdk/zbox.go b/wasmsdk/zbox.go index 880f5811e..1d4497eb7 100644 --- a/wasmsdk/zbox.go +++ b/wasmsdk/zbox.go @@ -7,7 +7,7 @@ import ( "context" "errors" - "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk/zboxapi" ) var ( diff --git a/wasmsdk/zcn.go b/wasmsdk/zcn.go index 17dfe788e..f0272e4b5 100644 --- a/wasmsdk/zcn.go +++ b/wasmsdk/zcn.go @@ -4,8 +4,8 @@ package main import ( - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/screstapi" + "github.com/0chain/gosdk/zcncore" ) type Balance struct { @@ -17,12 +17,10 @@ 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 } - balance, err := bal.ToToken() if err != nil { return nil, err