diff --git a/Makefile b/Makefile index 572b1f2ff..1ac52b62f 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ endif include _util/build_$(PLATFORM).mk include _util/build_mobile.mk -.PHONY: build-tools install-all herumi-all gosdk-all sdkver help lint +.PHONY: build-tools install-all herumi-all gosdk-all sdkver help lint docs default: help @@ -108,3 +108,7 @@ install-herumi-ubuntu: rm -R /tmp/mcl && \ rm -R /tmp/bls +docs: + @gomarkdoc --exclude-dirs ./zcncore/sample --output '{{.Dir}}/README.md' --repository.default-branch doc/initial ./... + @sed -i '' -r 's/\\_/_/g' ./**/README.md + @sed -i '' -r 's/\\`/`/g' ./**/README.md \ No newline at end of file diff --git a/README.md b/README.md index eb441e652..bc6f9bb43 100644 --- a/README.md +++ b/README.md @@ -1,221 +1,33 @@ -# 0chain/gosdk + -The Züs client SDK written in Go programming language. +# gosdk -- [GoSDK - a Go based SDK for Züs dStorage]() - - [Züs Overview ](#overview) - - [Installation](#installation) - - [Mobile Builds(iOS and Android)](#mobile-builds) - - [Exposing a gosdk function to mobilesdk](#expose-a-gosdk-function-to-mobilesdk) - - [Export a gosdk function to WebAssembly](#export-a-gosdk-function-to-webassembly) - - [Running Unit Tests](#running-unit-tests) - - [FAQ](#faq) - -## Overview -[Züs](https://zus.network/) is a high-performance cloud on a fast blockchain offering privacy and configurable uptime. It is an alternative to traditional cloud S3 and has shown better performance on a test network due to its parallel data architecture. The technology uses erasure code to distribute the data between data and parity servers. Züs storage is configurable to provide flexibility for IT managers to design for desired security and uptime, and can design a hybrid or a multi-cloud architecture with a few clicks using [Blimp's](https://blimp.software/) workflow, and can change redundancy and providers on the fly. - -For instance, the user can start with 10 data and 5 parity providers and select where they are located globally, and later decide to add a provider on-the-fly to increase resilience, performance, or switch to a lower cost provider. - -Users can also add their own servers to the network to operate in a hybrid cloud architecture. Such flexibility allows the user to improve their regulatory, content distribution, and security requirements with a true multi-cloud architecture. Users can also construct a private cloud with all of their own servers rented across the globe to have a better content distribution, highly available network, higher performance, and lower cost. - -[The QoS protocol](https://medium.com/0chain/qos-protocol-weekly-debrief-april-12-2023-44524924381f) is time-based where the blockchain challenges a provider on a file that the provider must respond within a certain time based on its size to pass. This forces the provider to have a good server and data center performance to earn rewards and income. - -The [privacy protocol](https://zus.network/build) from Züs is unique where a user can easily share their encrypted data with their business partners, friends, and family through a proxy key sharing protocol, where the key is given to the providers, and they re-encrypt the data using the proxy key so that only the recipient can decrypt it with their private key. - -Züs has ecosystem apps to encourage traditional storage consumption such as [Blimp](https://blimp.software/), a S3 server and cloud migration platform, and [Vult](https://vult.network/), a personal cloud app to store encrypted data and share privately with friends and family, and [Chalk](https://chalk.software/), a high-performance story-telling storage solution for NFT artists. - -Other apps are [Bolt](https://bolt.holdings/), a wallet that is very secure with air-gapped 2FA split-key protocol to prevent hacks from compromising your digital assets, and it enables you to stake and earn from the storage providers; [Atlus](https://atlus.cloud/), a blockchain explorer and [Chimney](https://demo.chimney.software/), which allows anyone to join the network and earn using their server or by just renting one, with no prior knowledge required. - -## Installation - -### Supported Platforms -This repository currently supports the following platforms: - - Mac OSX Mojave 10.14.5 or Above - - Linux (Ubuntu/bionic): This includes all Ubuntu 18+ platforms, so Ubuntu 19, Linux Mint 19 etc. (apt based package installer) - - Linux (RHEL/CENTOS 7+): All Releases based on RHEL 7+, Centos 7+, Fedora 30 etc. (yum based package installer) - - ### Instructions - - Go is required to build gosdk code. Instructions can be found [here](https://go.dev/doc/install) - - 1. Save below code as `sdkversion.go` - - package main - - import ( - "fmt" - - "github.com/0chain/gosdk/zcncore" - ) - - func main() { - fmt.Println("gosdk version: ", zcncore.GetVersion()) - } - -2. Run below command: (if you don't have gosdk already in your GOPATH) - - go get github.com/0chain/gosdk -3. Build the sample application sdkversion - - go build -o sdkversion sdkversion.go -4. Run the executable - - ./sdkversion -5. If it prints the gosdk version installed then setup is complete. - - -## Mobile Builds -- gosdk can be built for iOS and Android using gomobile. -- Xcode Command Line Tools is required to build the SDK for iOS. -- Android studio with NDK is required to build the SDK for Android. -- See [FAQ](#faq) for installing Go, gomobile Xcode or Android Studio. - -Steps: -1. Run the command below for the first time to setup the gomobile environment: - - make setup-gomobile -2. In case the Go package is not found in `golang.org/x/mobile/bind`, run: - `go get golang.org/x/mobile/bind` -3. Run below commands in the root folder of the repo to build the Mobile SDK: - - For iOS only: - make build-ios - For Android only: - make build-android - -## Expose a gosdk function to mobilesdk -Examples: -* `mobilesdk/sdk/common.go`, which exports the functions in `core/encryption/hash.go`. - -Steps: - -1. If you are exposing: - - - a new function from an existing file, such as `zboxcore/sdk/allocation.go`, you should add a function to `mobilesdksdk/zbox/allocation.go`. This new function should call the gosdk function you intend to expose. - - a function from a new file, you should create a new `.go` file for it. This should follow the same style as `mobilesdksdk/zbox/allocation.go`. In the new file, call the gosdk function you intend to expose. - -2. Build the Mobile SDK as mentioned in the 'Mobile Builds' section of this file to build the aar file used in the mobile application you are developing. - -## Export a gosdk function to WebAssembly - -Examples: -* `wasmsdk/ethwallet.go` which exports the functions in `zcncore/ethwallet.go`. -* `wasmsdk/wallet.go` which exports one function in `zcncore/wallet.go`. - -Steps: - -1. If you are exporting: - - - a new function from `zcncore/wallet.go`, you should add to `wasmsdk/wallet.go` - - - a function from a new file, you should create a new `.go` file for it, in the same style as `wasmsdk/wallet.go` or `wasmsdk/ethwallet.go` - -2. In func main(), `https://github.com/0chain/gosdk/wasmsdk/proxy.go`, you need to add this line: - - ```golang - js.Global().Set("YOURFUNC", js.FuncOf(YOURFUNC)) - ``` - -3. Now you need to compile a new `.wasm` (e.g. proxy.wasm). Currently, the right version to compile wasm is with Go version 1.16. So make sure you have it to make the wasm build works properly. In order to compile, run the following command: - - ```bash - $ GOOS=js CGO_ENABLED=0 GOARCH=wasm go build -o .wasm github.com/0chain/gosdk/wasmsdk - ``` - -### An important note regarding export of an async function - -If your golang function needs to suport asynchronous execution, you need to add more wrapper code where you are returning a Promise object. - -See "InitZCNSDK" example: - -```golang -func InitZCNSDK(this js.Value, p []js.Value) interface{} { - blockWorker := p[0].String() - signscheme := p[1].String() - - handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - resolve := args[0] - // reject := args[1] - - go func() { - err := zcncore.InitZCNSDK(blockWorker, signscheme) - if err != nil { - fmt.Println("error:", err) - } - resolve.Invoke() - }() - - return nil - }) - - // Create and return the Promise object - promiseConstructor := js.Global().Get("Promise") - return promiseConstructor.New(handler) -} +```go +import "github.com/0chain/gosdk" ``` -## Running Unit Tests +## Index -### BLS unit test +- [type Timestamp](<#Timestamp>) + - [func Now\(\) Timestamp](<#Now>) -It's advisable to put GOPATH as `$TOP/../go`, to avoid conflicts with this command: `go build ./...` -To run all the unit tests in `gosdk`: `go test github.com/0chain/gosdk/zboxcore/sdk -v` -```bash -$ go test ./... -``` + +## type [Timestamp]() -To run all the unit tests in `bls0chain_test.go`, run this command from $TOP: `go test github.com/0chain/gosdk/core/zcncrypto -v` +Timestamp represents Unix time \(e.g. in seconds\) -To run a specific unit test in `bls0chain_test.go`, such as `TestSignatureScheme`, run: `go test github.com/0chain/gosdk/core/zcncrypto -v -run TestSignatureScheme` - -To run the coverage test in `gosdk`: -```bash -$ go test -coverprofile=coverage.out -$ go tool cover -html=coverage.out +```go +type Timestamp int64 ``` -### WebAssembly - -#### Using go test - -1. You need to install nodejs first, see [this page](https://nodejs.org/en/download/) for further instructions - -2. Add `/path/to/go/misc/wasm` to your `$PATH` environment variable (so that `go test` can find `go_js_wasm_exec`). For example in Ubuntu, run `$export PATH=$PATH:/usr/local/go/misc/wasm/`. - -3. You can then run the test by following the [BLS unit test](#bls-unit-test) above by adding the prefix environment `GOOS=js CGO_ENABLED=0 GOARCH=wasm`: - ```bash - go test -tags test -v github.com/0chain/gosdk/wasmsdk - ``` - -#### Test in the client - -1. After you successfully [export the wasm package to proxy.wasm](#how-to-export-a-gosdk-function-to-webassembly), you can test the exported `proxy.wasm`. - -2. We currently have a test page going at the js-client-sdk repo: `https://github.com/0chain/js-client-sdk/blob/gosdk/test/index.html` - -3. You can replace the proxy.wasm at `https://github.com/0chain/js-client-sdk/blob/gosdk/test/proxy.wasm` - -4. You need to start a special test server in order to stream WASM files. Use the following command from js-client-sdk $TOP: `sudo php -S localhost:82 test/server.php` - -5. See "testethwallet" function in index.html for how the testing for ethwallet.go is done. - -6. To test the function you exported, it's probably as simple as calling "HelloWorld()". It should be a 1-liner. - -### How to install `ffmpeg` - -#### On Ubuntu Linux + +### func [Now]() -```bash -sudo apt-get install ffmpeg -sudo apt-get install v4l-utils +```go +func Now() Timestamp ``` -### FAQ ### +Now \- current datetime -- [How to install GO on any platform](https://golang.org/doc/install) -- [How to install different version of GO](https://golang.org/doc/install#extra_versions) -- [How to use go mod](https://blog.golang.org/using-go-modules) -- [What is gomobile](https://godoc.org/golang.org/x/mobile/cmd/gomobile) -- [About XCode](https://developer.apple.com/xcode/) -- [Android Studio](https://developer.android.com/studio) -- [Android NDK](https://developer.android.com/ndk/) +Generated by [gomarkdoc]() diff --git a/constants/context_key.go b/constants/context_key.go index b4c264035..8ac44740a 100644 --- a/constants/context_key.go +++ b/constants/context_key.go @@ -1,21 +1,27 @@ package constants -/*ContextKey - type for key used to store values into context */ +// ContextKey type for key used to store values into context type ContextKey string const ( - // ContextKeyAllocation + // ContextKeyAllocation represents key for context value for allocation ContextKeyAllocation ContextKey = "allocation" - // ContextKeyAllocationObject + + // ContextKeyAllocationObject represents key for context value for allocation object ContextKeyAllocationObject ContextKey = "allocation_object" - // ContextKeyClient + + // ContextKeyClient represents key for context value for client ContextKeyClient ContextKey = "client" - // ContextKeyClientKey + + // ContextKeyClientKey represents key for context value for client key ContextKeyClientKey ContextKey = "client_key" + // ContextKeyClientID represents key for context value for allocation id ContextKeyAllocationID ContextKey = "allocation_id" // ContextKeyClientSignatureHeaderKey represents key for context value passed with common.ClientSignatureHeader request header. ContextKeyClientSignatureHeaderKey ContextKey = "signature" + + // ContextKeyClientSignatureHeaderV2Key represents key for context value passed with common.ClientSignatureHeaderV2 request header. ContextKeyClientSignatureHeaderV2Key ContextKey = "signature_v2" ) diff --git a/constants/errors.go b/constants/errors.go index 4acdc0ad8..703259889 100644 --- a/constants/errors.go +++ b/constants/errors.go @@ -1,4 +1,5 @@ -// Package constants provides constants.the convention of naming is to use MixedCaps or mixedCaps rather than underscores to write multiword names. https://golang.org/doc/effective_go#mixed-caps +// Package constants provides constants. +// The convention of naming is to use MixedCaps or mixedCaps rather than underscores to write multiword names. https://golang.org/doc/effective_go#mixed-caps package constants import "errors" diff --git a/constants/files.go b/constants/files.go index 729ddd85d..0051a1404 100644 --- a/constants/files.go +++ b/constants/files.go @@ -3,10 +3,22 @@ package constants const ( // FileOperationInsert method name of add new file FileOperationInsert = "insert" + + // FileOperationDelete method name of delete file FileOperationDelete = "delete" + + // FileOperationUpdate method name of update file FileOperationUpdate = "update" + + // FileOperationRename method name of rename file FileOperationRename = "rename" + + // FileOperationCopy method name of copy file FileOperationCopy = "copy" + + // FileOperationMove method name of move file FileOperationMove = "move" + + // FileOperationCreateDir method name of create directory FileOperationCreateDir = "createdir" ) diff --git a/core/block/block.go b/core/block/block.go index 8e1abf04c..aec92693d 100644 --- a/core/block/block.go +++ b/core/block/block.go @@ -1,3 +1,7 @@ +// Provides the data structures and methods to work with the block data structure. +// The block data structure is the core data structure in the 0chain protocol. +// It is used to store the transactions and the state of the system at a given point in time. +// The block data structure is used to create the blockchain, which is a chain of blocks that are linked together using the hash of the previous block. package block import ( @@ -23,6 +27,8 @@ type Header struct { NumTxns int64 `json:"num_txns,omitempty"` } +// IsBlockExtends - check if the block extends the previous block +// - prevHash is the hash of the previous block func (h *Header) IsBlockExtends(prevHash string) bool { var data = fmt.Sprintf("%s:%s:%d:%d:%d:%s:%s", h.MinerID, prevHash, h.CreationDate, h.Round, h.RoundRandomSeed, h.MerkleTreeRoot, diff --git a/core/build.go b/core/build.go index 9a8bc9592..97e341d61 100644 --- a/core/build.go +++ b/core/build.go @@ -1 +1,2 @@ +// Provides some low-level functions and types that are used by the SDK. package core diff --git a/core/common/misc.go b/core/common/misc.go index 0d926924f..e8377e04a 100644 --- a/core/common/misc.go +++ b/core/common/misc.go @@ -59,9 +59,10 @@ func (s Size) String() string { // reParseToken is a regexp to parse string representation of token var reParseToken = regexp.MustCompile(`^((?:\d*\.)?\d+)\s+(SAS|sas|uZCN|uzcn|mZCN|mzcn|ZCN|zcn)$`) -// Balance represents 0chain native token +// Balance represents client's balance in Züs native token fractions (SAS = 10^-10 ZCN). type Balance uint64 +// ToToken converts Balance to ZCN tokens. func (b Balance) ToToken() (float64, error) { if b > math.MaxInt64 { return 0.0, ErrTooLarge @@ -79,6 +80,8 @@ func (b Balance) String() string { return "" } +// Format returns a string representation of the balance with the given unit. +// - unit is the balance unit. func (b Balance) Format(unit BalanceUnit) (string, error) { v := float64(b) if v < 0 { @@ -99,6 +102,7 @@ func (b Balance) Format(unit BalanceUnit) (string, error) { return fmt.Sprintf("%.3f %v", v, unit), nil } +// AutoFormat returns a string representation of the balance with the most func (b Balance) AutoFormat() (string, error) { switch { case b/1e10 > 0: @@ -112,6 +116,7 @@ func (b Balance) AutoFormat() (string, error) { } // ToBalance converts ZCN tokens to Balance. +// - token amount of ZCN tokens. func ToBalance(token float64) (Balance, error) { d := decimal.NewFromFloat(token) if d.Sign() == -1 { @@ -150,10 +155,12 @@ func AddBalance(c, b Balance) (Balance, error) { return sum, nil } +// FormatBalance returns a string representation of the balance with the given unit. func FormatBalance(b Balance, unit BalanceUnit) (string, error) { return b.Format(unit) } +// AutoFormatBalance returns a string representation of the balance with the most func AutoFormatBalance(b Balance) (string, error) { return b.AutoFormat() } diff --git a/core/common/time.go b/core/common/time.go index c9b5ab168..dbad4a2e4 100644 --- a/core/common/time.go +++ b/core/common/time.go @@ -10,7 +10,7 @@ import ( // Timestamp represents Unix time (e.g. in seconds) type Timestamp int64 -// Now - current datetime +// Now current datetime func Now() Timestamp { return Timestamp(time.Now().Unix()) } @@ -29,10 +29,15 @@ func (t Timestamp) ToTime() time.Time { var ErrInvalidTime = errors.New("invalid time") // ParseTime parse a time string with 4 formats -// +1h5m : now (local timezone) + 1h5m -// +3900 : now (local timezone) +3900s -// 1647858200 : Unix timestamp -// 2022-03-21 10:21:38 : parse UTC date string with YYYY-MM-dd HH:mm:ss +// +// +1h5m : now (local timezone) + 1h5m +// +3900 : now (local timezone) +3900s +// 1647858200 : Unix timestamp +// 2022-03-21 10:21:38 : parse UTC date string with YYYY-MM-dd HH:mm:ss +// +// Parameters +// - now is the current time +// - input is the time string to parse func ParseTime(now time.Time, input string) (*time.Time, error) { if len(input) == 0 { diff --git a/core/common/utils.go b/core/common/utils.go index b4a07d1fe..cd7beb5b4 100644 --- a/core/common/utils.go +++ b/core/common/utils.go @@ -1,3 +1,4 @@ +// Provides the data structures and methods to work with the common data structures. package common import ( diff --git a/core/conf/config.go b/core/conf/config.go index 5b770768e..7bd1f5f2a 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -1,3 +1,6 @@ +// Provides the data structures and methods to work with the configuration data structure. +// This includes parsing, loading, and saving the configuration data structure. +// It uses the viper library to parse and manage the configuration data structure. package conf import ( @@ -27,18 +30,19 @@ const ( ) // Config settings from ~/.zcn/config.yaml -// block_worker: http://198.18.0.98:9091 -// signature_scheme: bls0chain -// min_submit: 50 -// min_confirmation: 50 -// confirmation_chain_length: 3 -// max_txn_query: 5 -// query_sleep_time: 5 -// # # OPTIONAL - Uncomment to use/ Add more if you want -// # preferred_blobbers: -// # - http://one.devnet-0chain.net:31051 -// # - http://one.devnet-0chain.net:31052 -// # - http://one.devnet-0chain.net:31053 +// +// block_worker: http://198.18.0.98:9091 +// signature_scheme: bls0chain +// min_submit: 50 +// min_confirmation: 50 +// confirmation_chain_length: 3 +// max_txn_query: 5 +// query_sleep_time: 5 +// # # OPTIONAL - Uncomment to use/ Add more if you want +// # preferred_blobbers: +// # - http://one.devnet-0chain.net:31051 +// # - http://one.devnet-0chain.net:31052 +// # - http://one.devnet-0chain.net:31053 type Config struct { // BlockWorker the url of 0dns's network api BlockWorker string `json:"block_worker,omitempty"` @@ -76,7 +80,8 @@ type Config struct { SharderConsensous int `json:"sharder_consensous"` } -// LoadConfigFile load and parse Config from file +// LoadConfigFile load and parse SDK Config from file +// - file: config file path (full path) func LoadConfigFile(file string) (Config, error) { var cfg Config diff --git a/core/conf/mocks/doc.go b/core/conf/mocks/doc.go new file mode 100644 index 000000000..d5f5048fa --- /dev/null +++ b/core/conf/mocks/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! Do not use. +package mocks \ No newline at end of file diff --git a/core/conf/network.go b/core/conf/network.go index c2862c2bb..899e3acda 100644 --- a/core/conf/network.go +++ b/core/conf/network.go @@ -23,6 +23,7 @@ func (n *Network) IsValid() bool { } // LoadNetworkFile load and parse Network from file +// - file is the path of the file (full path) func LoadNetworkFile(file string) (Network, error) { var network Network diff --git a/core/conf/vars.go b/core/conf/vars.go index 508247e99..211c23c05 100644 --- a/core/conf/vars.go +++ b/core/conf/vars.go @@ -29,7 +29,7 @@ var ( ErrConfigNotInitialized = errors.New("[conf]conf.cfg is not initialized. please initialize it by conf.InitClientConfig") ) -// GetClientConfig get global client config +// GetClientConfig get global client config from the SDK configuration func GetClientConfig() (*Config, error) { if cfg == nil { return nil, ErrConfigNotInitialized @@ -38,7 +38,7 @@ func GetClientConfig() (*Config, error) { return cfg, nil } -// InitClientConfig set global client config +// InitClientConfig set global client SDK config func InitClientConfig(c *Config) { onceCfg.Do(func() { sharderConsensous := c.SharderConsensous @@ -50,7 +50,7 @@ func InitClientConfig(c *Config) { }) } -// InitChainNetwork set global chain network +// InitChainNetwork set global chain network for the SDK given its configuration func InitChainNetwork(n *Network) { if n == nil { return diff --git a/core/encryption/hash.go b/core/encryption/hash.go index 088de16c6..310c9bb2d 100644 --- a/core/encryption/hash.go +++ b/core/encryption/hash.go @@ -1,3 +1,4 @@ +// Provides the data structures and methods used in encryption. package encryption import ( @@ -10,14 +11,17 @@ import ( const HASH_LENGTH = 32 +// HashBytes hash bytes type HashBytes [HASH_LENGTH]byte -/*Hash - hash the given data and return the hash as hex string */ +// Hash hash the given data and return the hash as hex string +// - data is the data to hash func Hash(data interface{}) string { return hex.EncodeToString(RawHash(data)) } -/*RawHash - Logic to hash the text and return the hash bytes */ +// RawHash Logic to hash the text and return the hash bytes +// - data is the data to hash func RawHash(data interface{}) []byte { var databuf []byte switch dataImpl := data.(type) { @@ -36,6 +40,8 @@ func RawHash(data interface{}) []byte { return hash.Sum(buf) } +// ShaHash hash the given data and return the hash as hex string +// - data is the data to hash func ShaHash(data interface{}) []byte { var databuf []byte switch dataImpl := data.(type) { @@ -53,12 +59,14 @@ func ShaHash(data interface{}) []byte { return hash.Sum(nil) } -/*FastHash - sha1 hash the given data and return the hash as hex string */ +// FastHash - sha1 hash the given data and return the hash as hex string +// - data is the data to hash func FastHash(data interface{}) string { return hex.EncodeToString(RawFastHash(data)) } -/*RawFastHash - Logic to sha1 hash the text and return the hash bytes */ +// RawFastHash - Logic to sha1 hash the text and return the hash bytes +// - data is the data to hash func RawFastHash(data interface{}) []byte { var databuf []byte switch dataImpl := data.(type) { diff --git a/core/imageutil/thumbnailer.go b/core/imageutil/thumbnailer.go index e84b0bb9b..4d9dae350 100644 --- a/core/imageutil/thumbnailer.go +++ b/core/imageutil/thumbnailer.go @@ -1,3 +1,4 @@ +// Provides helper methods and data structures to work with images. package imageutil import ( diff --git a/core/logger/logger.go b/core/logger/logger.go index 8ca922a22..69b361956 100644 --- a/core/logger/logger.go +++ b/core/logger/logger.go @@ -1,3 +1,4 @@ +// Provides a simple logger for the SDK. package logger import ( @@ -59,7 +60,8 @@ func syncPrefixes(maxPrefixLen int, loggers []*Logger) { } } -// SyncLoggers - syncs the loggers +// SyncLoggers syncs the loggers prefixes +// - loggers is the list of loggers to sync func SyncLoggers(loggers []*Logger) { maxPrefixLen := 0 for _, lgr := range loggers { diff --git a/core/node/node.go b/core/node/node.go index b5c623e61..2a3ef7de0 100644 --- a/core/node/node.go +++ b/core/node/node.go @@ -1,3 +1,4 @@ +// Provides functions and data structures to interact with the system nodes in the context of the blockchain network. package node import ( diff --git a/core/pathutil/path.go b/core/pathutil/path.go index cb40ee927..91b36d967 100644 --- a/core/pathutil/path.go +++ b/core/pathutil/path.go @@ -1,3 +1,4 @@ +// Provides utility functions for working with file paths. package pathutil import ( @@ -9,6 +10,7 @@ import ( // If there is no Separator in path, Split returns an empty dir // and file set to path. // The returned values have the property that path = dir+file. +// - path is the path to be split. func Split(path string) (dir, file string) { if path == "" { return "", "" @@ -28,6 +30,7 @@ func Split(path string) (dir, file string) { } // Dir returns all but the last element of path, typically the path's directory. +// - path is the path to be split. func Dir(path string) string { dir, _ := Split(path) diff --git a/core/resty/doc.go b/core/resty/doc.go new file mode 100644 index 000000000..1f3a8c885 --- /dev/null +++ b/core/resty/doc.go @@ -0,0 +1,2 @@ +// HTTP and REST client library with parallel feature. +package resty \ No newline at end of file diff --git a/core/resty/mocks/doc.go b/core/resty/mocks/doc.go new file mode 100644 index 000000000..d5f5048fa --- /dev/null +++ b/core/resty/mocks/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! Do not use. +package mocks \ No newline at end of file diff --git a/core/resty/resty.go b/core/resty/resty.go index 260d58ea9..49ea9d695 100644 --- a/core/resty/resty.go +++ b/core/resty/resty.go @@ -1,4 +1,3 @@ -// Package resty HTTP and REST client library with parallel feature package resty import ( diff --git a/core/sys/doc.go b/core/sys/doc.go new file mode 100644 index 000000000..5fc9edc91 --- /dev/null +++ b/core/sys/doc.go @@ -0,0 +1,2 @@ +// Provides functions and data structures for working with memory and disk file systems. +package sys \ No newline at end of file diff --git a/core/sys/util.go b/core/sys/util.go index 3b69d90df..e911ff3f2 100644 --- a/core/sys/util.go +++ b/core/sys/util.go @@ -8,6 +8,8 @@ import ( "time" ) +// MemFile represents a file totally loaded in memory +// Aware of the file size, so it can seek and truncate. type MemFile struct { Name string Buffer []byte // file content @@ -17,9 +19,12 @@ type MemFile struct { reader io.Reader } +// Stat returns the file information func (f *MemFile) Stat() (fs.FileInfo, error) { return &MemFileInfo{name: f.Name, f: f}, nil } + +// Read reads data from the file func (f *MemFile) Read(p []byte) (int, error) { if f.reader == nil { f.reader = bytes.NewReader(f.Buffer) @@ -27,11 +32,14 @@ func (f *MemFile) Read(p []byte) (int, error) { return f.reader.Read(p) } + +// Write writes data to the file func (f *MemFile) Write(p []byte) (n int, err error) { f.Buffer = append(f.Buffer, p...) return len(p), nil } +// WriteAt writes data to the file at a specific offset func (f *MemFile) WriteAt(p []byte, offset int64) (n int, err error) { if offset < 0 || offset > int64(len(f.Buffer)) || len(p) > len(f.Buffer)-int(offset) { return 0, io.ErrShortWrite @@ -42,10 +50,12 @@ func (f *MemFile) WriteAt(p []byte, offset int64) (n int, err error) { return len(p), nil } +// InitBuffer initializes the buffer with a specific size func (f *MemFile) InitBuffer(size int) { f.Buffer = make([]byte, size) } +// Sync not implemented func (f *MemFile) Sync() error { return nil } @@ -70,42 +80,54 @@ func (f *MemFile) Close() error { return nil } +// MemFileInfo represents file information type MemFileInfo struct { name string f *MemFile } +// Name returns the base name of the file func (i *MemFileInfo) Name() string { return i.name } + +// Size returns the size of the file func (i *MemFileInfo) Size() int64 { return int64(len(i.f.Buffer)) } +// Mode returns the file mode bits func (i *MemFileInfo) Mode() fs.FileMode { return i.f.Mode } +// Type returns the file mode type func (i *MemFileInfo) Type() fs.FileMode { return i.f.Mode.Type() } +// ModTime returns the modification time of the file func (i *MemFileInfo) ModTime() time.Time { return i.f.ModTime } +// IsDir returns true if the file is a directory func (i *MemFileInfo) IsDir() bool { return i.f.Mode&fs.ModeDir != 0 } +// Sys returns the underlying data source (can return nil) func (i *MemFileInfo) Sys() interface{} { return i.f.Sys } +// Info returns the file information func (i *MemFileInfo) Info() (fs.FileInfo, error) { return i, nil } +// MemChanFile used to read or write file content sequentially through a buffer channel. +// Not aware of the file size, so it can't seek or truncate. type MemChanFile struct { Name string Buffer chan []byte // file content @@ -117,9 +139,14 @@ type MemChanFile struct { data []byte } +// Stat returns the file information func (f *MemChanFile) Stat() (fs.FileInfo, error) { return &MemFileChanInfo{name: f.Name, f: f}, nil } + +// Read reads data from the file through the buffer channel +// It returns io.EOF when the buffer channel is closed. +// - p: file in bytes loaded from the buffer channel func (f *MemChanFile) Read(p []byte) (int, error) { select { case err := <-f.ErrChan: @@ -136,6 +163,10 @@ func (f *MemChanFile) Read(p []byte) (int, error) { } } +// Write writes data to the file through the buffer channel +// It writes the data to the buffer channel in chunks of ChunkWriteSize. +// If ChunkWriteSize is 0, it writes the data as a whole. +// - p: file in bytes to write to the buffer channel func (f *MemChanFile) Write(p []byte) (n int, err error) { if f.ChunkWriteSize == 0 { data := make([]byte, len(p)) @@ -150,6 +181,9 @@ func (f *MemChanFile) Write(p []byte) (n int, err error) { return len(p), nil } +// Sync write the data chunk to the buffer channel +// It writes the data to the buffer channel in chunks of ChunkWriteSize. +// If ChunkWriteSize is 0, it writes the data as a whole. func (f *MemChanFile) Sync() error { current := 0 for ; current < len(f.data); current += f.ChunkWriteSize { @@ -162,47 +196,60 @@ func (f *MemChanFile) Sync() error { f.data = nil return nil } + +// Seek not implemented func (f *MemChanFile) Seek(offset int64, whence int) (ret int64, err error) { return 0, nil } +// Close closes the buffer channel func (f *MemChanFile) Close() error { close(f.Buffer) return nil } +// MemFileChanInfo represents file information type MemFileChanInfo struct { name string f *MemChanFile } +// Name returns the base name of the file func (i *MemFileChanInfo) Name() string { return i.name } + +// Size not implemented func (i *MemFileChanInfo) Size() int64 { return 0 } +// Mode returns the file mode bits func (i *MemFileChanInfo) Mode() fs.FileMode { return i.f.Mode } +// Type returns the file mode type func (i *MemFileChanInfo) Type() fs.FileMode { return i.f.Mode.Type() } +// ModTime returns the modification time of the file func (i *MemFileChanInfo) ModTime() time.Time { return i.f.ModTime } +// IsDir returns true if the file is a directory func (i *MemFileChanInfo) IsDir() bool { return i.f.Mode&fs.ModeDir != 0 } +// Sys returns the underlying data source (can return nil) func (i *MemFileChanInfo) Sys() interface{} { return i.f.Sys } +// Info returns the file information func (i *MemFileChanInfo) Info() (fs.FileInfo, error) { return i, nil } diff --git a/core/tokenrate/doc.go b/core/tokenrate/doc.go new file mode 100644 index 000000000..c268146ea --- /dev/null +++ b/core/tokenrate/doc.go @@ -0,0 +1,2 @@ +// Provides functions to get token rates from different sources (for example: CoinGecko, Bancor, Uniswap, CoinMarketCap). +package tokenrate diff --git a/core/transaction/entity.go b/core/transaction/entity.go index 1841e95bc..b2586a177 100644 --- a/core/transaction/entity.go +++ b/core/transaction/entity.go @@ -1,3 +1,4 @@ +// Provides low-level functions and types to work with the native smart contract transactions. package transaction import ( @@ -50,6 +51,7 @@ type TxnReceipt struct { Transaction *Transaction } +// SmartContractTxnData data structure to hold the smart contract transaction data type SmartContractTxnData struct { Name string `json:"name"` InputArgs interface{} `json:"input"` diff --git a/core/util/doc.go b/core/util/doc.go new file mode 100644 index 000000000..425c3445d --- /dev/null +++ b/core/util/doc.go @@ -0,0 +1,2 @@ +// Provides miscellaneous utility functions and types for the SDK. +package util diff --git a/core/util/fixed_merkle_tree.go b/core/util/fixed_merkle_tree.go index 991d25cbf..239dd923a 100644 --- a/core/util/fixed_merkle_tree.go +++ b/core/util/fixed_merkle_tree.go @@ -14,9 +14,16 @@ import ( ) const ( + // MerkleChunkSize is the size of a chunk of data that is hashed MerkleChunkSize = 64 + + // MaxMerkleLeavesSize is the maximum size of the data that can be written to the merkle tree MaxMerkleLeavesSize = 64 * 1024 + + // FixedMerkleLeaves is the number of leaves in the fixed merkle tree FixedMerkleLeaves = 1024 + + // FixedMTDepth is the depth of the fixed merkle tree FixedMTDepth = 11 ) diff --git a/core/util/rand.go b/core/util/rand.go index 1ac279240..540c39bdb 100644 --- a/core/util/rand.go +++ b/core/util/rand.go @@ -6,6 +6,9 @@ import ( "time" ) +// MinInt returns the minimum of two integers +// - x: first integer +// - y: second integer func MinInt(x, y int) int { if x < y { return x @@ -13,6 +16,9 @@ func MinInt(x, y int) int { return y } +// MaxInt returns the maximum of two integers +// - x: first integer +// - y: second integer func MaxInt(x, y int) int { if x > y { return x @@ -20,6 +26,9 @@ func MaxInt(x, y int) int { return y } +// MinInt64 returns the minimum of two int64 +// - x: first int64 +// - y: second int64 func MinInt64(x, y int64) int64 { if x < y { return x @@ -27,6 +36,9 @@ func MinInt64(x, y int64) int64 { return y } +// MaxInt64 returns the maximum of two int64 +// - x: first int64 +// - y: second int64 func MaxInt64(x, y int64) int64 { if x > y { return x @@ -34,6 +46,8 @@ func MaxInt64(x, y int64) int64 { return y } +// Shuffle returns a shuffled version of a string slice +// - in: input slice func Shuffle(in []string) (shuffle []string) { shuffle = make([]string, len(in)) copy(shuffle, in) diff --git a/core/util/secure_value.go b/core/util/secure_value.go index 3eead5d9b..aa41108ed 100644 --- a/core/util/secure_value.go +++ b/core/util/secure_value.go @@ -7,10 +7,15 @@ import ( "github.com/0chain/gosdk/core/encryption" ) -/*Hashable - anything that can provide it's hash */ +// Hashable anything that can provide it's hash type Hashable interface { + // GetHash get the hash of the object GetHash() string + + // GetHashBytes get the hash of the object as bytes GetHashBytes() []byte + + // Write write the bytes to the hash Write(b []byte) (int, error) } diff --git a/core/util/validation_tree.go b/core/util/validation_tree.go index 1bfd6045c..08e70356f 100644 --- a/core/util/validation_tree.go +++ b/core/util/validation_tree.go @@ -13,7 +13,10 @@ import ( ) const ( + // Left tree node chile Left = iota + + // Right tree node child Right ) @@ -22,6 +25,7 @@ const ( ADD_LENGTH = 320 ) +// ValidationTree is a merkle tree that is used to validate the data type ValidationTree struct { writeLock sync.Mutex writeCount int @@ -34,18 +38,23 @@ type ValidationTree struct { validationRoot []byte } +// GetLeaves returns the leaves of the validation tree func (v *ValidationTree) GetLeaves() [][]byte { return v.leaves } +// SetLeaves sets the leaves of the validation tree. +// - leaves: leaves of the validation tree, each leaf is in byte format func (v *ValidationTree) SetLeaves(leaves [][]byte) { v.leaves = leaves } +// GetDataSize returns the data size of the validation tree func (v *ValidationTree) GetDataSize() int64 { return v.dataSize } +// GetValidationRoot returns the validation root of the validation tree func (v *ValidationTree) GetValidationRoot() []byte { if len(v.validationRoot) > 0 { return v.validationRoot @@ -54,6 +63,7 @@ func (v *ValidationTree) GetValidationRoot() []byte { return v.validationRoot } +// Write writes the data to the validation tree func (v *ValidationTree) Write(b []byte) (int, error) { v.writeLock.Lock() defer v.writeLock.Unlock() @@ -72,7 +82,7 @@ func (v *ValidationTree) Write(b []byte) (int, error) { byteLen := len(b) shouldContinue := true - // j is initialized to MaxMerkleLeavesSize - writeCount so as to make up MaxMerkleLeavesSize with previouly + // j is initialized to MaxMerkleLeavesSize - writeCount so as to make up MaxMerkleLeavesSize with previously // read bytes. If previously it had written MaxMerkleLeavesSize - 1, then j will be initialized to 1 so // in first iteration it will only read 1 byte and write it to v.h after which hash of v.h will be calculated // and stored in v.Leaves and v.h will be reset. @@ -101,6 +111,7 @@ func (v *ValidationTree) Write(b []byte) (int, error) { return byteLen, nil } +// CalculateDepth calculates the depth of the validation tree func (v *ValidationTree) CalculateDepth() int { return int(math.Ceil(math.Log2(float64(len(v.leaves))))) + 1 } @@ -141,6 +152,7 @@ func (v *ValidationTree) calculateRoot() { v.validationRoot = nodes[0] } +// Finalize finalizes the validation tree, set isFinalized to true and calculate the root func (v *ValidationTree) Finalize() error { v.writeLock.Lock() defer v.writeLock.Unlock() @@ -165,6 +177,8 @@ func (v *ValidationTree) Finalize() error { return nil } +// NewValidationTree creates a new validation tree +// - dataSize is the size of the data func NewValidationTree(dataSize int64) *ValidationTree { totalLeaves := (dataSize + MaxMerkleLeavesSize - 1) / MaxMerkleLeavesSize if totalLeaves == 0 { diff --git a/core/version/doc.go b/core/version/doc.go new file mode 100644 index 000000000..04305704b --- /dev/null +++ b/core/version/doc.go @@ -0,0 +1,3 @@ +// AUTOGENERATED! Do not use. +// Provide current version of the SDK +package version \ No newline at end of file diff --git a/core/zcncrypto/factory.go b/core/zcncrypto/factory.go index b04422cb4..92e287b50 100644 --- a/core/zcncrypto/factory.go +++ b/core/zcncrypto/factory.go @@ -12,6 +12,7 @@ import ( ) // NewSignatureScheme creates an instance for using signature functions +// - sigScheme signature scheme to be used func NewSignatureScheme(sigScheme string) SignatureScheme { switch sigScheme { case "ed25519": @@ -62,7 +63,7 @@ func UnmarshalSignatureSchemes(sigScheme string, obj interface{}) ([]SignatureSc } } -//GenerateThresholdKeyShares given a signature scheme will generate threshold sig keys +// GenerateThresholdKeyShares given a signature scheme will generate threshold sig keys func GenerateThresholdKeyShares(t, n int, originalKey SignatureScheme) ([]SignatureScheme, error) { b0ss, ok := originalKey.(*HerumiScheme) if !ok { diff --git a/core/zcncrypto/signature_scheme.go b/core/zcncrypto/signature_scheme.go index c2683630a..da806b163 100644 --- a/core/zcncrypto/signature_scheme.go +++ b/core/zcncrypto/signature_scheme.go @@ -1,3 +1,4 @@ +// Provides low-level functions and types to work with different cryptographic schemes with a unified interface and provide cryptographic operations. package zcncrypto import ( @@ -8,6 +9,7 @@ import ( "github.com/tyler-smith/go-bip39" ) +// CryptoVersion - version of the crypto library const CryptoVersion = "1.0" // KeyPair private and publickey @@ -16,15 +18,28 @@ type KeyPair struct { PrivateKey string `json:"private_key"` } -// Wallet structure +// Wallet represents client wallet information type Wallet struct { - ClientID string `json:"client_id"` - ClientKey string `json:"client_key"` - Keys []KeyPair `json:"keys"` - Mnemonic string `json:"mnemonics"` - Version string `json:"version"` - DateCreated string `json:"date_created"` - Nonce int64 `json:"nonce"` + // ClientID client unique identifier + ClientID string `json:"client_id"` + + // ClientKey client public key + ClientKey string `json:"client_key"` + + // Keys private and public key pair + Keys []KeyPair `json:"keys"` + + // Mnemonic recovery phrase of the wallet + Mnemonic string `json:"mnemonics"` + + // Version version of the wallet + Version string `json:"version"` + + // DateCreated date of wallet creation + DateCreated string `json:"date_created"` + + // Nonce nonce of the wallet + Nonce int64 `json:"nonce"` } // SignatureScheme - an encryption scheme for signing and verifying messages diff --git a/dev/blobber/model/ref.go b/dev/blobber/model/ref.go index 5e4081e97..75759b027 100644 --- a/dev/blobber/model/ref.go +++ b/dev/blobber/model/ref.go @@ -12,7 +12,10 @@ import ( ) const ( - FILE = "f" + // FileRef represents a file + FILE = "f" + + // FileRef represents a directory DIRECTORY = "d" CHUNK_SIZE = 64 * 1024 @@ -142,7 +145,9 @@ func (r *Ref) CalculateDirHash(ctx context.Context) (string, error) { return r.Hash, nil } -// GetReferenceLookup hash(allocationID + ":" + path) +// GetReferenceLookup hash(allocationID + ":" + path) which is used to lookup the file reference in the db. +// - allocationID is the allocation ID. +// - path is the path of the file. func GetReferenceLookup(allocationID string, path string) string { return encryption.Hash(allocationID + ":" + path) } diff --git a/dev/server.go b/dev/server.go index 98a6221f9..3349bc937 100644 --- a/dev/server.go +++ b/dev/server.go @@ -1,4 +1,4 @@ -// package dev providers tools for local development +// Providers tools for local development - do not use. package dev import ( diff --git a/mobilesdk/build.go b/mobilesdk/build.go new file mode 100644 index 000000000..d76ddf6e6 --- /dev/null +++ b/mobilesdk/build.go @@ -0,0 +1,2 @@ +// Provides interface for the SDK functions to be used to build an SDK version for the mobile apps. +package mobilesdk \ No newline at end of file diff --git a/mobilesdk/sdk/common.go b/mobilesdk/sdk/common.go index 786c88e35..5a189b757 100644 --- a/mobilesdk/sdk/common.go +++ b/mobilesdk/sdk/common.go @@ -7,13 +7,12 @@ import ( "github.com/0chain/gosdk/core/encryption" ) -// GetLookupHash get lookup hash with allocation id and path -// ## Inputs -// - allocationID -// - remotePath +// GetLookupHash get lookup hash with allocation id and path. +// Lookuphash is a hashed value of the augmentation of allocation id and remote path. +// It is used to identify the file in the blobbers. // -// ## Outputs -// - lookup_hash +// - allocationID : allocation id +// - remotePath : remote path func GetLookupHash(allocationID string, remotePath string) string { return encryption.Hash(allocationID + ":" + remotePath) } diff --git a/mobilesdk/sdk/doc.go b/mobilesdk/sdk/doc.go new file mode 100644 index 000000000..41687fdcc --- /dev/null +++ b/mobilesdk/sdk/doc.go @@ -0,0 +1,2 @@ +// Provides the exported functions and types that are used to build the mobile SDK. +package sdk \ No newline at end of file diff --git a/mobilesdk/sdk/keys.go b/mobilesdk/sdk/keys.go index b563823e6..ebfd49562 100644 --- a/mobilesdk/sdk/keys.go +++ b/mobilesdk/sdk/keys.go @@ -17,7 +17,11 @@ import ( // } // ], // "mnemonics":"guitar cook depend snake response major argue abstract script tonight energy soccer copy latin street bracket combine image fabric maximum mercy icon bitter dwarf", -// "version":"1.0","date_created":"2022-11-02T10:21:32+08:00","nonce":0} +// "version":"1.0","date_created":"2022-11-02T10:21:32+08:00","nonce":0 +// } +// - privateKey: private key to use for signing +// - signatureScheme: signature scheme to use for signing +// - numSplits: number of splits func SplitKeys(privateKey, signatureScheme string, numSplits int) ([]byte, error) { signScheme := zcncrypto.NewSignatureScheme(signatureScheme) if signScheme != nil { diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 15def93b3..2068b58d5 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -49,28 +49,29 @@ type StorageSDK struct { client *client.Client } -// SetLogFile - setting up log level for core libraries -// -// # Inputs -// - logFile: the output file of logs -// - verbose: output detail logs +// SetLogFile setup log level for core libraries +// - logFile: the output file of logs +// - verbose: output detail logs func SetLogFile(logFile string, verbose bool) { zcncore.SetLogFile(logFile, verbose) sdk.SetLogFile(logFile, verbose) } // SetLogLevel set the log level. -// lvl - 0 disabled; higher number (upto 4) more verbosity +// +// `lvl` - 0 disabled; higher number (upto 4) more verbosity func SetLogLevel(logLevel int) { sdk.SetLogLevel(logLevel) } +// Init init the sdk with chain config +// - chainConfigJson: chain config json string func Init(chainConfigJson string) error { return zcncore.Init(chainConfigJson) } -// InitStorageSDK - init storage sdk from config -// - clientJson +// InitStorageSDK init storage sdk from config +// - clientJson example // { // "client_id":"8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0", // "client_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", @@ -84,7 +85,7 @@ func Init(chainConfigJson string) error { // "date_created":"1668667145", // "nonce":0 // } -// - configJson +// - configJson example // { // "block_worker": "https://dev.0chain.net/dns", // "signature_scheme": "bls0chain", @@ -141,13 +142,13 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { return &StorageSDK{client: client.GetClient(), chainconfig: configObj}, nil } -// CreateAllocation - creating new allocation -// ## Inputs +// CreateAllocation creating new allocation // - datashards: number of data shards, effects upload and download speeds // - parityshards: number of parity shards, effects availability // - size: size of space reserved on blobbers // - 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) { readPrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} writePrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} @@ -181,16 +182,14 @@ func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expira } // CreateAllocationWithBlobbers - creating new allocation with list of blobbers -// -// ## Inputs -// - name: allocation name -// - datashards: number of data shards, effects upload and download speeds -// - parityshards: number of parity shards, effects availability -// - size: size of space reserved on blobbers -// - expiration: duration to allocation expiration -// - 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 +// - name: allocation name +// - datashards: number of data shards, effects upload and download speeds +// - parityshards: number of parity shards, effects availability +// - size: size of space reserved on blobbers +// - expiration: duration to allocation expiration +// - 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) { readPrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} writePrice := sdk.PriceRange{Min: 0, Max: math.MaxInt64} @@ -241,7 +240,8 @@ func (s *StorageSDK) CreateAllocationWithBlobbers(name string, datashards, parit return zbox.ToAllocation(sdkAllocation), nil } -// GetAllocation - get allocation from ID +// GetAllocation retrieve allocation from ID +// - allocationID: allocation ID func (s *StorageSDK) GetAllocation(allocationID string) (*zbox.Allocation, error) { sdkAllocation, err := sdk.GetAllocation(allocationID) if err != nil { @@ -260,7 +260,7 @@ func (s *StorageSDK) GetAllocation(allocationID string) (*zbox.Allocation, error return alloc, nil } -// GetAllocations - get list of allocations +// GetAllocations retrieve list of allocations owned by the wallet func (s *StorageSDK) GetAllocations() (string, error) { sdkAllocations, err := sdk.GetAllocations() if err != nil { @@ -278,7 +278,10 @@ func (s *StorageSDK) GetAllocations() (string, error) { return string(retBytes), nil } -// GetAllocationFromAuthTicket - get allocation from Auth ticket +// GetAllocationFromAuthTicket retrieve allocation from Auth ticket +// AuthTicket is a signed message from the blobber authorizing the client to access the allocation. +// It's issued by the allocation owner and can be used by a non-owner to access the allocation. +// - authTicket: auth ticket func (s *StorageSDK) GetAllocationFromAuthTicket(authTicket string) (*zbox.Allocation, error) { sdkAllocation, err := sdk.GetAllocationFromAuthTicket(authTicket) if err != nil { @@ -287,7 +290,8 @@ func (s *StorageSDK) GetAllocationFromAuthTicket(authTicket string) (*zbox.Alloc return zbox.ToAllocation(sdkAllocation), nil } -// GetAllocationStats - get allocation stats by allocation ID +// GetAllocationStats retrieve allocation stats by allocation ID +// - allocationID: allocation ID func (s *StorageSDK) GetAllocationStats(allocationID string) (string, error) { allocationObj, err := sdk.GetAllocation(allocationID) if err != nil { @@ -301,19 +305,22 @@ func (s *StorageSDK) GetAllocationStats(allocationID string) (string, error) { return string(retBytes), nil } -// FinalizeAllocation - finalize allocation +// FinalizeAllocation finalize allocation +// - allocationID: allocation ID func (s *StorageSDK) FinalizeAllocation(allocationID string) (string, error) { hash, _, err := sdk.FinalizeAllocation(allocationID) return hash, err } -// CancelAllocation - cancel allocation by ID +// CancelAllocation cancel allocation by ID +// - allocationID: allocation ID func (s *StorageSDK) CancelAllocation(allocationID string) (string, error) { hash, _, err := sdk.CancelAllocation(allocationID) return hash, err } // GetReadPoolInfo is to get information about the read pool for the allocation +// - clientID: client ID func (s *StorageSDK) GetReadPoolInfo(clientID string) (string, error) { readPool, err := sdk.GetReadPoolInfo(clientID) if err != nil { @@ -328,7 +335,11 @@ func (s *StorageSDK) GetReadPoolInfo(clientID string) (string, error) { } // WRITE POOL METHODS - +// WritePoolLock lock write pool with given number of tokens +// - durInSeconds: duration in seconds +// - tokens: number of tokens +// - fee: fee of the transaction +// - allocID: allocation ID func (s *StorageSDK) WritePoolLock(durInSeconds int64, tokens, fee float64, allocID string) error { _, _, err := sdk.WritePoolLock( allocID, @@ -342,7 +353,11 @@ func (s *StorageSDK) GetVersion() string { return version.VERSIONSTR } -// UpdateAllocation with new expiry and size +// UpdateAllocation update allocation settings with new expiry and size +// - size: size of space reserved on blobbers +// - 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) { if lock > math.MaxInt64 { return "", errors.Errorf("int64 overflow in lock") @@ -379,6 +394,8 @@ func GetAllocations() (string, error) { return string(retBytes), nil } +// RedeeemFreeStorage given a free storage ticket, create a new free allocation +// - ticket: free storage ticket func (s *StorageSDK) RedeemFreeStorage(ticket string) (string, error) { recipientPublicKey, marker, lock, err := decodeTicket(ticket) if err != nil { @@ -423,12 +440,13 @@ func decodeTicket(ticket string) (string, string, uint64, error) { return string(recipientPublicKey), string(markerStr), zcncore.ConvertTokenToSAS(s), nil } -// Client can extend interface and fass implementation to this register like this -// public class Autorizer extends Pkg.Autorizer { -// public void Auth() { -// // do something here -// } -// } +// RegisterAuthorizer Client can extend interface and FaSS implementation to this register like this: +// +// public class Autorizer extends Pkg.Autorizer { +// public void Auth() { +// // do something here +// } +// } func RegisterAuthorizer(auth Autorizer) { sys.Authorize = auth.Auth } diff --git a/mobilesdk/sdk/sign.go b/mobilesdk/sdk/sign.go index c9e705f99..0e0a7ef5f 100644 --- a/mobilesdk/sdk/sign.go +++ b/mobilesdk/sdk/sign.go @@ -12,6 +12,9 @@ import ( var ErrInvalidSignatureScheme = errors.New("invalid_signature_scheme") // SignRequest sign data with private key and scheme +// - privateKey: private key to use for signing +// - signatureScheme: signature scheme to use for signing +// - data: data to sign using the private key func SignRequest(privateKey, signatureScheme string, data string) (string, error) { hash := encryption.Hash(data) return sys.Sign(hash, signatureScheme, []sys.KeyPair{{ @@ -20,6 +23,10 @@ func SignRequest(privateKey, signatureScheme string, data string) (string, error } // VerifySignature verify signature with public key, schema and data +// - publicKey: public key to use for verifying signature +// - signatureScheme: signature scheme to use for verifying signature +// - data: data to verify using the public key +// - signature: signature to verify func VerifySignature(publicKey, signatureScheme string, data string, signature string) (bool, error) { hash := encryption.Hash(data) diff --git a/mobilesdk/zboxapi/client.go b/mobilesdk/zboxapi/client.go index 2e21f4fde..393013c96 100644 --- a/mobilesdk/zboxapi/client.go +++ b/mobilesdk/zboxapi/client.go @@ -1,3 +1,4 @@ +// Subpackage to provide interface for zboxapi SDK (dealing with apps backend) to be used to build the mobile SDK. package zboxapi /* @@ -25,6 +26,9 @@ var ( logging logger.Logger ) +// Init initialize the zbox api client for the mobile sdk +// - baseUrl is the base url of the server +// - appType is the type of the application func Init(baseUrl, appType string) { zboxApiClient = zboxapi.NewClient() zboxApiClient.SetRequest(baseUrl, appType) @@ -40,6 +44,10 @@ func Init(baseUrl, appType string) { } } +// SetWallet set the client's wallet information for the zbox api client +// - clientID is the client id +// - clientPrivateKey is the client private key +// - clientPublicKey is the client public key func SetWallet(clientID, clientPrivateKey, clientPublicKey string) error { if zboxApiClient == nil { return ErrZboxApiNotInitialized @@ -60,7 +68,8 @@ func GetCsrfToken() (string, error) { return zboxApiClient.GetCsrfToken(context.TODO()) } -// CreateJwtSession create a jwt session +// CreateJwtSession create a jwt session for the given phone number +// - phoneNumber is the phone number func CreateJwtSession(phoneNumber string) (int64, error) { if zboxApiClient == nil { return 0, ErrZboxApiNotInitialized @@ -68,7 +77,10 @@ func CreateJwtSession(phoneNumber string) (int64, error) { return zboxApiClient.CreateJwtSession(context.TODO(), phoneNumber) } -// CreateJwtToken create a fresh jwt token +// CreateJwtToken create a fresh jwt token for the given phone number +// - phoneNumber is the phone number +// - jwtSessionID is the jwt session id +// - otp is the one time password func CreateJwtToken(phoneNumber string, jwtSessionID int64, otp string) (string, error) { if zboxApiClient == nil { return "", ErrZboxApiNotInitialized @@ -77,6 +89,8 @@ func CreateJwtToken(phoneNumber string, jwtSessionID int64, otp string) (string, } // RefreshJwtToken refresh jwt token +// - phoneNumber is the phone number for which the token is to be refreshed +// - token is the token to be refreshed func RefreshJwtToken(phoneNumber string, token string) (string, error) { if zboxApiClient == nil { return "", ErrZboxApiNotInitialized diff --git a/mobilesdk/zcn/doc.go b/mobilesdk/zcn/doc.go new file mode 100644 index 000000000..7dc3dc5ca --- /dev/null +++ b/mobilesdk/zcn/doc.go @@ -0,0 +1,2 @@ +// Subpackage to provide interface for zcncore SDK functions to be used to build the mobile SDK. +package zcn \ No newline at end of file diff --git a/play.go b/play.go new file mode 100644 index 000000000..c88634db9 --- /dev/null +++ b/play.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + fmt.Printf("Now = %v\n", Now()) +} + +// Timestamp represents Unix time (e.g. in seconds) +type Timestamp int64 + +// Now - current datetime +func Now() Timestamp { + return Timestamp(time.Now().Unix()) +} diff --git a/sdks/blobber/blobber.go b/sdks/blobber/blobber.go index 03ffa762b..e13d9016b 100644 --- a/sdks/blobber/blobber.go +++ b/sdks/blobber/blobber.go @@ -1,4 +1,3 @@ -// package blobber wrap blobber's apis as sdk client package blobber import ( @@ -11,6 +10,9 @@ type Blobber struct { *sdks.ZBox } +// New create an sdk client instance given its configuration +// - zbox zbox sdk client instance +// - baseURLs base urls of the blobber func New(zbox *sdks.ZBox, baseURLs ...string) *Blobber { b := &Blobber{ BaseURLs: baseURLs, diff --git a/sdks/blobber/doc.go b/sdks/blobber/doc.go new file mode 100644 index 000000000..58580152e --- /dev/null +++ b/sdks/blobber/doc.go @@ -0,0 +1,2 @@ +// Provides sdk functions to be used by the blobber. +package blobber \ No newline at end of file diff --git a/sdks/doc.go b/sdks/doc.go new file mode 100644 index 000000000..1cb024dab --- /dev/null +++ b/sdks/doc.go @@ -0,0 +1,2 @@ +// Miscellaneous provider-related SDKs. +package sdks \ No newline at end of file diff --git a/sdks/zbox.go b/sdks/zbox.go index 85b4e9682..9e92f0c33 100644 --- a/sdks/zbox.go +++ b/sdks/zbox.go @@ -33,7 +33,11 @@ type ZBox struct { NewRequest func(method, url string, body io.Reader) (*http.Request, error) } -// New create a sdk client instance +// New create an sdk client instance given its configuration +// - clientID client id of the using client +// - clientKey client key of the using client +// - signatureScheme signature scheme for transaction encryption +// - wallet wallet of the using client func New(clientID, clientKey, signatureScheme string, wallet *zcncrypto.Wallet) *ZBox { s := &ZBox{ ClientID: clientID, @@ -47,11 +51,14 @@ func New(clientID, clientKey, signatureScheme string, wallet *zcncrypto.Wallet) } // InitWallet init wallet from json +// - js json string of wallet func (z *ZBox) InitWallet(js string) error { return json.Unmarshal([]byte(js), &z.Wallet) } -// SignRequest sign request with client_id, client_key and sign +// SignRequest sign request with client_id, client_key and sign by adding headers to the request +// - req http request +// - allocationID allocation id func (z *ZBox) SignRequest(req *http.Request, allocationID string) error { if req == nil { @@ -84,7 +91,11 @@ func (z *ZBox) CreateTransport() *http.Transport { } } -// BuildUrls build full request url +// BuildUrls build full request url given base urls, query string, path format and path args +// - baseURLs base urls +// - queryString query string +// - pathFormat path format +// - pathArgs path args func (z *ZBox) BuildUrls(baseURLs []string, queryString map[string]string, pathFormat string, pathArgs ...interface{}) []string { requestURL := pathFormat @@ -109,6 +120,9 @@ func (z *ZBox) BuildUrls(baseURLs []string, queryString map[string]string, pathF return list } +// DoPost do post request with request and handle +// - req request instance +// - handle handle function for the response func (z *ZBox) DoPost(req *Request, handle resty.Handle) *resty.Resty { opts := make([]resty.Option, 0, 5) diff --git a/wasmsdk/README.md b/wasmsdk/README.md index 7f7adbaec..c4b52b221 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -1,682 +1,76 @@ -# 0chain/wasmsdk + -The 0chain wasm SDK is written in Go programming language, and released with WebAssembly binary format +# wasmsdk -_NOTE_ please use `try{await zcn.sdk.[method];}catch(err){...}` to handle any error from wasm sdk in js - -## ZCN global js methods - -### zcn.setWallet - -set bls.SecretKey on runtime env(browser,nodejs...etc), and call `zcn.sdk.setWallet` to set wallet on go. - -**Input**: - -> bls, clientID, sk, pk, mnemonic string - -**Output**: - -> N/A - -## ZCN methods - -### zcn.sdk.init - -init wasm sdk - -**Input**: - -> chainID, blockWorker, signatureScheme string, minConfirmation, minSubmit, confirmationChainLength int,zboxHost, zboxAppType string - -**Output**: - -> N/A - -### zcn.sdk.hideLogs - -hide interactive sdk logs. default is hidden. - -**Input**: - -> N/A - -**Output**: - -> N/A - -### zcn.sdk.showLogs - -show interactive sdk logs. default is hidden. - -**Input**: - -> N/A - -**Output**: - -> N/A - -### zcn.sdk.getUSDRate - -get USD rate by token symbol(eg zcn, eth) - -**Input**: - -> symbol string - -**Output**: - -> float64 - -### zcn.sdk.createThumbnail - -create thumbnail of an image buffer - -**Input**: - -> buf []byte, width,height int - -**Output**: - -> []byte - -### zcn.sdk.isWalletID - -valid wallet id - -**Input**: - -> clientID string - -**Output**: - -> bool - -### zcn.sdk.setWallet - -set wallet on go - -**Input**: - -> clientID, publicKey, privateKey string - -**Output**: - -> N/A - -### zcn.sdk.getPublicEncryptionKey - -get public encryption key by mnemonic - -**Input**: - -> mnemonic string - -**Output**: - -> string - -### zcn.sdk.getAllocationBlobbers - -get blobbers with filters for creating allocation - -**Input**: - -> referredBlobberURLs []string, - - dataShards, parityShards int, size, expiry int64, - minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64 - -**Output**: - -> string array - -### zcn.sdk.createAllocation - -create an allocation - -**Input**: - -> datashards, parityshards int, size, - - minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, lock int64,preferredBlobberIds []string, setThirdPartyExtendable bool - -**Output**: - -> [transaction.Transaction](https://github.com/0chain/gosdk/blob/e1e35e084d5c17d6bf233bbe8ac9c91701bdd8fd/core/transaction/entity.go#L32) - -### zcn.sdk.listAllocations - -list all allocations - -**Input**: - -> N/A - -**Output**: - -> [sdk.Allocation](https://github.com/0chain/gosdk/blob/a9e504e4a0e8fc76a05679e4ef183bb03b8db8e5/zboxcore/sdk/allocation.go#L140) array - -### zcn.sdk.getAllocation - -get allocation detail - -**Input**: - -> allocationID string - -**Output**: - -> [sdk.Allocation](https://github.com/0chain/gosdk/blob/a9e504e4a0e8fc76a05679e4ef183bb03b8db8e5/zboxcore/sdk/allocation.go#L140) - -### zcn.sdk.reloadAllocation - -clean cache, and get allocation detail from blockchain - -**Input**: - -> allocationID string - -**Output**: - -> [sdk.Allocation](https://github.com/0chain/gosdk/blob/a9e504e4a0e8fc76a05679e4ef183bb03b8db8e5/zboxcore/sdk/allocation.go#L140) - -### zcn.sdk.transferAllocation - -changes the owner of an allocation. Only the current owner of the allocation, can change an allocation's ownership. - -**Input**: - -> allocationId, newOwnerId, newOwnerPublicKey string - -**Output**: - -> N/A - -### zcn.sdk.freezeAllocation - -freeze allocation so that data can no longer be modified - -**Input**: - -> allocationId string - -**Output**: - -> hash: string - -### zcn.sdk.cancelAllocation - -immediately return all remaining tokens from challenge pool back to the allocation's owner and cancels the allocation. If blobbers already got some tokens, the tokens will not be returned. Remaining min lock payment to the blobber will be funded from the allocation's write pools. - -**Input**: - -> allocationId string - -**Output**: - -> hash: string - -### zcn.sdk.updateAllocation - -updates allocation settings - -**Input**: - -> allocationId string, name string,size int64, extend bool,lock int64,setImmutable,addBlobberId, removeBlobberId string, setThirdPartyExtendable bool - -**Output**: - -> hash: string - -### zcn.sdk.getAllocationWith - -returns allocation from authToken - -**Input**: - -> authTicket string - -**Output**: - -> [sdk.Allocation](https://github.com/0chain/gosdk/blob/a9e504e4a0e8fc76a05679e4ef183bb03b8db8e5/zboxcore/sdk/allocation.go#L140) - -### zcn.sdk.getReadPoolInfo - -gets information about the read pool for the allocation - -**Input**: - -> clientID string - -**Output**: - -> [sdk.ReadPool](https://github.com/0chain/gosdk/blob/6878504e4e4d7cb25b2ac819c3c578228b3d3e30/zboxcore/sdk/sdk.go#L167-L169) - -### zcn.sdk.decodeAuthTicket - -**Input**: - -> ticket string - -**Output**: - -> recipientPublicKey string, markerStr string, tokensInSAS uint64 - -### zcn.sdk.lockWritePool - -locks given number of tokes for given duration in write pool - -**Input**: - -> allocationId string, tokens uint64, fee uint64 - -**Output**: - -> hash: string - -### zcn.sdk.lockStakePool - -locks given number of tokens on a provider - -**Input**: - -> [providerType](https://github.com/0chain/gosdk/blob/bc96f54e68a68ef5d757428b9c4153405ebe4163/zboxcore/sdk/sdk.go#L1186-L1194) uint64, tokens uint64, fee uint64, providerID string, - -**Output**: - -> hash: string - -### zcn.sdk.unlockStakePool - -unlocks tokens on a provider - -**Input**: - -> [providerType](https://github.com/0chain/gosdk/blob/bc96f54e68a68ef5d757428b9c4153405ebe4163/zboxcore/sdk/sdk.go#L1186-L1194) uint64, fee uint64, providerID string, - -**Output**: - -> returns time where the tokens can be unlocked - -### zcn.sdk.getSkatePoolInfo - -get the details of the stakepool associated with provider -**Input**: - -> [providerType](https://github.com/0chain/gosdk/blob/bc96f54e68a68ef5d757428b9c4153405ebe4163/zboxcore/sdk/sdk.go#L1186-L1194) int, providerID string - -**Output**: - -> [sdk.StakePoolInfo](https://github.com/0chain/gosdk/blob/2ec97a9bb116db166e31c0207971282e7008d22c/zboxcore/sdk/sdk.go#L263-L275), err - -### zcn.sdk.getWalletBalance - -get wallet balance - -**Input**: - -> clientId string - -**Output**: - -> {zcn:float64, usd: float64} - -### zcn.sdk.getBlobberIds - -convert blobber urls to blobber ids - -**Input**: - -> blobberUrls []string - -**Output**: - -> []string - -### zcn.sdk.getBlobbers - -get blobbers from the network - -**Input**: - -**Output**: - -> array of [sdk.Blobber](https://github.com/0chain/gosdk/blob/6878504e4e4d7cb25b2ac819c3c578228b3d3e30/zboxcore/sdk/sdk.go#L558-L572) - -### zcn.sdk.createReadPool - -create readpool in storage SC if the pool is missing. - -**Input**: - -> N/A - -**Output**: - -> string - -### zcn.sdk.executeSmartContract - -send raw SmartContract transaction, and verify result - -**Input**: - -> address, methodName, input string, value uint64 - -**Output**: - -> > [transaction.Transaction](https://github.com/0chain/gosdk/blob/e1e35e084d5c17d6bf233bbe8ac9c91701bdd8fd/core/transaction/entity.go#L32) - -### zcn.sdk.faucet - -faucet SmartContract - -**Input**: - -> methodName, input string, token float64 - -**Output**: - -> > [transaction.Transaction](https://github.com/0chain/gosdk/blob/e1e35e084d5c17d6bf233bbe8ac9c91701bdd8fd/core/transaction/entity.go#L32) - -## Blobber methods - -### zcn.sdk.getLookupHash - -get lookup hash by allocation id and path - -**Input**: - -> allocationID string, path string - -**Output**: - -> string - -### zcn.sdk.delete - -delete remote file from blobbers - -**Input**: - -> allocationID, remotePath string - -**Output**: - -> {commandSuccess:bool,error:string} - -### zcn.sdk.rename - -rename a file existing already on dStorage. Only the allocation's owner can rename a file. - -**Input**: - -> allocationID, remotePath, destName string - -**Output**: - -> {commandSuccess:bool, error:string} - -### zcn.sdk.copy - -copy file to another folder path on blobbers -**Input**: - -> allocationID, remotePath, destPath string - -**Output**: - -> {commandSuccess:bool, error:string} - -### zcn.sdk.move - -move file to another remote folder path on dStorage. Only the owner of the allocation can copy an object. - -**Input**: - -> allocationID, remotePath, destPath string - -**Output**: +```go +import "github.com/0chain/gosdk/wasmsdk" +``` -> {commandSuccess:bool, error:string} +## Index -### zcn.sdk.share +- [func InvalidArg\(argName string\) error](<#InvalidArg>) +- [func RequiredArg\(argName string\) error](<#RequiredArg>) +- [type CheckStatusResult](<#CheckStatusResult>) +- [type DownloadCommandResponse](<#DownloadCommandResponse>) +- [type FileCommandResponse](<#FileCommandResponse>) -generate an authtoken that provides authorization to the holder to the specified file on the remotepath. -**Input**: + +## func [InvalidArg]() -> allocationID, remotePath, clientID, encryptionPublicKey string, expiration int, revoke bool,availableAfter int +```go +func InvalidArg(argName string) error +``` -**Output**: -> string -### zcn.sdk.download + +## func [RequiredArg]() -download your own or a shared file. +```go +func RequiredArg(argName string) error +``` -**Input**: -> allocationID, remotePath, authTicket, lookupHash string, downloadThumbnailOnly bool, numBlocks int,callbackFuncName string -**Output**: + +## type [CheckStatusResult]() -> {commandSuccess:bool, fileName:string,url:string, error:string} -**Example** -```json -{ - "commandSuccess": true, - "fileName": "scan3.png", - "url": "blob:http://localhost:3000/42157751-1d33-4448-88c8-7d7e2ad887a5" +```go +type CheckStatusResult struct { + Status string `json:"status"` + Err error `json:"error"` + BlobberStatus []sdk.BlobberStatus `json:"blobberStatus"` } ``` -### zcn.sdk.downloadBlocks - -download blocks of a file + +## type [DownloadCommandResponse]() -**Input**: -> allocationID, remotePath, authTicket, lookupHash string, numBlocks int, startBlockNumber, endBlockNumber int64, callbackFuncName string -**Output**: +```go +type DownloadCommandResponse struct { + CommandSuccess bool `json:"commandSuccess,omitempty"` + Error string `json:"error,omitempty"` -> {[]byte, error:string} + FileName string `json:"fileName,omitempty"` + Url string `json:"url,omitempty"` +} ``` -### zcn.sdk.upload - -upload file - -**Input**: - -> allocationID, remotePath string, fileBytes, thumbnailBytes []byte, encrypt bool, isUpdate, isRepair bool, numBlocks int - -**Output**: - -> {commandSuccess:bool, error:string} - -### zcn.sdk.multiUpload - -bulk upload files with json options - -**Input**: - -> jsonBulkUploadOptions string: -> BulkOption: { allocationId,remotePath,readChunkFuncName, fileSize, thumbnailBytes, encrypt,isUpdate,isRepair,numBlocks,callbackFuncName:callbackFuncName } - -**Output**: - -> [ {remotePath:"/d.png", success:true,error:""} ] - -### zcn.sdk.play - -play stream video files + +## type [FileCommandResponse]() -**Input**: -> allocationID, remotePath, authTicket, lookupHash string, isLive bool -**Output**: - -> N/A - -### zcn.sdk.stop - -stop current play - -**Input**: - -> N/A - -**Output**: - -> N/A - -### zcn.sdk.listObjects - -list files with allocationID and remotePath - -**Input**: - -> allocationId string, remotePath string - -**Output**: - -> sdk.ListResult - -### zcn.sdk.createDir - -create folder from blobbers - -**Input**: - -> allocationID, remotePath string - -**Output**: - -> N/A - -### zcn.sdk.getFileStats - -**Input**: - -> allocationID string, remotePath string - -**Output**: - -> string: []sdk.FileStats - -### zcn.sdk.updateBlobberSettings - -**Input**: - -> blobberSettingsJson string -> blobberSettings: fetch blobber settings by calling /getBlobber on sharder and modify them (see demo for usage) -> **Output**: -> string: resp - -### zcn.sdk.getAllocationMinLock - -**Input**: - -> datashards int, parityshards int, size int, maxreadPrice int, maxwritePrice int - -**Output**: - -> int: min_lock_demand - - -### zcn.sdk.getUpdateAllocationMinLock - -**Input**: - -> allocationID string, size int, extend bool, addBlobberId string, removeBlobberId string - -**Output**: - -> int: min_lock_demand - -### zcn.sdk.getRemoteFileMap - -takes allocation ID and returns all the files/directories in allocation as JSON -**Input**: - -> allocationID string - -**Output**: - -> []\*fileResp - -## Swap methods - -### zcn.sdk.setSwapWallets - -**Input**: - -> usdcTokenAddress, bancorAddress, zcnTokenAddress, ethWalletMnemonic string - -**Output**: - -> N/A - -### zcn.sdk.swapToken - -**Input**: - -> swapAmount int64, tokenSource string - -**Output**: - -> string: txnHash - -## 0Box API methods - -### zcn.sdk.getCsrfToken - -get a fresh CSRF token - -**Input**: - -> N/A - -**Output**: - -> string - -### zcn.sdk.createJwtSession - -create a jwt session with phone number -**Input**: - -> phoneNumber string - -**Output**: - -> sessionID int64 - -### zcn.sdk.createJwtToken - -create a jwt token with jwt session id and otp -**Input**: - -> phoneNumber string, jwtSessionID int64, otp string - -**Output**: - -> token string - -### zcn.sdk.refreshJwtToken - -refresh jwt token -**Input**: - -> phoneNumber string, token string - -**Output**: +```go +type FileCommandResponse struct { + CommandSuccess bool `json:"commandSuccess,omitempty"` + Error string `json:"error,omitempty"` +} +``` -> token string +Generated by [gomarkdoc]() diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 3cf765e8c..af03ac4eb 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -31,10 +31,14 @@ type decodeAuthTokenResp struct { Tokens uint64 `json:"tokens"` } +// getBlobberIds retrieves blobber ids from the given blobber urls +// - blobberUrls is the list of blobber urls func getBlobberIds(blobberUrls []string) ([]string, error) { return sdk.GetBlobberIds(blobberUrls) } +// createfreeallocation creates a free allocation +// - freeStorageMarker is the free storage marker func createfreeallocation(freeStorageMarker string) (string, error) { allocationID, _, err := sdk.CreateFreeAllocation(freeStorageMarker, 0) if err != nil { @@ -44,6 +48,17 @@ func createfreeallocation(freeStorageMarker string) (string, error) { return allocationID, err } +// getAllocationBlobbers retrieves allocation blobbers +// - preferredBlobberURLs is the list of preferred blobber urls +// - dataShards is the number of data shards +// - parityShards is the number of parity shards +// - size is the size of the allocation +// - minReadPrice is the minimum read price +// - maxReadPrice is the maximum read price +// - minWritePrice is the minimum write price +// - maxWritePrice is the maximum write price +// - isRestricted is the restricted flag +// - force is the force flag func getAllocationBlobbers(preferredBlobberURLs []string, dataShards, parityShards int, size int64, minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, isRestricted int, force bool) ([]string, error) { @@ -61,8 +76,19 @@ func getAllocationBlobbers(preferredBlobberURLs []string, }, force) } +// createAllocation creates an allocation given allocation creation parameters +// - datashards is the number of data shards. Data uploaded to the allocation will be split and distributed across these shards. +// - parityshards is the number of parity shards. Parity shards are used to replicate datashards for redundancy. +// - size is the size of the allocation in bytes. +// - minReadPrice is the minimum read price set by the client. +// - maxReadPrice is the maximum read price set by the client. +// - minWritePrice is the minimum write price set by the client. +// - maxWritePrice is the maximum write price set by the client. +// - 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, - minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, lock int64, blobberIds, blobberAuthTickets []string, setThirdPartyExtendable, force bool) ( + minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, lock int64, blobberIds, blobberAuthTickets []string, setThirdPartyExtendable, IsEnterprise, force bool) ( *transaction.Transaction, error) { options := sdk.CreateAllocationOptions{ @@ -80,6 +106,7 @@ func createAllocation(datashards, parityshards int, size int64, Lock: uint64(lock), BlobberIds: blobberIds, ThirdPartyExtendable: setThirdPartyExtendable, + IsEnterprise: IsEnterprise, BlobberAuthTickets: blobberAuthTickets, Force: force, } @@ -90,10 +117,15 @@ func createAllocation(datashards, parityshards int, size int64, return txn, err } +// listAllocations retrieves the list of allocations owned by the client func listAllocations() ([]*sdk.Allocation, error) { return sdk.GetAllocations() } +// transferAllocation transfers the ownership of an allocation to a new owner +// - allocationID is the allocation id +// - newOwnerId is the new owner id +// - newOwnerPublicKey is the new owner public key func transferAllocation(allocationID, newOwnerId, newOwnerPublicKey string) error { if allocationID == "" { return RequiredArg("allocationID") @@ -116,7 +148,14 @@ func transferAllocation(allocationID, newOwnerId, newOwnerPublicKey string) erro return err } -// updateForbidAllocation updates the settings for forbid alocation +// UpdateForbidAllocation updates the permissions of an allocation, given the permission parameters in a forbid-first manner. +// - allocationID: allocation ID +// - forbidupload: forbid upload flag, if true, uploading files to the allocation is forbidden +// - forbiddelete: forbid delete flag, if true, deleting files from the allocation is forbidden +// - forbidupdate: forbid update flag, if true, updating files in the allocation is forbidden +// - forbidmove: forbid move flag, if true, moving files in the allocation is forbidden +// - forbidcopy: forbid copy flag, if true, copying files in the allocation is forbidden +// - forbidrename: forbid rename flag, if true, renaming files in the allocation is forbidden func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, forbidupdate, forbidmove, forbidcopy, forbidrename bool) (string, error) { hash, _, err := sdk.UpdateAllocation( @@ -142,6 +181,9 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for } +// freezeAllocation freezes one of the client's allocations, given its ID +// Freezing the allocation means to forbid all the operations on the files in the allocation. +// - allocationID: allocation ID func freezeAllocation(allocationID string) (string, error) { hash, _, err := sdk.UpdateAllocation( @@ -171,6 +213,8 @@ func freezeAllocation(allocationID string) (string, error) { } +// cancelAllocation cancels one of the client's allocations, given its ID +// - allocationID: allocation ID func cancelAllocation(allocationID string) (string, error) { hash, _, err := sdk.CancelAllocation(allocationID) @@ -181,6 +225,17 @@ func cancelAllocation(allocationID string) (string, error) { return hash, err } +// updateAllocationWithRepair updates the allocation settings and repairs it if necessary. +// Repair means to sync the user's data under the allocation on all the blobbers +// and fill the missing data on the blobbers that have missing data. +// Check the system documentation for more information about the repoair process. +// - allocationID: allocation ID +// - size: size of the allocation +// - extend: extend flag +// - lock: lock value to add to the allocation +// - addBlobberId: blobber ID to add to the allocation +// - 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, extend bool, @@ -220,6 +275,15 @@ func updateAllocationWithRepair(allocationID string, return hash, err } +// updateAllocation updates the allocation settings +// - allocationID: allocation ID +// - size: new size of the allocation +// - extend: extend flag, whether to extend the allocation's expiration date +// - lock: lock value to add to the allocation +// - addBlobberId: blobber ID to add to the allocation +// - addBlobberAuthTicket: blobber auth ticket to add to the allocation, in case of restricted blobbers +// - 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, lock int64, @@ -233,6 +297,13 @@ func updateAllocation(allocationID string, return hash, 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. +// - datashards: number of data shards +// - parityshards: number of parity shards. +// - size: size of the allocation. +// - maxwritePrice: maximum write price set by the client. func getAllocationMinLock(datashards, parityshards int, size int64, maxwritePrice uint64, @@ -248,6 +319,14 @@ func getAllocationMinLock(datashards, parityshards int, return value, nil } +// getUpdateAllocationMinLock retrieves the minimum lock value for the allocation after update, as calculated by the network based on the update parameters. +// 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. +// - allocationID: allocation ID +// - size: new size of the allocation +// - extend: extend flag, whether to extend the allocation's expiration date +// - addBlobberId: blobber ID to add to the allocation +// - removeBlobberId: blobber ID to remove from the allocation func getUpdateAllocationMinLock( allocationID string, size int64, @@ -256,6 +335,8 @@ func getUpdateAllocationMinLock( return sdk.GetUpdateAllocationMinLock(allocationID, size, extend, addBlobberId, removeBlobberId) } +// getRemoteFileMap list all files in an allocation from the blobbers. +// - allocationID: allocation ID func getRemoteFileMap(allocationID string) ([]*fileResp, error) { if len(allocationID) == 0 { return nil, RequiredArg("allocationID") @@ -286,7 +367,6 @@ func getRemoteFileMap(allocationID string) ([]*fileResp, error) { } // lockWritePool locks given number of tokes for given duration in write pool. -// ## Inputs // - allocID: allocation id // - tokens: sas tokens // - fee: sas tokens @@ -295,6 +375,11 @@ func lockWritePool(allocID string, tokens, fee uint64) (string, error) { return hash, err } +// lockStakePool stake number of tokens for a given provider given its type and id +// - providerType: provider type (1: miner, 2:sharder, 3:blobber, 4:validator, 5:authorizer) +// - tokens: amount of tokens to lock (in SAS) +// - fee: transaction fees (in SAS) +// - providerID: provider id func lockStakePool(providerType, tokens, fee uint64, providerID string) (string, error) { hash, _, err := sdk.StakePoolLock(sdk.ProviderType(providerType), providerID, @@ -302,21 +387,33 @@ func lockStakePool(providerType, tokens, fee uint64, providerID string) (string, return hash, err } +// unlockWritePool unlocks the read pool +// - tokens: amount of tokens to lock (in SAS) +// - fee: transaction fees (in SAS) func lockReadPool(tokens, fee uint64) (string, error) { hash, _, err := sdk.ReadPoolLock(tokens, fee) return hash, err } +// unLockWritePool unlocks the write pool +// - fee: transaction fees (in SAS) func unLockReadPool(fee uint64) (string, error) { hash, _, err := sdk.ReadPoolUnlock(fee) return hash, err } +// unlockWritePool unlocks the write pool +// - 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) return unstake, err } +// getSkatePoolInfo is to get information about the stake pool for the allocation +// - providerType: provider type (1: miner, 2:sharder, 3:blobber, 4:validator, 5:authorizer) +// - providerID: provider id func getSkatePoolInfo(providerType int, providerID string) (*sdk.StakePoolInfo, error) { info, err := sdk.GetStakePoolInfo(sdk.ProviderType(providerType), providerID) @@ -327,7 +424,8 @@ func getSkatePoolInfo(providerType int, providerID string) (*sdk.StakePoolInfo, return info, err } -// GetReadPoolInfo is to get information about the read pool for the allocation +// getReadPoolInfo is to get information about the read pool for the allocation +// - clientID: client id func getReadPoolInfo(clientID string) (*sdk.ReadPool, error) { readPool, err := sdk.GetReadPoolInfo(clientID) if err != nil { @@ -337,7 +435,11 @@ func getReadPoolInfo(clientID string) (*sdk.ReadPool, error) { return readPool, nil } -// GetAllocationFromAuthTicket - get allocation from Auth ticket +// getAllocationWith retrieves the information of a free or a shared allocation object given the auth ticket. +// A free allocation is an allocation that is created to the user using Vult app for the first time with no fees. +// A shared allocation is an allocation that has some shared files. The user who needs +// to access those files needs first to read the information of this allocation. +// - authTicket: auth ticket usually used by a non-owner to access a shared allocation func getAllocationWith(authTicket string) (*sdk.Allocation, error) { sdk.SetWasm() sdkAllocation, err := sdk.GetAllocationFromAuthTicket(authTicket) @@ -347,6 +449,8 @@ func getAllocationWith(authTicket string) (*sdk.Allocation, error) { return sdkAllocation, err } +// decodeAuthTicket decodes the auth ticket and returns the recipient public key and the tokens +// - ticket: auth ticket func decodeAuthTicket(ticket string) (*decodeAuthTokenResp, error) { resp := &decodeAuthTokenResp{} @@ -388,10 +492,19 @@ func decodeAuthTicket(ticket string) (*decodeAuthTokenResp, error) { return resp, nil } +// convertTokenToSAS converts tokens in ZCN to SAS. +// 1 ZCN = 1e10 SAS +// - token: token value in ZCN func convertTokenToSAS(token float64) uint64 { return uint64(token * float64(TOKEN_UNIT)) } +// allocationRepair issue repair process for an allocation, starting from a specific path. +// Repair means to sync the user's data under the allocation on all the blobbers +// and fill the missing data on the blobbers that have missing data. +// Check the system documentation for more information about the repoair process. +// - allocationID: allocation ID +// - remotePath: remote path func allocationRepair(allocationID, remotePath string) error { if len(allocationID) == 0 { return RequiredArg("allocationID") @@ -417,6 +530,10 @@ func allocationRepair(allocationID, remotePath string) error { return nil } +// repairSize retrieves the repair size for a specific path in an allocation. +// Repair size is the size of the data that needs to be repaired in the allocation. +// - allocationID: allocation ID +// - remotePath: remote path func repairSize(allocationID, remotePath string) (sdk.RepairSize, error) { alloc, err := sdk.GetAllocation(allocationID) if err != nil { diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 3ac7d325c..641b58b1f 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -15,7 +15,9 @@ type AuthCallbackFunc func(msg string) string var authCallback AuthCallbackFunc var authResponseC chan string -// Register the callback function +// registerAuthorizer Register the callback function to authorize the transaction. +// This function is called from JavaScript. +// It stores the callback function in the global variable authCallback. func registerAuthorizer(this js.Value, args []js.Value) interface{} { // Store the callback function authCallback = parseAuthorizerCallback(args[0]) @@ -28,11 +30,14 @@ func registerAuthorizer(this js.Value, args []js.Value) interface{} { return nil } +// authResponse Publishes the response to the authorization request. +// `response` is the response to the authorization request. func authResponse(response string) { authResponseC <- response } -// Use the stored callback function +// callAuth Call the authorization callback function and provide the message to pass to it. +// The message is passed as the first argument to the js calling. func callAuth(this js.Value, args []js.Value) interface{} { fmt.Println("callAuth is called") if len(args) == 0 { diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index ce2aafc9b..cf7a6b097 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -30,6 +30,11 @@ import ( const FileOperationInsert = "insert" +// listObjects list allocation objects from its blobbers +// - allocationID is the allocation id +// - remotePath is the remote path of the file +// - offset is the offset of the list +// - pageLimit is the limit of the page func listObjects(allocationID string, remotePath string, offset, pageLimit int) (*sdk.ListResult, error) { defer func() { if r := recover(); r != nil { @@ -44,6 +49,12 @@ func listObjects(allocationID string, remotePath string, offset, pageLimit int) return alloc.ListDir(remotePath, sdk.WithListRequestOffset(offset), sdk.WithListRequestPageLimit(pageLimit)) } +// listObjectsFromAuthTicket list allocation objects from its blobbers using auth ticket +// - allocationID is the allocation id +// - authTicket is the auth ticket, provided usually by a non-owner to be able to access a shared source +// - lookupHash is the lookup hash +// - offset is the offset of the list +// - pageLimit is the limit of the page func listObjectsFromAuthTicket(allocationID, authTicket, lookupHash string, offset, pageLimit int) (*sdk.ListResult, error) { alloc, err := getAllocation(allocationID) if err != nil { @@ -52,6 +63,9 @@ func listObjectsFromAuthTicket(allocationID, authTicket, lookupHash string, offs return alloc.ListDirFromAuthTicket(authTicket, lookupHash, sdk.WithListRequestOffset(offset), sdk.WithListRequestPageLimit(pageLimit)) } +// cancelUpload cancel the upload operation of the file +// - allocationID is the allocation id +// - remotePath is the remote path of the file func cancelUpload(allocationID, remotePath string) error { allocationObj, err := getAllocation(allocationID) if err != nil { @@ -61,6 +75,9 @@ func cancelUpload(allocationID, remotePath string) error { return allocationObj.CancelUpload(remotePath) } +// pauseUpload pause the upload operation of the file +// - allocationID is the allocation id +// - remotePath is the remote path of the file func pauseUpload(allocationID, remotePath string) error { allocationObj, err := getAllocation(allocationID) if err != nil { @@ -70,6 +87,9 @@ func pauseUpload(allocationID, remotePath string) error { return allocationObj.PauseUpload(remotePath) } +// createDir create a directory on blobbers +// - allocationID is the allocation id +// - remotePath is the remote path of the file func createDir(allocationID, remotePath string) error { if len(allocationID) == 0 { return RequiredArg("allocationID") @@ -93,6 +113,8 @@ func createDir(allocationID, remotePath string) error { } // getFileStats get file stats from blobbers +// - allocationID is the allocation id +// - remotePath is the remote path of the file func getFileStats(allocationID, remotePath string) ([]*sdk.FileStats, error) { if len(allocationID) == 0 { return nil, RequiredArg("allocationID") @@ -122,6 +144,8 @@ func getFileStats(allocationID, remotePath string) ([]*sdk.FileStats, error) { } // updateBlobberSettings expects settings JSON of type sdk.Blobber +// and updates the blobber settings. Can only be called by the owner of the blobber. +// - blobberSettingsJson is the blobber settings in JSON format func updateBlobberSettings(blobberSettingsJson string) (*transaction.Transaction, error) { var blobberSettings sdk.Blobber err := json.Unmarshal([]byte(blobberSettingsJson), &blobberSettings) @@ -139,7 +163,9 @@ func updateBlobberSettings(blobberSettingsJson string) (*transaction.Transaction return txn, err } -// Delete delete file from blobbers +// Delete delete file from an allocation, only the owner of the allocation can delete a file. +// - allocationID is the allocation id +// - remotePath is the remote path of the file func Delete(allocationID, remotePath string) (*FileCommandResponse, error) { if len(allocationID) == 0 { @@ -170,7 +196,10 @@ func Delete(allocationID, remotePath string) (*FileCommandResponse, error) { return resp, nil } -// Rename rename a file existing already on dStorage. Only the allocation's owner can rename a file. +// Rename rename file on an allocation, only the owner of the allocation can rename a file. +// - allocationID is the allocation id +// - remotePath is the remote path of the file +// - destName is the new name of the file func Rename(allocationID, remotePath, destName string) (*FileCommandResponse, error) { if len(allocationID) == 0 { return nil, RequiredArg("allocationID") @@ -211,7 +240,10 @@ func Rename(allocationID, remotePath, destName string) (*FileCommandResponse, er return resp, nil } -// Copy copy file to another folder path on blobbers +// Copy copy file to another folder path on an allocation, only the owner of the allocation can copy an object. +// - allocationID is the allocation id +// - remotePath is the remote path of the file (source path) +// - destPath is the destination path of the file func Copy(allocationID, remotePath, destPath string) (*FileCommandResponse, error) { if len(allocationID) == 0 { @@ -255,6 +287,9 @@ func Copy(allocationID, remotePath, destPath string) (*FileCommandResponse, erro } // Move move file to another remote folder path on dStorage. Only the owner of the allocation can copy an object. +// - allocationID is the allocation id +// - remotePath is the remote path of the file (source path) +// - destPath is the destination path of the file func Move(allocationID, remotePath, destPath string) (*FileCommandResponse, error) { if len(allocationID) == 0 { return nil, RequiredArg("allocationID") @@ -297,6 +332,13 @@ func Move(allocationID, remotePath, destPath string) (*FileCommandResponse, erro } // Share generate an authtoken that provides authorization to the holder to the specified file on the remotepath. +// - allocationID is the allocation id +// - remotePath is the remote path of the file +// - clientID is the client id +// - encryptionPublicKey is the encryption public key of the client to share with, in case of private sharing +// - expiration is the expiration time of the auth ticket +// - revoke is the flag to revoke the share +// - availableAfter is the time after which the share is available func Share(allocationID, remotePath, clientID, encryptionPublicKey string, expiration int, revoke bool, availableAfter string) (string, error) { if len(allocationID) == 0 { @@ -364,16 +406,28 @@ func Share(allocationID, remotePath, clientID, encryptionPublicKey string, expir } -// MultiOperation - do copy, move, delete and createdir operation together +func getFileMetaByName(allocationID, fileNameQuery string) ([]*sdk.ConsolidatedFileMetaByName, error) { + allocationObj, err := getAllocation(allocationID) + if err != nil { + return nil, err + } + fileMetas, err := allocationObj.GetFileMetaByName(fileNameQuery) + if err != nil { + return nil, err + } + return fileMetas, nil +} + +// multiDownload - start multi-download operation. // ## Inputs // - allocationID // - jsonMultiDownloadOptions: Json Array of MultiDownloadOption. -// - authTicket -// - callbackFuncName: callback function name Invoke with totalBytes, completedBytes, objURL, err +// - authTicket +// - callbackFuncName: callback function name Invoke with totalBytes, completedBytes, objURL, err +// // ## Outputs // - json string of array of DownloadCommandResponse -// - error - +// - error func multiDownload(allocationID, jsonMultiDownloadOptions, authTicket, callbackFuncName string) (string, error) { defer func() { if r := recover(); r != nil { @@ -476,6 +530,7 @@ func multiDownload(allocationID, jsonMultiDownloadOptions, authTicket, callbackF return string(respBytes), nil } +// BulkUploadOption options for the a single file upload, usually as part of bulk operations request type BulkUploadOption struct { AllocationID string `json:"allocationId,omitempty"` RemotePath string `json:"remotePath,omitempty"` @@ -495,16 +550,20 @@ type BulkUploadOption struct { MemoryStorer bool `json:"memoryStorer,omitempty"` } +// BulkUploadResult result of a single file upload, usually as part of bulk operations request type BulkUploadResult struct { RemotePath string `json:"remotePath,omitempty"` Success bool `json:"success,omitempty"` Error string `json:"error,omitempty"` } + +// MultiUploadResult result of a multi file upload type MultiUploadResult struct { Success bool `json:"success,omitempty"` Error string `json:"error,omitempty"` } +// MultiOperationOption options for the a single file operation, usually as part of multi operations request type MultiOperationOption struct { OperationType string `json:"operationType,omitempty"` RemotePath string `json:"remotePath,omitempty"` @@ -512,6 +571,7 @@ type MultiOperationOption struct { DestPath string `json:"destPath,omitempty"` // Required for copy and move operation` } +// MultiDownloadOption options for the a single file download, usually as part of multi download request type MultiDownloadOption struct { RemotePath string `json:"remotePath"` LocalPath string `json:"localPath,omitempty"` @@ -522,7 +582,8 @@ type MultiDownloadOption struct { DownloadToDisk bool `json:"downloadToDisk"` } -// MultiOperation - do copy, move, delete and createdir operation together +// MultiOperation do copy, move, delete and createdir operation together +// // ## Inputs // - allocationID // - jsonMultiUploadOptions: Json Array of MultiOperationOption. eg: "[{"operationType":"move","remotePath":"/README.md","destPath":"/folder1/"},{"operationType":"delete","remotePath":"/t3.txt"}]" @@ -561,6 +622,8 @@ func MultiOperation(allocationID string, jsonMultiUploadOptions string) error { return allocationObj.DoMultiOperation(operations) } +// bulkUpload upload multiple files in parallel +// - jsonBulkUploadOptions is the json array of BulkUploadOption func bulkUpload(jsonBulkUploadOptions string) ([]BulkUploadResult, error) { var options []BulkUploadOption err := json.Unmarshal([]byte(jsonBulkUploadOptions), &options) @@ -606,7 +669,8 @@ func bulkUpload(jsonBulkUploadOptions string) ([]BulkUploadResult, error) { return results, nil } -// set upload mode, default is medium, for low set 0, for high set 2 +// setUploadMode set upload mode, default is medium, for low set 0, for high set 2 +// - mode is the upload mode func setUploadMode(mode int) { switch mode { case 0: @@ -618,6 +682,8 @@ func setUploadMode(mode int) { } } +// multiUpload upload multiple files in parallel +// - jsonBulkUploadOptions is the json array of BulkUploadOption. Follows the BulkUploadOption struct func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { defer func() { if r := recover(); r != nil { @@ -830,6 +896,15 @@ func uploadWithJsFuncs(allocationID, remotePath string, readChunkFuncName string } // upload upload file +// - allocationID is the allocation id +// - remotePath is the remote path of the file +// - fileBytes is the file in bytes +// - thumbnailBytes is the thumbnail in bytes +// - webStreaming is the flag to enable web streaming +// - encrypt is the flag to enable encryption of the uploaded file +// - isUpdate is the flag to update the file +// - isRepair is the flag to repair the file +// - numBlocks is the number of blocks to upload func upload(allocationID, remotePath string, fileBytes, thumbnailBytes []byte, webStreaming, encrypt, isUpdate, isRepair bool, numBlocks int) (*FileCommandResponse, error) { if len(allocationID) == 0 { return nil, RequiredArg("allocationID") @@ -908,7 +983,12 @@ func upload(allocationID, remotePath string, fileBytes, thumbnailBytes []byte, w return resp, nil } -// download download file blocks +// downloadBlocks download file blocks +// - allocId : allocation ID of the file +// - remotePath : remote path of the file +// - authTicket : auth ticket of the file, if the file is shared +// - lookupHash : lookup hash of the file, which is used to locate the file if remotepath and allocation id are not provided + func downloadBlocks(allocId string, remotePath, authTicket, lookupHash string, startBlock, endBlock int64) ([]byte, error) { if len(remotePath) == 0 && len(authTicket) == 0 { @@ -962,7 +1042,8 @@ func downloadBlocks(allocId string, remotePath, authTicket, lookupHash string, s return mf.Buffer, nil } -// GetBlobbersList get list of active blobbers, and format them as array json string +// getBlobbers get list of active blobbers, and format them as array json string +// - stakable : flag to get only stakable blobbers func getBlobbers(stakable bool) ([]*sdk.Blobber, error) { blobbs, err := sdk.GetBlobbers(true, stakable) if err != nil { @@ -971,6 +1052,9 @@ func getBlobbers(stakable bool) ([]*sdk.Blobber, error) { return blobbs, err } +// repairAllocation repair the allocation +// Allocation repair is a process to repair the allocation files on its blobbers by re-uploading the missing blocks. +// - allocationID : allocation ID of the file func repairAllocation(allocationID string) error { alloc, err := getAllocation(allocationID) if err != nil { @@ -992,6 +1076,8 @@ func repairAllocation(allocationID string) error { return statusBar.CheckError() } +// checkAllocStatus check the status of the allocation, either it is ok, needs repair or broken +// - allocationID : allocation ID of the file func checkAllocStatus(allocationID string) (string, error) { alloc, err := getAllocation(allocationID) if err != nil { @@ -1020,6 +1106,8 @@ func checkAllocStatus(allocationID string) (string, error) { return string(statusBytes), err } +// skipStatusCheck skip the status check of the allocation +// - allocationID : allocation ID of the file func skipStatusCheck(allocationID string, checkStatus bool) error { alloc, err := getAllocation(allocationID) if err != nil { @@ -1029,6 +1117,8 @@ func skipStatusCheck(allocationID string, checkStatus bool) error { return nil } +// terminateWorkers remove local workers that sync with the allocation +// - allocationID : allocation ID of the file func terminateWorkers(allocationID string) { alloc, err := getAllocation(allocationID) if err != nil { @@ -1045,6 +1135,8 @@ func terminateWorkersWithAllocation(alloc *sdk.Allocation) { } } +// createWorkers create local workers that sync with the allocation +// - allocationID : allocation ID of the file func createWorkers(allocationID string) error { alloc, err := getAllocation(allocationID) if err != nil { diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index f4a3c0057..ff69e5409 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -19,6 +19,15 @@ import ( var bridge *zcnbridge.BridgeClient +// initBridge initializes the bridge client +// - ethereumAddress: ethereum address of the wallet owner +// - bridgeAddress: address of the bridge contract on the Ethereum network +// - authorizersAddress: address of the authorizers contract on the Ethereum network +// - tokenAddress: address of the token contract on the Ethereum network +// - ethereumNodeURL: URL of the Ethereum node +// - gasLimit: gas limit for the transactions +// - value: value to be sent with the transaction (unused) +// - consensusThreshold: consensus threshold for the transactions func initBridge( ethereumAddress string, bridgeAddress string, @@ -60,7 +69,9 @@ func initBridge( return nil } -// Burns ZCN tokens and returns a hash of the burn transaction +// burnZCN Burns ZCN tokens and returns a hash of the burn transaction +// - amount: amount of ZCN tokens to burn +// - txnfee: transaction fee func burnZCN(amount, txnfee uint64) string { //nolint if bridge == nil { return errors.New("burnZCN", "bridge is not initialized").Error() @@ -74,7 +85,9 @@ func burnZCN(amount, txnfee uint64) string { //nolint return tx.GetHash() } -// Mints ZCN tokens and returns a hash of the mint transaction +// mintZCN Mints ZCN tokens and returns a hash of the mint transaction +// - burnTrxHash: hash of the burn transaction +// - timeout: timeout in seconds func mintZCN(burnTrxHash string, timeout int) string { //nolint mintPayload, err := bridge.QueryZChainMintPayload(burnTrxHash) if err != nil { @@ -92,7 +105,8 @@ func mintZCN(burnTrxHash string, timeout int) string { //nolint return hash } -// Returns a payload used to perform minting of WZCN tokens +// getMintWZCNPayload returns the mint payload for the given burn transaction hash +// - burnTrxHash: hash of the burn transaction func getMintWZCNPayload(burnTrxHash string) string { mintPayload, err := bridge.QueryEthereumMintPayload(burnTrxHash) if err != nil { @@ -107,7 +121,7 @@ func getMintWZCNPayload(burnTrxHash string) string { return string(result) } -// Returns all not processed WZCN burn events for the given client id param +// getNotProcessedWZCNBurnEvents returns all not processed WZCN burn events from the Ethereum network func getNotProcessedWZCNBurnEvents() string { var mintNonce int64 cb := wallet.NewZCNStatus(&mintNonce) @@ -141,7 +155,7 @@ func getNotProcessedWZCNBurnEvents() string { return string(result) } -// Returns all not processed ZCN burn tickets burned for a certain ethereum address +// getNotProcessedZCNBurnTickets Returns all not processed ZCN burn tickets burned for a certain ethereum address func getNotProcessedZCNBurnTickets() string { userNonce, err := bridge.GetUserNonceMinted(context.Background(), bridge.EthereumAddress) if err != nil { @@ -175,6 +189,9 @@ func getNotProcessedZCNBurnTickets() string { } // estimateBurnWZCNGasAmount performs gas amount estimation for the given burn wzcn transaction. +// - from: address of the sender +// - to: address of the receiver +// - amountTokens: amount of tokens to burn (as a string) func estimateBurnWZCNGasAmount(from, to, amountTokens string) string { // nolint:golint,unused estimateBurnWZCNGasAmountResponse, err := bridge.EstimateBurnWZCNGasAmount( context.Background(), from, to, amountTokens) @@ -192,6 +209,12 @@ func estimateBurnWZCNGasAmount(from, to, amountTokens string) string { // nolint } // estimateMintWZCNGasAmount performs gas amount estimation for the given mint wzcn transaction. +// - from: address of the sender +// - to: address of the receiver +// - zcnTransaction: hash of the ZCN transaction +// - amountToken: amount of tokens to mint (as a string) +// - nonce: nonce of the transaction +// - signaturesRaw: encoded format (base-64) of the burn signatures received from the authorizers. func estimateMintWZCNGasAmount(from, to, zcnTransaction, amountToken string, nonce int64, signaturesRaw []string) string { // nolint:golint,unused var signaturesBytes [][]byte diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 1cac6d653..ed00387a8 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -23,6 +23,10 @@ var ( cachedAllocations, _ = lru.New[string, *cachedAllocation](100) ) +// getAllocation get allocation from cache +// if not found in cache, fetch from blockchain +// and store in cache +// - allocationId is the allocation id func getAllocation(allocationId string) (*sdk.Allocation, error) { it, ok := cachedAllocations.Get(allocationId) @@ -52,6 +56,8 @@ func clearAllocation(allocationID string) { cachedAllocations.Remove(allocationID) } +// reloadAllocation reload allocation from blockchain and update cache +// - allocationID is the allocation id func reloadAllocation(allocationID string) (*sdk.Allocation, error) { a, err := sdk.GetAllocation(allocationID) if err != nil { diff --git a/wasmsdk/chunked_upload_progress_storer.go b/wasmsdk/chunked_upload_progress_storer.go index 325d8da39..d839d5be0 100644 --- a/wasmsdk/chunked_upload_progress_storer.go +++ b/wasmsdk/chunked_upload_progress_storer.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk/zboxcore/zboxutil" ) // chunkedUploadProgressStorer load and save upload progress @@ -43,7 +44,7 @@ func (mem *chunkedUploadProgressStorer) Save(up sdk.UploadProgress) { } //nolint:golint,unused -func (mem *chunkedUploadProgressStorer) Update(id string, chunkIndex int) { +func (mem *chunkedUploadProgressStorer) Update(id string, chunkIndex int, _ zboxutil.Uint128) { mem.lock.Lock() defer mem.lock.Unlock() if mem.list == nil { diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index ad0cab057..6c899cdd7 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -1,3 +1,4 @@ +// Demo for the wasm sdk- do not use. package main import ( diff --git a/wasmsdk/doc.go b/wasmsdk/doc.go new file mode 100644 index 000000000..4cc3a3ede --- /dev/null +++ b/wasmsdk/doc.go @@ -0,0 +1,2 @@ +// Provides an interface for the SDK functions to be used to build a WebAssemply SDK for usage in the webapps. +package main \ No newline at end of file diff --git a/wasmsdk/jsbridge/doc.go b/wasmsdk/jsbridge/doc.go new file mode 100644 index 000000000..01fc635d3 --- /dev/null +++ b/wasmsdk/jsbridge/doc.go @@ -0,0 +1,3 @@ +// Utilities for interacting with the JavaScript runtime. +// Used by the wasmsdk to provide the needed low-level interop between Go and JavaScript. +package jsbridge \ No newline at end of file diff --git a/wasmsdk/player.go b/wasmsdk/player.go index c48ed36e8..a391e1a6b 100644 --- a/wasmsdk/player.go +++ b/wasmsdk/player.go @@ -5,6 +5,7 @@ package main import "errors" +// Player is the interface for a file player type Player interface { Start() error Stop() @@ -14,6 +15,12 @@ type Player interface { var currentPlayer Player +// play starts playing a playable file or stream +// - allocationID is the allocation id +// - remotePath is the remote path of the file or stream +// - authTicket is the auth ticket, in case of accessing as a shared file +// - lookupHash is the lookup hash for the file +// - isLive is the flag to indicate if the file is live or not func play(allocationID, remotePath, authTicket, lookupHash string, isLive bool) error { var err error @@ -39,6 +46,7 @@ func play(allocationID, remotePath, authTicket, lookupHash string, isLive bool) } +// stop stops the current player func stop() error { if currentPlayer != nil { currentPlayer.Stop() @@ -49,6 +57,7 @@ func stop() error { return nil } +// getNextSegment gets the next segment of the current player func getNextSegment() ([]byte, error) { if currentPlayer == nil { return nil, errors.New("No player is available") diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 2652bc729..fac087a50 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -201,6 +201,7 @@ func main() { "skipStatusCheck": skipStatusCheck, "terminateWorkers": terminateWorkers, "createWorkers": createWorkers, + "getFileMetaByName": getFileMetaByName, // player "play": play, diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 0521c8857..6503f8844 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -22,7 +22,16 @@ import ( var CreateObjectURL func(buf []byte, mimeType string) string -// initSDKs init sharder/miners , +// initSDKs init sdk with its parameters +// - chainID is the chain id +// - blockWorker is the block worker url, which is the DNS server used to locate the network nodes +// - signatureScheme is the signature scheme used for signing transactions +// - minConfirmation is the minimum number of confirmations required for a transaction to be considered final +// - minSubmit is the minimum number of times a transaction must be submitted to the network +// - confirmationChainLength is the number of blocks to wait for a transaction to be confirmed +// - zboxHost is the url of the 0box service +// - zboxAppType is the application type of the 0box service +// - sharderconsensous is the number of sharders to reach consensus func initSDKs(chainID, blockWorker, signatureScheme string, minConfirmation, minSubmit, confirmationChainLength int, zboxHost, zboxAppType string, sharderconsensous int) error { @@ -49,6 +58,7 @@ func initSDKs(chainID, blockWorker, signatureScheme string, return nil } +// getVersion retrieve the sdk version func getVersion() string { return sdk.GetVersion() } @@ -57,6 +67,7 @@ var sdkLogger *logger.Logger var zcnLogger *logger.Logger var logEnabled = false +// showLogs enable logging func showLogs() { zcnLogger.SetLevel(logger.DEBUG) sdkLogger.SetLevel(logger.DEBUG) @@ -67,6 +78,7 @@ func showLogs() { logEnabled = true } +// hideLogs disable logging func hideLogs() { zcnLogger.SetLevel(logger.ERROR) sdkLogger.SetLevel(logger.ERROR) @@ -77,6 +89,8 @@ func hideLogs() { logEnabled = false } +// isWalletID check if the client id is a valid wallet hash +// - clientID is the client id to check func isWalletID(clientID string) bool { if clientID == "" { return false @@ -97,7 +111,10 @@ func isHash(str string) bool { return err == nil && len(bytes) == HASH_LENGTH } -// getLookupHash get lookup hash with allocation id and path +// getLookupHash retrieve lookup hash with allocation id and path +// Lookup hash is generated by hashing the allocation id and path +// - allocationID is the allocation id +// - path is the path func getLookupHash(allocationID string, path string) string { return encryption.Hash(allocationID + ":" + path) } @@ -114,10 +131,18 @@ func getLookupHash(allocationID string, path string) string { // - vp8 // - vp8l // - webp +// Paramters: +// - buf is the image buffer which carry the image in bytes +// - width is the width of the thumbnail +// - height is the height of the thumbnail func createThumbnail(buf []byte, width, height int) ([]byte, error) { return imageutil.CreateThumbnail(buf, width, height) } +// makeSCRestAPICall issue a request to the public API of one of the smart contracts +// - scAddress is the smart contract address +// - relativePath is the relative path of the endpoint +// - paramsJson is the parameters in JSON format. It's a key-value map, and added as query parameters to the request. func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, error) { var params map[string]string err := json.Unmarshal([]byte(paramsJson), ¶ms) @@ -128,6 +153,11 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro return string(b), err } +// send Send tokens to a client +// - toClientID is the client id to send tokens to +// - tokens is the number of tokens to send +// - fee is the transaction fee +// - desc is the description of the transaction func send(toClientID string, tokens uint64, fee uint64, desc string) (string, error) { wg := &sync.WaitGroup{} cb := &transactionCallback{wg: wg} diff --git a/wasmsdk/smartcontract.go b/wasmsdk/smartcontract.go index e0421dfb1..582bea1c1 100644 --- a/wasmsdk/smartcontract.go +++ b/wasmsdk/smartcontract.go @@ -13,6 +13,11 @@ func faucet(methodName, input string, token float64) (*transaction.Transaction, return executeSmartContract(zcncore.FaucetSmartContractAddress, methodName, input, zcncore.ConvertToValue(token)) } +// executeSmartContract issue a smart contract transaction +// - address is the smart contract address +// - methodName is the method name to be called +// - input is the input data for the method +// - value is the value to be sent with the transaction func executeSmartContract(address, methodName, input string, value uint64) (*transaction.Transaction, error) { wg := &sync.WaitGroup{} cb := &transactionCallback{wg: wg} diff --git a/wasmsdk/tokenrate.go b/wasmsdk/tokenrate.go index 6b1d813ad..66cc05f0d 100644 --- a/wasmsdk/tokenrate.go +++ b/wasmsdk/tokenrate.go @@ -6,6 +6,7 @@ import ( "github.com/0chain/gosdk/core/tokenrate" ) +// getUSDRate gets the USD rate for the given crypto symbol func getUSDRate(symbol string) (float64, error) { return tokenrate.GetUSD(context.TODO(), symbol) } diff --git a/wasmsdk/updateImage.go b/wasmsdk/updateImage.go index d793a2c11..c3ffce2ad 100644 --- a/wasmsdk/updateImage.go +++ b/wasmsdk/updateImage.go @@ -34,7 +34,16 @@ const ( ) // --- exposed functions --- -// UpdateContainer update the given container ID with a new image +// UpdateContainer update the given container ID with a new image ID in a given domain +// The domain should expose the docker API endpoints under `/endpoints/{endpointID}/docker` +// The request should be authenticated with the given username and password, by first creating an auth token then issuing the request. +// +// Parameters: +// - username is the username to authenticate with +// - password is the password to authenticate with +// - domain is the domain to issue the request to +// - containerID is the ID of the container to update +// - NewImageID is the ID of the new image to update the container with func UpdateContainer(username, password, domain, containerID, NewImageID string) (map[string]interface{}, error) { sdkLogger.Info("generating authtoken") authToken, err := getToken(username, password, domain) @@ -110,7 +119,14 @@ func UpdateContainer(username, password, domain, containerID, NewImageID string) return newContainer, nil } -// GetContainers returns all the running containers +// GetContainers returns all the running containers in a given domain exposing the `/endpoints/{endpointID}/docker/containers/json` endpoint +// The request should be authenticated with the given username and password, by first creating an auth token then issuing the request. +// The response is a list of containers in JSON format. +// +// Parameters: +// - username is the username to authenticate with +// - password is the password to authenticate with +// - domain is the domain to issue the request to func GetContainers(username, password, domain string) ([]*map[string]interface{}, error) { authToken, err := getToken(username, password, domain) if err != nil { @@ -142,7 +158,15 @@ func GetContainers(username, password, domain string) ([]*map[string]interface{} return nil, fmt.Errorf("returned response %d. Body: %s", status, string(body)) } -// SearchContainer search a container with a given name +// SearchContainer search a container with a given name in a given domain exposing the `/endpoints/{endpointID}/docker/containers/json` endpoint +// The request should be authenticated with the given username and password, by first creating an auth token then issuing the request. +// The response is a list of containers in JSON format that match the given name. +// +// Parameters: +// - username is the username to authenticate with +// - password is the password to authenticate with +// - domain is the domain to issue the request to +// - name is the name of the container to search for func SearchContainer(username, password, domain, name string) ([]*map[string]interface{}, error) { authToken, err := getToken(username, password, domain) if err != nil { diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index 453963ea7..ee3d820b5 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -11,6 +11,11 @@ import ( "github.com/0chain/gosdk/zcncore" ) +// setWallet sets the wallet used by the client for the network transactions and the backend API requests +// - clientID is the client id +// - publicKey is the public key of the client +// - privateKey is the private key of the client +// - mnemonic is the mnemonic of the client func setWallet(clientID, publicKey, privateKey, mnemonic string) error { if mnemonic == "" { return errors.New("mnemonic is required") diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index 2915a7953..265beeed9 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -6,18 +6,21 @@ import ( // Split keys from the primary master key +// splitKeys splits the primary master key into n number of keys +// - privateKey is the primary master key +// - numSplits is the number of keys to split into +// // nolint: unused func splitKeys(privateKey string, numSplits int) (string, error) { wStr, err := zcncore.SplitKeys(privateKey, numSplits) return wStr, err } -// SetWalletInfo should be set before any transaction or client specific APIs +// setWalletInfo should be set before any transaction or client specific APIs. // splitKeyWallet parameter is valid only if SignatureScheme is "BLS0Chain" -// # Inputs -// - jsonWallet: json format of wallet -// - splitKeyWallet: if wallet keys is split - +// - jsonWallet: json format of wallet +// - splitKeyWallet: if wallet keys is split +// // nolint: unused func setWalletInfo(jsonWallet string, splitKeyWallet bool) bool { err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) @@ -28,10 +31,9 @@ func setWalletInfo(jsonWallet string, splitKeyWallet bool) bool { } } -// SetAuthUrl will be called by app to set zauth URL to SDK. -// # Inputs -// - url: the url of zAuth server - +// setAuthUrl will be called by app to set zauth URL to SDK. +// - url: the url of zAuth server +// // nolint: unused func setAuthUrl(url string) bool { err := zcncore.SetAuthUrl(url) diff --git a/wasmsdk/zbox.go b/wasmsdk/zbox.go index 236d8dca4..257f7660f 100644 --- a/wasmsdk/zbox.go +++ b/wasmsdk/zbox.go @@ -19,6 +19,7 @@ func setZbox(host, appType string) { } +// getCsrfToken gets csrf token from 0box api func getCsrfToken() (string, error) { if zboxApiClient == nil { return "", ErrZboxApiNotInitialized @@ -26,6 +27,8 @@ func getCsrfToken() (string, error) { return zboxApiClient.GetCsrfToken(context.TODO()) } +// createJwtSession creates jwt session for the given phone number +// - phoneNumber is the phone number of the user func createJwtSession(phoneNumber string) (int64, error) { if zboxApiClient == nil { return 0, ErrZboxApiNotInitialized @@ -33,6 +36,10 @@ func createJwtSession(phoneNumber string) (int64, error) { return zboxApiClient.CreateJwtSession(context.TODO(), phoneNumber) } +// createJwtToken creates jwt token for the given phone number +// - phoneNumber is the phone number of the user +// - jwtSessionID is the jwt session id +// - otp is the one time password func createJwtToken(phoneNumber string, jwtSessionID int64, otp string) (string, error) { if zboxApiClient == nil { return "", ErrZboxApiNotInitialized @@ -40,6 +47,9 @@ func createJwtToken(phoneNumber string, jwtSessionID int64, otp string) (string, return zboxApiClient.CreateJwtToken(context.TODO(), phoneNumber, jwtSessionID, otp) } +// refreshJwtToken refreshes jwt token for the given phone number +// - phoneNumber is the phone number of the user +// - token is the jwt token to refresh func refreshJwtToken(phoneNumber string, token string) (string, error) { if zboxApiClient == nil { return "", ErrZboxApiNotInitialized diff --git a/wasmsdk/zcn.go b/wasmsdk/zcn.go index 91c65cfa2..0fac9e39f 100644 --- a/wasmsdk/zcn.go +++ b/wasmsdk/zcn.go @@ -9,11 +9,13 @@ import ( ) type Balance struct { - ZCN float64 `json:"zcn"` - USD float64 `json:"usd"` - Nonce int64 `json:"nonce"` + ZCN float64 `json:"zcn"` + USD float64 `json:"usd"` + Nonce int64 `json:"nonce"` } +// getWalletBalance retrieves the wallet balance of the client from the network. +// - clientId is the client id func getWalletBalance(clientId string) (*Balance, error) { zcn, nonce, err := zcncore.GetWalletBalance(clientId) @@ -32,12 +34,13 @@ func getWalletBalance(clientId string) (*Balance, error) { } return &Balance{ - ZCN: zcnToken, - USD: usd, + ZCN: zcnToken, + USD: usd, Nonce: nonce, }, nil } +// createReadPool creates a read pool for the client where they should lock tokens to be able to read data. func createReadPool() (string, error) { hash, _, err := sdk.CreateReadPool() return hash, err diff --git a/winsdk/doc.go b/winsdk/doc.go new file mode 100644 index 000000000..f73fb6714 --- /dev/null +++ b/winsdk/doc.go @@ -0,0 +1,2 @@ +// Provides an interface for the SDK functions to be used to build an SDK for usage in developing Windows applications. +package main \ No newline at end of file diff --git a/zboxapi/doc.go b/zboxapi/doc.go new file mode 100644 index 000000000..173276726 --- /dev/null +++ b/zboxapi/doc.go @@ -0,0 +1,2 @@ +// Provides functions and types to communicate with the 0box API (an off-chain service that provides functionality for the applications out of the scope of the chain transactions). +package zboxapi \ No newline at end of file diff --git a/zboxcore/allocationchange/doc.go b/zboxcore/allocationchange/doc.go new file mode 100644 index 000000000..306ce70fc --- /dev/null +++ b/zboxcore/allocationchange/doc.go @@ -0,0 +1,2 @@ +// Types and methods related to file operations (rename, move, delete, etc). +package allocationchange \ No newline at end of file diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go index 8e562a8c7..991558be4 100644 --- a/zboxcore/blockchain/entity.go +++ b/zboxcore/blockchain/entity.go @@ -1,3 +1,4 @@ +// Methods and types for blockchain entities and interactions. package blockchain import ( @@ -24,6 +25,7 @@ func calculateMinRequired(minRequired, percent float64) int { return int(math.Ceil(minRequired * percent)) } +// GetStableMiners get stable miners func GetStableMiners() []string { mGuard.Lock() defer mGuard.Unlock() @@ -33,6 +35,8 @@ func GetStableMiners() []string { return miners } + +// ResetStableMiners reset stable miners to random miners func ResetStableMiners() { mGuard.Lock() defer mGuard.Unlock() @@ -57,25 +61,28 @@ type StakePoolSettings struct { ServiceCharge float64 `json:"service_charge"` } -// UpdateStakePoolSettings information. +// UpdateStakePoolSettings represent stake pool information of a provider node. type UpdateStakePoolSettings struct { DelegateWallet *string `json:"delegate_wallet,omitempty"` NumDelegates *int `json:"num_delegates,omitempty"` ServiceCharge *float64 `json:"service_charge,omitempty"` } +// ValidationNode represents a validation node (miner) type ValidationNode struct { ID string `json:"id"` BaseURL string `json:"url"` StakePoolSettings StakePoolSettings `json:"stake_pool_settings"` } +// UpdateValidationNode represents a validation node (miner) update type UpdateValidationNode struct { ID string `json:"id"` BaseURL *string `json:"url"` StakePoolSettings *UpdateStakePoolSettings `json:"stake_pool_settings"` } +// StorageNode represents a storage node (blobber) type StorageNode struct { ID string `json:"id"` Baseurl string `json:"url"` @@ -84,6 +91,8 @@ type StorageNode struct { skip uint64 `json:"-"` // skip on error } +// SetSkip set skip, whether to skip this node in operations or not +// - t is the boolean value func (sn *StorageNode) SetSkip(t bool) { var val uint64 if t { @@ -92,10 +101,13 @@ func (sn *StorageNode) SetSkip(t bool) { atomic.StoreUint64(&sn.skip, val) } +// IsSkip check if skip func (sn *StorageNode) IsSkip() bool { return atomic.LoadUint64(&sn.skip) > 0 } +// PopulateNodes populate nodes from json string +// - nodesjson is the json string func PopulateNodes(nodesjson string) ([]string, error) { sharders := make([]string, 0) err := json.Unmarshal([]byte(nodesjson), &sharders) @@ -114,10 +126,14 @@ func init() { } } +// GetChainConfig get chain config func GetChainID() string { return chain.ChainID } +// PopulateChain populate chain from json string +// - minerjson is the array of miner urls, serialized as json +// - sharderjson is the array of sharder urls, serialized as json func PopulateChain(minerjson string, sharderjson string) error { var err error chain.Miners, err = PopulateNodes(minerjson) @@ -132,21 +148,27 @@ func PopulateChain(minerjson string, sharderjson string) error { return nil } +// GetBlockWorker get block worker func GetBlockWorker() string { return chain.BlockWorker } +// GetSharders get sharders func GetAllSharders() []string { return Sharders.All() } + +// GetSharders get healthy sharders func GetSharders() []string { return Sharders.Healthy() } +// GetMiners get miners func GetMiners() []string { return chain.Miners } +// GetMaxTxnQuery get max transaction query func GetMaxTxnQuery() int { return chain.MaxTxnQuery } @@ -187,18 +209,26 @@ func SetChainID(id string) { chain.ChainID = id } +// SetMaxTxnQuery set max transaction query, maximum number of trials to query a transaction confirmation from sharders. +// - num is the number of transaction query func SetMaxTxnQuery(num int) { chain.MaxTxnQuery = num } +// SetQuerySleepTime set query sleep time, number of seconds to sleep between each transaction query. +// - time is the sleep time func SetQuerySleepTime(time int) { chain.QuerySleepTime = time } +// SetMinSubmit set minimum submit, minimum number of miners to submit a transaction +// - minSubmit is the minimum submit func SetMinSubmit(minSubmit int) { chain.MinSubmit = minSubmit } +// SetMinConfirmation set minimum confirmation, minimum number of miners to confirm a transaction +// - minConfirmation is the minimum confirmation func SetMinConfirmation(minConfirmation int) { chain.MinConfirmation = minConfirmation } diff --git a/zboxcore/client/entity.go b/zboxcore/client/entity.go index f36e0e30a..fa50ab6e2 100644 --- a/zboxcore/client/entity.go +++ b/zboxcore/client/entity.go @@ -1,3 +1,4 @@ +// Methods and types for client and wallet operations. package client import ( @@ -9,6 +10,7 @@ import ( type SignFunc func(hash string) (string, error) +// Client represents client information type Client struct { *zcncrypto.Wallet SignatureScheme string @@ -18,7 +20,9 @@ type Client struct { var ( client *Client clients []*Client - Sign SignFunc + + // Sign is a function to sign a hash + Sign SignFunc ) func init() { @@ -37,12 +41,15 @@ func init() { } // PopulateClient populates single client +// - clientjson: client json string +// - signatureScheme: signature scheme func PopulateClient(clientjson string, signatureScheme string) error { err := json.Unmarshal([]byte(clientjson), &client) client.SignatureScheme = signatureScheme return err } +// SetClientNonce sets client nonce func SetClientNonce(nonce int64) { client.Nonce = nonce } @@ -58,6 +65,8 @@ func TxnFee() uint64 { } // PopulateClients This is a workaround for blobber tests that requires multiple clients to test authticket functionality +// - clientJsons: array of client json strings +// - signatureScheme: signature scheme func PopulateClients(clientJsons []string, signatureScheme string) error { for _, clientJson := range clientJsons { c := new(Client) @@ -70,22 +79,27 @@ func PopulateClients(clientJsons []string, signatureScheme string) error { return nil } +// GetClient returns client instance func GetClient() *Client { return client } +// GetClients returns all clients func GetClients() []*Client { return clients } +// GetClientID returns client id func GetClientID() string { return client.ClientID } +// GetClientPublicKey returns client public key func GetClientPublicKey() string { return client.ClientKey } +// GetClientPrivateKey returns client private key func GetClientPrivateKey() string { for _, kv := range client.Keys { return kv.PrivateKey @@ -130,6 +144,9 @@ func signHash(hash string, signatureScheme string, keys []sys.KeyPair) (string, return retSignature, nil } +// VerifySignature verifies signature of a message with client public key and signature scheme +// - signature: signature to use for verification +// - msg: message to verify func VerifySignature(signature string, msg string) (bool, error) { ss := zcncrypto.NewSignatureScheme(client.SignatureScheme) if err := ss.SetPublicKey(client.ClientKey); err != nil { @@ -139,6 +156,10 @@ func VerifySignature(signature string, msg string) (bool, error) { return ss.Verify(signature, msg) } +// VerifySignatureWith verifies signature of a message with a given public key, and the client's signature scheme +// - pubKey: public key to use for verification +// - signature: signature to use for verification +// - hash: message to verify func VerifySignatureWith(pubKey, signature, hash string) (bool, error) { sch := zcncrypto.NewSignatureScheme(client.SignatureScheme) err := sch.SetPublicKey(pubKey) diff --git a/zboxcore/doc.go b/zboxcore/doc.go new file mode 100644 index 000000000..bbe249646 --- /dev/null +++ b/zboxcore/doc.go @@ -0,0 +1,2 @@ +// Contains sub-packages and modules for managing users' storage and allocations. +package zboxcore diff --git a/zboxcore/encoder/erasurecode.go b/zboxcore/encoder/erasurecode.go index 9345dc7e8..cb22fd151 100644 --- a/zboxcore/encoder/erasurecode.go +++ b/zboxcore/encoder/erasurecode.go @@ -1,3 +1,4 @@ +// Stream Encoder for erasure coding. package encoder import ( diff --git a/zboxcore/encryption/doc.go b/zboxcore/encryption/doc.go new file mode 100644 index 000000000..574ebf163 --- /dev/null +++ b/zboxcore/encryption/doc.go @@ -0,0 +1,2 @@ +// Methods and types for encryption operations. +package encryption \ No newline at end of file diff --git a/zboxcore/encryption/pre.go b/zboxcore/encryption/pre.go index f4871ce9d..3f02b4d20 100644 --- a/zboxcore/encryption/pre.go +++ b/zboxcore/encryption/pre.go @@ -405,13 +405,8 @@ func (pre *PREEncryptionScheme) SymEnc(group kyber.Group, message []byte, keyhas if err != nil { return nil, err } - c := aesgcm.Seal(nil, nonce, message, nil) - var ctx bytes.Buffer - _, err = ctx.Write(c) - if err != nil { - return nil, err - } - return ctx.Bytes(), nil + c := aesgcm.Seal(message[:0], nonce, message, nil) + return c, nil } func UnmarshallPublicKey(publicKey string) (kyber.Point, error) { @@ -443,7 +438,7 @@ func (pre *PREEncryptionScheme) SymDec(group kyber.Group, ctx []byte, keyhash [] if err != nil { return nil, err } - return aesgcm.Open(nil, nonce, ctx, nil) + return aesgcm.Open(ctx[:0], nonce, ctx, nil) } func (pre *PREEncryptionScheme) Encrypt(data []byte) (*EncryptedMessage, error) { diff --git a/zboxcore/encryption/scheme.go b/zboxcore/encryption/scheme.go index 6f2fd234b..9f55158b8 100644 --- a/zboxcore/encryption/scheme.go +++ b/zboxcore/encryption/scheme.go @@ -1,5 +1,6 @@ package encryption +// EncryptionScheme interface for encryption schemes type EncryptionScheme interface { Initialize(mnemonic string) ([]byte, error) InitializeWithPrivateKey(privateKey []byte) error @@ -18,10 +19,12 @@ type EncryptionScheme interface { GetEncryptedKeyPoint() string } +// NewEncryptionScheme create a new encryption scheme func NewEncryptionScheme() EncryptionScheme { return new(PREEncryptionScheme) } +// EncryptedMessage encrypted message structure type EncryptedMessage struct { EncryptedKey string EncryptedData []byte diff --git a/zboxcore/fileref/doc.go b/zboxcore/fileref/doc.go new file mode 100644 index 000000000..517ac3a63 --- /dev/null +++ b/zboxcore/fileref/doc.go @@ -0,0 +1,6 @@ +// Methods and types to interact with File Reference. +// File References are the representation of files in the blobbers DB, +// which carry the metadata of the file in and of itself, +// its information in the context of the allocation, +// and the location of the file in the blobbers filesystem. +package fileref \ No newline at end of file diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index 7dc024093..ae8581468 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -12,10 +12,14 @@ import ( lru "github.com/hashicorp/golang-lru/v2" ) +// File read/write chunk size const CHUNK_SIZE = 64 * 1024 const ( + // FILE represents a file for fileref FILE = "f" + + // DIRECTORY represents a directory for fileref DIRECTORY = "d" REGULAR = "regular" ) @@ -98,6 +102,9 @@ type Ref struct { UpdatedAt common.Timestamp `json:"updated_at" mapstructure:"updated_at"` } +// GetReferenceLookup returns the lookup hash for a given allocationID and path +// - allocationID: allocation ID +// - path: path of the file func GetReferenceLookup(allocationID string, path string) string { return encryption.Hash(allocationID + ":" + path) } diff --git a/zboxcore/logger/logger.go b/zboxcore/logger/logger.go index 155e80102..37a89ee44 100644 --- a/zboxcore/logger/logger.go +++ b/zboxcore/logger/logger.go @@ -1,8 +1,11 @@ +// Proxy for the core logger package. package logger import "github.com/0chain/gosdk/core/logger" var defaultLogLevel = logger.DEBUG + +// Logger global logger instance var Logger logger.Logger func init() { diff --git a/zboxcore/marker/authticket.go b/zboxcore/marker/authticket.go index 4cf3a94a9..781c9d899 100644 --- a/zboxcore/marker/authticket.go +++ b/zboxcore/marker/authticket.go @@ -7,6 +7,10 @@ import ( "github.com/0chain/gosdk/zboxcore/client" ) +// AuthTicket authentication ticket for file sharing. +// AuthTicket is used to provide access to a file or directory by non-owner clients. +// It's generated by the owner client and signed with their wallet's private key. +// Then shared with the non-owner client to be able to access the shared file or directory. type AuthTicket struct { ClientID string `json:"client_id"` OwnerID string `json:"owner_id"` @@ -22,6 +26,7 @@ type AuthTicket struct { Signature string `json:"signature"` } +// NewAuthTicket returns the MPT hash of the AuthTicket func (at *AuthTicket) GetHashData() string { hashData := fmt.Sprintf("%v:%v:%v:%v:%v:%v:%v:%v:%v:%v:%v", at.AllocationID, @@ -39,6 +44,7 @@ func (at *AuthTicket) GetHashData() string { return hashData } +// Sign signs the AuthTicket func (at *AuthTicket) Sign() error { var err error hash := encryption.Hash(at.GetHashData()) diff --git a/zboxcore/marker/doc.go b/zboxcore/marker/doc.go new file mode 100644 index 000000000..de27c191d --- /dev/null +++ b/zboxcore/marker/doc.go @@ -0,0 +1,5 @@ +// Methods and types to interact with Read and Write Markers. +// Read and Write Markers are the representation of the read and write operations, +// and a means by which the blobber is paid for storage cost. +// Write markers also are used to determine the latest allocation version. +package marker \ No newline at end of file diff --git a/zboxcore/mocks/doc.go b/zboxcore/mocks/doc.go new file mode 100644 index 000000000..d5f5048fa --- /dev/null +++ b/zboxcore/mocks/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! Do not use. +package mocks \ No newline at end of file diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index ad5c312c1..cfc4b736b 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -74,6 +74,7 @@ var GetFileInfo = func(localpath string) (os.FileInfo, error) { return sys.Files.Stat(localpath) } +// BlobberAllocationStats represents the blobber allocation statistics. type BlobberAllocationStats struct { BlobberID string BlobberURL string @@ -100,6 +101,7 @@ type BlobberAllocationStats struct { } `json:"Terms"` } +// ConsolidatedFileMeta represents the file meta data. type ConsolidatedFileMeta struct { Name string Type string @@ -119,6 +121,27 @@ type ConsolidatedFileMeta struct { Collaborators []fileref.Collaborator } +type ConsolidatedFileMetaByName struct { + Name string + Type string + Path string + LookupHash string + Hash string + MimeType string + Size int64 + NumBlocks int64 + ActualFileSize int64 + ActualNumBlocks int64 + EncryptedKey string + FileMetaHash string + ThumbnailHash string + ActualThumbnailSize int64 + ActualThumbnailHash string + Collaborators []fileref.Collaborator + CreatedAt common.Timestamp + UpdatedAt common.Timestamp +} + type AllocationStats struct { UsedSize int64 `json:"used_size"` NumWrites int64 `json:"num_of_writes"` @@ -157,6 +180,7 @@ type UpdateTerms struct { MaxOfferDuration *time.Duration `json:"max_offer_duration,omitempty"` } +// BlobberAllocation represents the blobber in the context of an allocation type BlobberAllocation struct { BlobberID string `json:"blobber_id"` Size int64 `json:"size"` @@ -170,20 +194,46 @@ type BlobberAllocation struct { FinalReward common.Balance `json:"final_reward"` } +// Allocation represents a storage allocation. type Allocation struct { - ID string `json:"id"` - Tx string `json:"tx"` - DataShards int `json:"data_shards"` - ParityShards int `json:"parity_shards"` - Size int64 `json:"size"` - Expiration int64 `json:"expiration_date"` - Owner string `json:"owner_id"` - OwnerPublicKey string `json:"owner_public_key"` - Payer string `json:"payer_id"` - Blobbers []*blockchain.StorageNode `json:"blobbers"` - Stats *AllocationStats `json:"stats"` - TimeUnit time.Duration `json:"time_unit"` - WritePool common.Balance `json:"write_pool"` + // ID is the unique identifier of the allocation. + ID string `json:"id"` + // Tx is the transaction hash of the latest transaction related to the allocation. + Tx string `json:"tx"` + + // DataShards is the number of data shards. + DataShards int `json:"data_shards"` + + // ParityShards is the number of parity shards. + ParityShards int `json:"parity_shards"` + + // Size is the size of the allocation. + Size int64 `json:"size"` + + // Expiration is the expiration date of the allocation. + Expiration int64 `json:"expiration_date"` + + // Owner is the id of the owner of the allocation. + Owner string `json:"owner_id"` + + // OwnerPublicKey is the public key of the owner of the allocation. + OwnerPublicKey string `json:"owner_public_key"` + + // Payer is the id of the payer of the allocation. + Payer string `json:"payer_id"` + + // Blobbers is the list of blobbers that store the data of the allocation. + Blobbers []*blockchain.StorageNode `json:"blobbers"` + + // Stats contains the statistics of the allocation. + Stats *AllocationStats `json:"stats"` + + // TimeUnit is the time unit of the allocation. + TimeUnit time.Duration `json:"time_unit"` + + // WritePool is the write pool of the allocation. + WritePool common.Balance `json:"write_pool"` + // BlobberDetails contains real terms used for the allocation. // If the allocation has updated, then terms calculated using // weighted average values. @@ -191,18 +241,47 @@ type Allocation struct { // ReadPriceRange is requested reading prices range. ReadPriceRange PriceRange `json:"read_price_range"` + // WritePriceRange is requested writing prices range. - WritePriceRange PriceRange `json:"write_price_range"` - MinLockDemand float64 `json:"min_lock_demand"` - ChallengeCompletionTime time.Duration `json:"challenge_completion_time"` - StartTime common.Timestamp `json:"start_time"` - Finalized bool `json:"finalized,omitempty"` - Canceled bool `json:"canceled,omitempty"` - MovedToChallenge common.Balance `json:"moved_to_challenge,omitempty"` - MovedBack common.Balance `json:"moved_back,omitempty"` - MovedToValidators common.Balance `json:"moved_to_validators,omitempty"` - FileOptions uint16 `json:"file_options"` - ThirdPartyExtendable bool `json:"third_party_extendable"` + WritePriceRange PriceRange `json:"write_price_range"` + + // MinLockDemand is the minimum lock demand of the allocation. + MinLockDemand float64 `json:"min_lock_demand"` + + // ChallengeCompletionTime is the time taken to complete a challenge. + ChallengeCompletionTime time.Duration `json:"challenge_completion_time"` + + // StartTime is the start time of the allocation. + StartTime common.Timestamp `json:"start_time"` + + // Finalized is the flag to indicate if the allocation is finalized. + Finalized bool `json:"finalized,omitempty"` + + // Cancelled is the flag to indicate if the allocation is cancelled. + Canceled bool `json:"canceled,omitempty"` + + // MovedToChallenge is the amount moved to challenge pool related to the allocation. + MovedToChallenge common.Balance `json:"moved_to_challenge,omitempty"` + + // MovedBack is the amount moved back from the challenge pool related to the allocation. + MovedBack common.Balance `json:"moved_back,omitempty"` + + // MovedToValidators is the amount moved to validators related to the allocation. + MovedToValidators common.Balance `json:"moved_to_validators,omitempty"` + + // FileOptions is a bitmask of file options, which are the permissions of the allocation. + FileOptions uint16 `json:"file_options"` + + // FileOptions to define file restrictions on an allocation for third-parties + // default 00000000 for all crud operations suggesting only owner has the below listed abilities. + // enabling option/s allows any third party to perform certain ops + // 00000001 - 1 - upload + // 00000010 - 2 - delete + // 00000100 - 4 - update + // 00001000 - 8 - move + // 00010000 - 16 - copy + // 00100000 - 32 - rename + ThirdPartyExtendable bool `json:"third_party_extendable"` numBlockDownloads int downloadChan chan *DownloadRequest @@ -223,6 +302,7 @@ type Allocation struct { allocationVersion int64 } +// OperationRequest represents an operation request with its related options. type OperationRequest struct { OperationType string LocalPath string @@ -246,9 +326,12 @@ type OperationRequest struct { CopyDirOnly bool } +// GetReadPriceRange returns the read price range from the global configuration. func GetReadPriceRange() (PriceRange, error) { return getPriceRange("max_read_price") } + +// GetWritePriceRange returns the write price range from the global configuration. func GetWritePriceRange() (PriceRange, error) { return getPriceRange("max_write_price") } @@ -262,8 +345,11 @@ func SetWasm() { BatchSize = 4 extraCount = 0 RepairBatchSize = 20 + RepairBlocks = 50 } +// SetCheckStatus sets the check status of the allocation. +// - checkStatus: the check status to set. func (a *Allocation) SetCheckStatus(checkStatus bool) { a.checkStatus = checkStatus } @@ -294,10 +380,12 @@ func getPriceRange(name string) (PriceRange, error) { } +// GetStats returns the statistics of the allocation. func (a *Allocation) GetStats() *AllocationStats { return a.Stats } +// GetBlobberStats returns the statistics of the blobbers in the allocation. func (a *Allocation) GetBlobberStats() map[string]*BlobberAllocationStats { numList := len(a.Blobbers) wg := &sync.WaitGroup{} @@ -321,6 +409,7 @@ func SetDownloadWorkerCount(count int) { downloadWorkerCount = count } +// InitAllocation initializes the allocation. func (a *Allocation) InitAllocation() { a.downloadChan = make(chan *DownloadRequest, 100) a.repairChan = make(chan *RepairRequest, 1) @@ -373,26 +462,32 @@ func (a *Allocation) dispatchWork(ctx context.Context) { } } +// CanUpload returns true if the allocation grants upload operation func (a *Allocation) CanUpload() bool { return (a.FileOptions & CanUploadMask) > 0 } +// CanDelete returns true if the allocation grants delete operation func (a *Allocation) CanDelete() bool { return (a.FileOptions & CanDeleteMask) > 0 } +// CanUpdate returns true if the allocation grants update operation func (a *Allocation) CanUpdate() bool { return (a.FileOptions & CanUpdateMask) > 0 } +// CanMove returns true if the allocation grants move operation func (a *Allocation) CanMove() bool { return (a.FileOptions & CanMoveMask) > 0 } +// CanCopy returns true if the allocation grants copy operation func (a *Allocation) CanCopy() bool { return (a.FileOptions & CanCopyMask) > 0 } +// CanRename returns true if the allocation grants rename operation func (a *Allocation) CanRename() bool { return (a.FileOptions & CanRenameMask) > 0 } @@ -411,6 +506,12 @@ func (a *Allocation) UploadFile(workdir, localpath string, remotepath string, return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false, "", false, false) } +// RepairFile repair a file in the allocation. +// - file: the file to repair. +// - remotepath: the remote path of the file. +// - statusCallback: a callback function to get the status of the repair. +// - mask: the mask of the repair descriping the blobbers to repair. +// - ref: the file reference, a representation of the file in the database. func (a *Allocation) RepairFile(file sys.File, remotepath string, statusCallback StatusCallback, mask zboxutil.Uint128, ref ORef) *OperationRequest { idr, _ := homedir.Dir() if Workdir != "" { @@ -430,13 +531,13 @@ func (a *Allocation) RepairFile(file sys.File, remotepath string, statusCallback WithEncrypt(true), WithStatusCallback(statusCallback), WithEncryptedPoint(ref.EncryptedKeyPoint), - WithChunkNumber(100), + WithChunkNumber(RepairBlocks), } } else { opts = []ChunkedUploadOption{ WithMask(mask), WithStatusCallback(statusCallback), - WithChunkNumber(100), + WithChunkNumber(RepairBlocks), } } op := &OperationRequest{ @@ -517,6 +618,22 @@ func (a *Allocation) EncryptAndUploadFileWithThumbnail( ) } +// StartMultiUpload starts a multi upload operation. +// A multi upload operation uploads multiple files to the allocation, given ordered arrays of upload parameters. +// The paramteres are ordered in a way that the ith element of each array corresponds to the ith file to upload. +// The upload operation is done in parallel. +// - workdir: the working directory, where the files are stored. +// - localPaths: the local paths of the files to upload. +// - fileNames: the names of the files to upload. +// - thumbnailPaths: the paths of the thumbnails of the files to upload. +// - encrypts: the encryption flags of the files to upload. +// - chunkNumbers: the chunk numbers of the files to upload. Chunk number is used to upload the file in chunks. +// - remotePaths: the remote paths of the files to upload. +// - isUpdate: the update flags of the files to upload. If true, the file is to overwrite an existing file. +// - isWebstreaming: the webstreaming flags of the files to upload. +// - status: the status callback function. Will be used to gather the status of the upload operations. +// +// Returns any error encountered during any of the upload operations, or during preparation of the upload operations. func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileNames []string, thumbnailPaths []string, encrypts []bool, chunkNumbers []int, remotePaths []string, isUpdate []bool, isWebstreaming []bool, status StatusCallback) error { if len(localPaths) != len(thumbnailPaths) { return errors.New("invalid_value", "length of localpaths and thumbnailpaths must be equal") @@ -621,6 +738,18 @@ func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileN return nil } +// StartChunkedUpload starts a chunked upload operation. +// A chunked upload operation uploads a file to the allocation in chunks. +// - workdir: the working directory, where the file is stored. +// - localPath: the local path of the file to upload. +// - remotePath: the remote path of the file to upload. +// - status: the status callback function. Will be used to gather the status of the upload operation. +// - isUpdate: the update flag of the file to upload. If true, the file is to overwrite an existing file. +// - isRepair: the repair flag of the file to upload. If true, the file is to repair an existing file. +// - thumbnailPath: the path of the thumbnail of the file to upload. +// - encryption: the encryption flag of the file to upload. +// - webStreaming: the webstreaming flag of the file to upload. +// - uploadOpts: the options of the upload operation as operation functions that customize the upload operation. func (a *Allocation) StartChunkedUpload(workdir, localPath string, remotePath string, status StatusCallback, @@ -705,6 +834,12 @@ func (a *Allocation) StartChunkedUpload(workdir, localPath string, return ChunkedUpload.Start() } +// GetCurrentVersion retrieves the current version of the allocation. +// The version of the allocation is the version of the latest write marker. +// The versions are gathered from the blobbers of the allocation. +// If the versions are not consistent, the allocation is repaired. +// Returns a boolean indicating if the allocation is repaired, and an error if any. +// In case of more than 2 versions found, an error is returned. func (a *Allocation) GetCurrentVersion() (bool, error) { //get versions from blobbers @@ -809,6 +944,12 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { return success, nil } +// RepairRequired checks if a repair is required for the given remotepath in the allocation. +// The repair is required if the file is not found in all the blobbers. +// Returns the found mask, delete mask, a boolean indicating if the repair is required, and an error if any. +// The found mask is a 128-bitmask of the blobbers where the file is found. +// The delete mask is a 128-bitmask of the blobbers where the file is not found. +// - remotepath: the remote path of the file to check. func (a *Allocation) RepairRequired(remotepath string) (zboxutil.Uint128, zboxutil.Uint128, bool, *fileref.FileRef, error) { if !a.isInitialized() { return zboxutil.Uint128{}, zboxutil.Uint128{}, false, nil, notInitialized @@ -836,6 +977,10 @@ func (a *Allocation) RepairRequired(remotepath string) (zboxutil.Uint128, zboxut return found, deleteMask, !found.Equals(uploadMask), fileRef, nil } +// DoMultiOperation performs multiple operations on the allocation. +// The operations are performed in parallel. +// - operations: the operations to perform. +// - opts: the options of the multi operation as operation functions that customize the multi operation. func (a *Allocation) DoMultiOperation(operations []OperationRequest, opts ...MultiOperationOption) error { if len(operations) == 0 { return nil @@ -989,6 +1134,8 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest, opts ...Mul return nil } +// GenerateParentPath generates the parent path of the given path. +// - path: the path to generate the parent path from. func GenerateParentPaths(path string) map[string]bool { path = strings.Trim(path, "/") parts := strings.Split(path, "/") @@ -1000,6 +1147,15 @@ func GenerateParentPaths(path string) map[string]bool { return parentPaths } +// DownloadFileToFileHandler adds a download operation a file to a file handler. +// Triggers the download operations if the added download operation is final. +// The file is downloaded from the allocation to the file handler. +// - fileHandler: the file handler to download the file to. +// - remotePath: the remote path of the file to download. +// - verifyDownload: a flag to verify the download. If true, the download should be verified against the client keys. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - isFinal: a flag to indicate if the download is the final download, meaning no more downloads are expected. It triggers the finalization of the download operation. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadFileToFileHandler( fileHandler sys.File, remotePath string, @@ -1012,6 +1168,18 @@ func (a *Allocation) DownloadFileToFileHandler( numBlockDownloads, verifyDownload, status, isFinal, "", downloadReqOpts...) } +// DownloadFileByBlockToFileHandler adds a download operation of a file by block to a file handler. +// Triggers the download operations if the added download operation is final. +// The file is downloaded from the allocation to the file handler in blocks. +// - fileHandler: the file handler to download the file to. +// - remotePath: the remote path of the file to download. +// - startBlock: the start block of the file to download. +// - endBlock: the end block of the file to download. +// - numBlocks: the number of blocks to download. +// - verifyDownload: a flag to verify the download. If true, the download should be verified against the client keys. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - isFinal: a flag to indicate if the download is the final download, meaning no more downloads are expected. It triggers the finalization of the download operation. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadByBlocksToFileHandler( fileHandler sys.File, remotePath string, @@ -1026,6 +1194,15 @@ func (a *Allocation) DownloadByBlocksToFileHandler( numBlocks, verifyDownload, status, isFinal, "", downloadReqOpts...) } +// DownloadThumbnailToFileHandler adds a download operation of a thumbnail to a file handler. +// Triggers the download operations if the added download operation is final. +// The thumbnail is downloaded from the allocation to the file handler. +// - fileHandler: the file handler to download the thumbnail to. +// - remotePath: the remote path of the thumbnail to download. +// - verifyDownload: a flag to verify the download. If true, the download should be verified against the client keys. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - isFinal: a flag to indicate if the download is the final download, meaning no more downloads are expected. It triggers the finalization of the download operation. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadThumbnailToFileHandler( fileHandler sys.File, remotePath string, @@ -1038,6 +1215,16 @@ func (a *Allocation) DownloadThumbnailToFileHandler( numBlockDownloads, verifyDownload, status, isFinal, "", downloadReqOpts...) } +// DownloadFile adds a download operation of a file from the allocation. +// Triggers the download operations if the added download operation is final. +// The file is downloaded from the allocation to the local path. +// - localPath: the local path to download the file to. +// - remotePath: the remote path of the file to download. +// - verifyDownload: a flag to verify the download. If true, the download should be verified against the client keys. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - isFinal: a flag to indicate if the download is the final download, meaning no more downloads are expected. It triggers the finalization of the download operation. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. + func (a *Allocation) DownloadFile(localPath string, remotePath string, verifyDownload bool, status StatusCallback, isFinal bool, downloadReqOpts ...DownloadRequestOption) error { f, localFilePath, toKeep, err := a.prepareAndOpenLocalFile(localPath, remotePath) if err != nil { @@ -1058,6 +1245,19 @@ func (a *Allocation) DownloadFile(localPath string, remotePath string, verifyDow return nil } +// DownloadFileByBlock adds a download operation of a file by block from the allocation. +// Triggers the download operations if the added download operation is final. +// The file is downloaded from the allocation to the local path in blocks. +// - localPath: the local path to download the file to. +// - remotePath: the remote path of the file to download. +// - startBlock: the start block of the file to download. +// - endBlock: the end block of the file to download. +// - numBlocks: the number of blocks to download. +// - verifyDownload: a flag to verify the download. If true, the download should be verified against the client keys. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - isFinal: a flag to indicate if the download is the final download, meaning no more downloads are expected. It triggers the finalization of the download operation. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. + // TODO: Use a map to store the download request and use flag isFinal to start the download, calculate readCount in parallel if possible func (a *Allocation) DownloadFileByBlock( localPath string, remotePath string, startBlock int64, endBlock int64, @@ -1081,6 +1281,14 @@ func (a *Allocation) DownloadFileByBlock( return nil } +// DownloadThumbnail adds a download operation of a thumbnail from the allocation. +// Triggers the download operations if the added download operation is final. +// The thumbnail is downloaded from the allocation to the local path. +// - localPath: the local path to download the thumbnail to. +// - remotePath: the remote path of the thumbnail to download. +// - verifyDownload: a flag to verify the download. If true, the download should be verified against the client keys. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - isFinal: a flag to indicate if the download is the final download, meaning no more downloads are expected. It triggers the finalization of the download operation. func (a *Allocation) DownloadThumbnail(localPath string, remotePath string, verifyDownload bool, status StatusCallback, isFinal bool) error { f, localFilePath, toKeep, err := a.prepareAndOpenLocalFile(localPath, remotePath) if err != nil { @@ -1330,6 +1538,12 @@ func (a *Allocation) prepareAndOpenLocalFile(localPath string, remotePath string return f, localFilePath, toKeep, nil } +// ListDirFromAuthTicket lists the allocation directory encoded in the given auth ticket. +// Usually used for directory sharing, the owner sets the directory as shared and generates an auth ticket which they should share with other non-owner users. +// The non-owner users can list the shared directory using the auth ticket. +// - authTicket: the auth ticket to list the directory. +// - lookupHash: the lookup hash of the directory to list. It's an augmentation of the allocation ID and the path hash. +// - opts: the options of the list request as operation functions that customize the list request. func (a *Allocation) ListDirFromAuthTicket(authTicket string, lookupHash string, opts ...ListRequestOptions) (*ListResult, error) { if !a.isInitialized() { return nil, notInitialized @@ -1371,6 +1585,9 @@ func (a *Allocation) ListDirFromAuthTicket(authTicket string, lookupHash string, return nil, errors.New("list_request_failed", "Failed to get list response from the blobbers") } +// ListDir lists the allocation directory. +// - path: the path of the directory to list. +// - opts: the options of the list request as operation functions that customize the list request. func (a *Allocation) ListDir(path string, opts ...ListRequestOptions) (*ListResult, error) { if !a.isInitialized() { return nil, notInitialized @@ -1458,6 +1675,12 @@ func (a *Allocation) getDownloadMaskForBlobber(blobberID string) (zboxutil.Uint1 return x, a.Blobbers[blobberIdx : blobberIdx+1], nil } +// DownloadFromBlobber downloads a file from a specific blobber. +// - blobberID: the ID of the blobber to download the file from. +// - localPath: the local path to download the file to. +// - remotePath: the remote path of the file to download. +// - status: the status callback function. Will be used to gather the status of the download operation. +// - opts: the options of the download request as operation functions that customize the download request. func (a *Allocation) DownloadFromBlobber(blobberID, localPath, remotePath string, status StatusCallback, opts ...DownloadRequestOption) error { mask, blobbers, err := a.getDownloadMaskForBlobber(blobberID) @@ -1508,7 +1731,18 @@ func (a *Allocation) DownloadFromBlobber(blobberID, localPath, remotePath string return nil } -// GetRefsWithAuthTicket get refs that are children of shared remote path. +// GetRefsWithAuthTicket retrieve file refs that are children of a shared remote path. +// Refs are the representations of files and directories in the blobber database. +// An auth ticket is provided in case the path is shared, and usually by a non-owner user. +// This function will retrieve paginated objectTree and will handle concensus; Required tree should be made in application side. +// - authToken: the auth ticket to get the refs. +// - offsetPath: the offset path to get the refs. +// - updatedDate: the updated date to get the refs. +// - offsetDate: the offset date to get the refs. +// - fileType: the file type to get the refs. +// - refType: the ref type to get the refs, e.g., file or directory. +// - level: the level of the refs to get relative to the path root (strating from 0 as the root path). +// - pageLimit: the limit of the refs to get per page. func (a *Allocation) GetRefsWithAuthTicket(authToken, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int) (*ObjectTreeResult, error) { if authToken == "" { return nil, errors.New("empty_auth_token", "auth token cannot be empty") @@ -1527,7 +1761,17 @@ func (a *Allocation) GetRefsWithAuthTicket(authToken, offsetPath, updatedDate, o return a.getRefs("", authTicket.FilePathHash, string(at), offsetPath, updatedDate, offsetDate, fileType, refType, level, pageLimit) } +// GetRefs retrieve file refs that are children of a remote path. +// Used by the owner to get the refs of the files and directories in the allocation. // This function will retrieve paginated objectTree and will handle concensus; Required tree should be made in application side. +// - path: the path to get the refs. +// - offsetPath: the offset path to get the refs. +// - updatedDate: the updated date to get the refs. +// - offsetDate: the offset date to get the refs. +// - fileType: the file type to get the refs. +// - refType: the ref type to get the refs, e.g., file or directory. +// - level: the level of the refs to get relative to the path root (strating from 0 as the root path). +// - pageLimit: the limit of the refs to get per page. func (a *Allocation) GetRefs(path, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int, opts ...ObjectTreeRequestOption) (*ObjectTreeResult, error) { if len(path) == 0 || !zboxutil.IsRemoteAbs(path) { return nil, errors.New("invalid_path", fmt.Sprintf("Absolute path required. Path provided: %v", path)) @@ -1545,6 +1789,12 @@ func (a *Allocation) GetRefsFromLookupHash(pathHash, offsetPath, updatedDate, of } +// GetRecentlyAddedRefs retrieves the recently added refs in the allocation. +// The refs are the representations of files and directories in the blobber database. +// This function will retrieve paginated objectTree and will handle concensus; Required tree should be made in application side. +// - page: the page number of the refs to get. +// - fromDate: the date to get the refs from. +// - pageLimit: the limit of the refs to get per page. func (a *Allocation) GetRecentlyAddedRefs(page int, fromDate int64, pageLimit int) (*RecentlyAddedRefResult, error) { if !a.isInitialized() { return nil, notInitialized @@ -1575,6 +1825,9 @@ func (a *Allocation) GetRecentlyAddedRefs(page int, fromDate int64, pageLimit in return req.GetRecentlyAddedRefs() } +// GetFileMeta retrieves the file meta data of a file in the allocation. +// The file meta data includes the file type, name, hash, lookup hash, mime type, path, size, number of blocks, encrypted key, collaborators, actual file size, actual thumbnail hash, and actual thumbnail size. +// - path: the path of the file to get the meta data. func (a *Allocation) GetFileMeta(path string) (*ConsolidatedFileMeta, error) { if !a.isInitialized() { return nil, notInitialized @@ -1612,6 +1865,60 @@ func (a *Allocation) GetFileMeta(path string) (*ConsolidatedFileMeta, error) { return nil, errors.New("file_meta_error", "Error getting the file meta data from blobbers") } +// GetFileMetaByName retrieve consolidated file metadata given its name (its full path starting from root "/"). +// - fileName: full file path starting from the allocation root. +func (a *Allocation) GetFileMetaByName(fileName string) ([]*ConsolidatedFileMetaByName, error) { + if !a.isInitialized() { + return nil, notInitialized + } + + resultArr := []*ConsolidatedFileMetaByName{} + listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} + listReq.allocationID = a.ID + listReq.allocationTx = a.Tx + listReq.blobbers = a.Blobbers + listReq.fullconsensus = a.fullconsensus + listReq.consensusThresh = a.consensusThreshold + listReq.ctx = a.ctx + listReq.filename = fileName + _, _, refs, _ := listReq.getMultipleFileConsensusFromBlobbers() + if len(refs) != 0 { + for _, ref := range refs { + result := &ConsolidatedFileMetaByName{} + if ref != nil { + result.Type = ref.Type + result.Name = ref.Name + result.Hash = ref.ActualFileHash + result.LookupHash = ref.LookupHash + result.MimeType = ref.MimeType + result.Path = ref.Path + result.Size = ref.Size + result.NumBlocks = ref.NumBlocks + result.EncryptedKey = ref.EncryptedKey + result.Collaborators = ref.Collaborators + result.ActualFileSize = ref.ActualFileSize + result.ActualThumbnailHash = ref.ActualThumbnailHash + result.ActualThumbnailSize = ref.ActualThumbnailSize + result.FileMetaHash = ref.FileMetaHash + result.ThumbnailHash = ref.ThumbnailHash + result.CreatedAt = ref.CreatedAt + result.UpdatedAt = ref.UpdatedAt + if result.ActualFileSize > 0 { + result.ActualNumBlocks = (ref.ActualFileSize + CHUNK_SIZE - 1) / CHUNK_SIZE + } + } + resultArr = append(resultArr, result) + } + return resultArr, nil + } + return nil, errors.New("file_meta_error", "Error getting the file meta data from blobbers") +} + +// GetChunkReadSize returns the size of the chunk to read. +// The size of the chunk to read is calculated based on the data shards and the encryption flag. +// If the encryption flag is true, the size of the chunk to read is the chunk size minus the encrypted data padding size and the encryption header size. +// Otherwise, the size of the chunk to read is the chunk size multiplied by the data shards. +// - encrypt: the flag to indicate if the chunk is encrypted. func (a *Allocation) GetChunkReadSize(encrypt bool) int64 { chunkDataSize := int64(DefaultChunkSize) if encrypt { @@ -1620,6 +1927,12 @@ func (a *Allocation) GetChunkReadSize(encrypt bool) int64 { return chunkDataSize * int64(a.DataShards) } +// GetFileMetaFromAuthTicket retrieves the file meta data of a file in the allocation using the auth ticket. +// The file meta data includes the file type, name, hash, lookup hash, mime type, path, size, number of blocks, actual file size, actual thumbnail hash, and actual thumbnail size. +// The auth ticket is used to access the file meta data of a shared file. +// Usually used for file sharing, the owner sets the file as shared and generates an auth ticket which they should share with other non-owner users. +// - authTicket: the auth ticket to get the file meta data. +// - lookupHash: the lookup hash of the file to get the meta data. It's an augmentation of the allocation ID and the path hash. func (a *Allocation) GetFileMetaFromAuthTicket(authTicket string, lookupHash string) (*ConsolidatedFileMeta, error) { if !a.isInitialized() { return nil, notInitialized @@ -1669,6 +1982,9 @@ func (a *Allocation) GetFileMetaFromAuthTicket(authTicket string, lookupHash str return nil, errors.New("file_meta_error", "Error getting the file meta data from blobbers") } +// GetFileStats retrieves the file stats of a file in the allocation. +// The file stats include the number of blocks, size, and actual file size. +// - path: the path of the file to get the stats. func (a *Allocation) GetFileStats(path string) (map[string]*FileStats, error) { if !a.isInitialized() { return nil, notInitialized @@ -1696,6 +2012,9 @@ func (a *Allocation) GetFileStats(path string) (map[string]*FileStats, error) { return nil, errors.New("file_stats_request_failed", "Failed to get file stats response from the blobbers") } +// DeleteFile deletes a file from the allocation. +// The file is deleted from the allocation and the blobbers. +// - path: the path of the file to delete. func (a *Allocation) DeleteFile(path string) error { return a.deleteFile(path, a.consensusThreshold, a.fullconsensus, zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1)) } @@ -1773,6 +2092,19 @@ func (a *Allocation) createDir(remotePath string, threshConsensus, fullConsensus return err } +// GetAuthTicketForShare returns the authentication ticket for sharing a file or directory within the allocation. +// It generates an authentication ticket using the provided parameters and the current time. +// The authentication ticket can be used by the recipient to access the shared file or directory. +// +// Parameters: +// - path: The path of the file or directory to be shared. +// - filename: The name of the file to be shared. +// - referenceType: The type of reference for the shared file or directory. +// - refereeClientID: The client ID of the recipient who will be granted access to the shared file or directory. +// +// Returns: +// - string: The authentication ticket for sharing the file or directory. +// - error: An error if the authentication ticket generation fails. func (a *Allocation) GetAuthTicketForShare( path, filename, referenceType, refereeClientID string) (string, error) { @@ -1780,6 +2112,15 @@ func (a *Allocation) GetAuthTicketForShare( return a.GetAuthTicket(path, filename, referenceType, refereeClientID, "", 0, &now) } +// RevokeShare revokes the shared access to a file or directory within the allocation. +// It revokes the shared access to the file or directory for the specified recipient. +// +// Parameters: +// - path: The path of the file or directory to revoke the shared access. +// - refereeClientID: The client ID of the recipient whose shared access is to be revoked. +// +// Returns: +// - error: An error if the shared access revocation fails. func (a *Allocation) RevokeShare(path string, refereeClientID string) error { success := make(chan int, len(a.Blobbers)) notFound := make(chan int, len(a.Blobbers)) @@ -1841,6 +2182,18 @@ func (a *Allocation) RevokeShare(path string, refereeClientID string) error { var ErrInvalidPrivateShare = errors.New("invalid_private_share", "private sharing is only available for encrypted file") +// GetAuthTicket generates an authentication ticket for the specified file or directory in the allocation. +// The authentication ticket is used to grant access to the file or directory to another client. +// The function takes the following parameters: +// - path: The path of the file or directory (should be absolute). +// - filename: The name of the file. +// - referenceType: The type of reference (file or directory). +// - refereeClientID: The client ID of the referee. +// - refereeEncryptionPublicKey: The encryption public key of the referee. +// - expiration: The expiration time of the authentication ticket in Unix timestamp format. +// - availableAfter: The time after which the authentication ticket becomes available in Unix timestamp format. +// +// Returns the authentication ticket as a base64-encoded string and an error if any. func (a *Allocation) GetAuthTicket(path, filename string, referenceType, refereeClientID, refereeEncryptionPublicKey string, expiration int64, availableAfter *time.Time) (string, error) { @@ -1913,6 +2266,11 @@ func (a *Allocation) GetAuthTicket(path, filename string, return base64.StdEncoding.EncodeToString(atBytes), nil } +// UploadAuthTicketToBlobber uploads the authentication ticket to the blobbers after creating it at the client side. +// The authentication ticket is uploaded to the blobbers to grant access to the file or directory to a client other than the owner. +// - authTicket: The authentication ticket to upload. +// - clientEncPubKey: The encryption public key of the client, used in case of private sharing. +// - availableAfter: The time after which the authentication ticket becomes available in Unix timestamp format. func (a *Allocation) UploadAuthTicketToBlobber(authTicket string, clientEncPubKey string, availableAfter *time.Time) error { success := make(chan int, len(a.Blobbers)) wg := &sync.WaitGroup{} @@ -1980,6 +2338,9 @@ func (a *Allocation) UploadAuthTicketToBlobber(authTicket string, clientEncPubKe return nil } +// CancelDownload cancels the download operation for the specified remote path. +// It cancels the download operation and removes the download request from the download progress map. +// - remotepath: The remote path of the file to cancel the download operation. func (a *Allocation) CancelDownload(remotepath string) error { if downloadReq, ok := a.downloadProgressMap[remotepath]; ok { downloadReq.isDownloadCanceled = true @@ -1989,6 +2350,8 @@ func (a *Allocation) CancelDownload(remotepath string) error { return errors.New("remote_path_not_found", "Invalid path. No download in progress for the path "+remotepath) } +// DownloadFromReader downloads a file from the allocation to the specified local path using the provided reader. +// [DEPRECATED] Use DownloadFile or DownloadFromAuthTicket instead. func (a *Allocation) DownloadFromReader( remotePath, localPath, lookupHash, authTicket, contentMode string, verifyDownload bool, @@ -2055,8 +2418,9 @@ func (a *Allocation) DownloadFromReader( return nil } -// GetStreamDownloader will check file ref existence and returns an instance that provides -// io.ReadSeekerCloser interface +// GetAllocationFileReader will check file ref existence and returns an instance that provides +// io.ReadSeekerCloser interface. +// [DEPRECATED] Use DownloadFile or DownloadFromAuthTicket instead. func (a *Allocation) GetAllocationFileReader( remotePath, lookupHash, authTicket, contentMode string, verifyDownload bool, @@ -2107,6 +2471,22 @@ func (a *Allocation) GetAllocationFileReader( return GetDStorageFileReader(a, ref, sdo) } +// DownloadFileToFileHandlerFromAuthTicket adds a download operation of a file from the allocation to the specified file handler +// using the provided authentication ticket. +// Triggers the downaload operations if this download request is the final one. +// +// Parameters: +// - fileHandler: The file handler to write the downloaded file to. +// - authTicket: The authentication ticket for accessing the allocation. +// - remoteLookupHash: The lookup hash of the remote file. +// - remoteFilename: The name of the remote file. +// - verifyDownload: A boolean indicating whether to verify the downloaded file. +// - status: A callback function to receive status updates during the download. +// - isFinal: A boolean indicating whether this is the final download request. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. +// +// Returns: +// - An error if the download fails, nil otherwise. func (a *Allocation) DownloadFileToFileHandlerFromAuthTicket( fileHandler sys.File, authTicket string, @@ -2121,6 +2501,22 @@ func (a *Allocation) DownloadFileToFileHandlerFromAuthTicket( remoteFilename, DOWNLOAD_CONTENT_FULL, verifyDownload, status, isFinal, "", downloadReqOpts...) } +// DownloadByBlocksToFileHandlerFromAuthTicket adds a download operation of a file from the allocation to the specified file handler +// using the provided authentication ticket. +// Triggers the downaload operations if this download request is the final one. +// +// Parameters: +// - fileHandler: The file handler to write the downloaded file to. +// - authTicket: The authentication ticket for accessing the allocation. +// - remoteLookupHash: The lookup hash of the remote file. +// - startBlock: The starting block number to download. +// - endBlock: The ending block number to download. +// - numBlocks: The number of blocks to download. +// - remoteFilename: The name of the remote file. +// - verifyDownload: A boolean indicating whether to verify the downloaded file. +// - status: A callback function to receive status updates during the download. +// - isFinal: A boolean indicating whether this is the final download request. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadByBlocksToFileHandlerFromAuthTicket( fileHandler sys.File, authTicket string, @@ -2137,6 +2533,18 @@ func (a *Allocation) DownloadByBlocksToFileHandlerFromAuthTicket( remoteFilename, DOWNLOAD_CONTENT_FULL, verifyDownload, status, isFinal, "", downloadReqOpts...) } +// DownloadThumbnailToFileHandlerFromAuthTicket adds a download operation of a thumbnail from the allocation to the specified file handler +// using the provided authentication ticket. +// Triggers the downaload operations if this download request is the final one. +// +// Parameters: +// - fileHandler: The file handler to write the downloaded thumbnail to. +// - authTicket: The authentication ticket for accessing the allocation. +// - remoteLookupHash: The lookup hash of the remote file. +// - remoteFilename: The name of the remote file. +// - verifyDownload: A boolean indicating whether to verify the downloaded thumbnail. +// - status: A callback function to receive status updates during the download. +// - isFinal: A boolean indicating whether this is the final download request. func (a *Allocation) DownloadThumbnailToFileHandlerFromAuthTicket( fileHandler sys.File, authTicket string, @@ -2150,6 +2558,18 @@ func (a *Allocation) DownloadThumbnailToFileHandlerFromAuthTicket( remoteFilename, DOWNLOAD_CONTENT_THUMB, verifyDownload, status, isFinal, "") } +// DownloadThumbnailFromAuthTicket downloads a thumbnail from the allocation to the specified local path using the provided authentication ticket. +// Triggers the downaload operations if this download request is the final one. +// +// Parameters: +// - localPath: The local path to save the downloaded thumbnail. +// - authTicket: The authentication ticket for accessing the allocation. +// - remoteLookupHash: The lookup hash of the remote file. +// - remoteFilename: The name of the remote file. +// - verifyDownload: A boolean indicating whether to verify the downloaded thumbnail. +// - status: A callback function to receive status updates during the download. +// - isFinal: A boolean indicating whether this is the final download request. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadThumbnailFromAuthTicket( localPath string, authTicket string, @@ -2179,6 +2599,18 @@ func (a *Allocation) DownloadThumbnailFromAuthTicket( return nil } +// DownloadFromAuthTicket downloads a file from the allocation to the specified local path using the provided authentication ticket. +// Triggers the downaload operations if this download request is the final one. +// +// Parameters: +// - localPath: The local path to save the downloaded file. +// - authTicket: The authentication ticket for accessing the allocation. +// - remoteLookupHash: The lookup hash of the remote file. +// - remoteFilename: The name of the remote file. +// - verifyDownload: A boolean indicating whether to verify the downloaded file. +// - status: A callback function to receive status updates during the download. +// - isFinal: A boolean indicating whether this is the final download request. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadFromAuthTicket(localPath string, authTicket string, remoteLookupHash string, remoteFilename string, verifyDownload bool, status StatusCallback, isFinal bool, downloadReqOpts ...DownloadRequestOption) error { f, localFilePath, toKeep, err := a.prepareAndOpenLocalFile(localPath, remoteFilename) @@ -2200,6 +2632,22 @@ func (a *Allocation) DownloadFromAuthTicket(localPath string, authTicket string, return nil } +// DownloadFromAuthTicketByBlocks downloads a file from the allocation to the specified local path using the provided authentication ticket. +// The file is downloaded by blocks from the specified start block to the end block. +// Triggers the downaload operations if this download request is the final one. +// +// Parameters: +// - localPath: The local path to save the downloaded file. +// - authTicket: The authentication ticket for accessing the allocation. +// - startBlock: The starting block number to download. +// - endBlock: The ending block number to download. +// - numBlocks: The number of blocks to download. +// - remoteLookupHash: The lookup hash of the remote file. +// - remoteFilename: The name of the remote file. +// - verifyDownload: A boolean indicating whether to verify the downloaded file. +// - status: A callback function to receive status updates during the download. +// - isFinal: A boolean indicating whether this is the final download request. +// - downloadReqOpts: the options of the download operation as operation functions that customize the download operation. func (a *Allocation) DownloadFromAuthTicketByBlocks(localPath string, authTicket string, startBlock int64, endBlock int64, numBlocks int, remoteLookupHash string, remoteFilename string, verifyDownload bool, @@ -2301,6 +2749,12 @@ func (a *Allocation) downloadFromAuthTicket(fileHandler sys.File, authTicket str return nil } +// StartRepair starts the repair operation for the specified path in the allocation. +// It starts the repair operation and returns an error if the path is not found. +// Repair operation is used to repair the files in the allocation, which are corrupted or missing in some blobbers. +// - localRootPath: The local root path to repair the files. +// - pathToRepair: The path to repair in the allocation. +// - statusCB: A callback function to receive status updates during the repair operation. func (a *Allocation) StartRepair(localRootPath, pathToRepair string, statusCB StatusCallback) error { if !a.isInitialized() { return notInitialized @@ -2351,7 +2805,8 @@ func (a *Allocation) RepairAlloc(statusCB StatusCallback) (err error) { return a.StartRepair(dir, "/", statusCB) } -// Gets the size in bytes to repair allocation +// RepairSize Gets the size in bytes to repair allocation +// - remotePath: the path to repair in the allocation. func (a *Allocation) RepairSize(remotePath string) (RepairSize, error) { if !a.isInitialized() { return RepairSize{}, notInitialized @@ -2371,6 +2826,9 @@ func (a *Allocation) RepairSize(remotePath string) (RepairSize, error) { return repairReq.Size(context.Background(), dir) } +// CancelUpload cancels the upload operation for the specified remote path. +// It cancels the upload operation and returns an error if the remote path is not found. +// - remotePath: The remote path to cancel the upload operation. func (a *Allocation) CancelUpload(remotePath string) error { cancelLock.Lock() cancelFunc, ok := CancelOpCtx[remotePath] @@ -2383,6 +2841,9 @@ func (a *Allocation) CancelUpload(remotePath string) error { return nil } +// PauseUpload pauses the upload operation for the specified remote path. +// It pauses the upload operation and returns an error if the remote path is not found. +// - remotePath: The remote path to pause the upload operation. func (a *Allocation) PauseUpload(remotePath string) error { cancelLock.Lock() cancelFunc, ok := CancelOpCtx[remotePath] @@ -2397,6 +2858,8 @@ func (a *Allocation) PauseUpload(remotePath string) error { return nil } +// CancelRepair cancels the repair operation for the allocation. +// It cancels the repair operation and returns an error if no repair is in progress for the allocation. func (a *Allocation) CancelRepair() error { if a.repairRequestInProgress != nil { a.repairRequestInProgress.isRepairCanceled = true @@ -2435,10 +2898,12 @@ func (a *Allocation) GetMaxWriteReadFromBlobbers(blobbers []*BlobberAllocation) return maxWritePrice, maxReadPrice, nil } +// GetMaxWriteRead returns the maximum write and read prices from the blobbers in the allocation. func (a *Allocation) GetMaxWriteRead() (maxW float64, maxR float64, err error) { return a.GetMaxWriteReadFromBlobbers(a.BlobberDetails) } +// GetMinWriteRead returns the minimum write and read prices from the blobbers in the allocation. func (a *Allocation) GetMinWriteRead() (minW float64, minR float64, err error) { if !a.isInitialized() { return 0, 0, notInitialized @@ -2470,6 +2935,9 @@ func (a *Allocation) GetMinWriteRead() (minW float64, minR float64, err error) { return minWritePrice, minReadPrice, nil } +// GetMaxStorageCostFromBlobbers returns the maximum storage cost from a given list of allocation blobbers. +// - size: The size of the file to calculate the storage cost. +// - blobbers: The list of blobbers to calculate the storage cost. func (a *Allocation) GetMaxStorageCostFromBlobbers(size int64, blobbers []*BlobberAllocation) (float64, error) { var cost common.Balance // total price for size / duration @@ -2485,6 +2953,8 @@ func (a *Allocation) GetMaxStorageCostFromBlobbers(size int64, blobbers []*Blobb return cost.ToToken() } +// GetMaxStorageCost returns the maximum storage cost from the blobbers in the allocation. +// - size: The size of the file to calculate the storage cost. func (a *Allocation) GetMaxStorageCost(size int64) (float64, error) { var cost common.Balance // total price for size / duration @@ -2503,6 +2973,8 @@ func (a *Allocation) GetMaxStorageCost(size int64) (float64, error) { return cost.ToToken() } +// GetMinStorageCost returns the minimum storage cost from the blobbers in the allocation. +// - size: The size of the file to calculate the storage cost. func (a *Allocation) GetMinStorageCost(size int64) (common.Balance, error) { minW, _, err := a.GetMinWriteRead() if err != nil { @@ -2545,6 +3017,17 @@ func (a *Allocation) SetConsensusThreshold() { a.consensusThreshold = a.DataShards } +// UpdateWithRepair updates the allocation with the specified parameters and starts the repair operation if required. +// It updates the allocation with the specified parameters and starts the repair operation if required. +// - size: The updated size of the allocation to update. +// - extend: A boolean indicating whether to extend the expiration of the allocation. +// - lock: The lock value to update the allocation. +// - addBlobberId: The blobber ID to add to the allocation. +// - addBlobberAuthTicket: The authentication ticket for the blobber to add to the allocation. +// - removeBlobberId: The blobber ID to remove from the allocation. +// - setThirdPartyExtendable: A boolean indicating whether to set the allocation as third-party extendable. If set to true, the allocation can be extended in terms of size by a non-owner. +// - 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, extend bool, @@ -2567,6 +3050,19 @@ func (a *Allocation) UpdateWithRepair( return hash, nil } +// UpdateWithStatus updates the allocation with the specified parameters. +// It updates the allocation with the specified parameters and returns the updated allocation, hash, and a boolean indicating whether repair is required. +// - size: The updated size of the allocation to update. +// - extend: A boolean indicating whether to extend the expiration of the allocation. +// - lock: The lock value to update the allocation. +// - addBlobberId: The blobber ID to add to the allocation. +// - addBlobberAuthTicket: The authentication ticket for the blobber to add to the allocation. Used in case of adding a restricted blobber. +// - removeBlobberId: The blobber ID to remove from the allocation. +// - setThirdPartyExtendable: A boolean indicating whether to set the allocation as third-party extendable. If set to true, the allocation can be extended in terms of size by a non-owner. +// - 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. +// +// Returns the updated allocation, hash, and a boolean indicating whether repair is required. func (a *Allocation) UpdateWithStatus( size int64, extend bool, diff --git a/zboxcore/sdk/authticket.go b/zboxcore/sdk/authticket.go index b1cb4304c..40a71ccb2 100644 --- a/zboxcore/sdk/authticket.go +++ b/zboxcore/sdk/authticket.go @@ -13,6 +13,8 @@ type AuthTicket struct { b64Ticket string } +// InitAuthTicket initialize auth ticket instance +// - authTicket: base64 encoded auth ticket func InitAuthTicket(authTicket string) *AuthTicket { at := &AuthTicket{} at.b64Ticket = authTicket diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 2798b851b..c1d1496d8 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -368,10 +368,10 @@ func (su *ChunkedUpload) removeProgress() { } } -func (su *ChunkedUpload) updateProgress(chunkIndex int) { +func (su *ChunkedUpload) updateProgress(chunkIndex int, upMask zboxutil.Uint128) { if su.progressStorer != nil { if chunkIndex > su.progress.ChunkIndex { - su.progressStorer.Update(su.progress.ID, chunkIndex) + su.progressStorer.Update(su.progress.ID, chunkIndex, upMask) } } } @@ -728,7 +728,7 @@ func (su *ChunkedUpload) uploadToBlobbers(uploadData UploadData) error { if uploadData.uploadLength > 0 { index := uploadData.chunkEndIndex uploadLength := uploadData.uploadLength - go su.updateProgress(index) + go su.updateProgress(index, su.uploadMask) if su.statusCallback != nil { su.statusCallback.InProgress(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(atomic.AddInt64(&su.progress.UploadLength, uploadLength)), nil) } diff --git a/zboxcore/sdk/chunked_upload_bench_test.go b/zboxcore/sdk/chunked_upload_bench_test.go index bb0e67329..19ec6c6b3 100644 --- a/zboxcore/sdk/chunked_upload_bench_test.go +++ b/zboxcore/sdk/chunked_upload_bench_test.go @@ -31,7 +31,7 @@ func (nope *nopeChunkedUploadProgressStorer) Remove(id string) error { return nil } -func (nope *nopeChunkedUploadProgressStorer) Update(id string, chunkIndex int) { +func (nope *nopeChunkedUploadProgressStorer) Update(id string, chunkIndex int, upMask zboxutil.Uint128) { } func generateRandomBytes(n int64) []byte { diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index 6023efa1a..998c1ef05 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -9,10 +9,14 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/zboxcore/encryption" + "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" + "github.com/valyala/bytebufferpool" ) +var uploadPool bytebufferpool.Pool + type ChunkedUploadChunkReader interface { // Next read, encode and encrypt next chunk Next() (*ChunkData, error) @@ -52,7 +56,7 @@ type chunkedUploadChunkReader struct { totalChunkDataSizePerRead int64 //fileShardsDataBuffer - fileShardsDataBuffer []byte + fileShardsDataBuffer *bytebufferpool.ByteBuffer //offset offset int64 @@ -128,7 +132,14 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards, chunkNum := (size + r.chunkDataSizePerRead - 1) / r.chunkDataSizePerRead totalDataSize = r.totalChunkDataSizePerRead * chunkNum } - r.fileShardsDataBuffer = make([]byte, 0, totalDataSize) + buf := uploadPool.Get() + if cap(buf.B) < int(totalDataSize) { + buf.B = make([]byte, 0, totalDataSize) + logger.Logger.Debug("creating buffer with size: ", " totalDataSize: ", totalDataSize) + } else { + logger.Logger.Debug("reusing buffer with size: ", cap(buf.B), " totalDataSize: ", totalDataSize, " len: ", len(buf.B)) + } + r.fileShardsDataBuffer = buf if CurrentMode == UploadModeHigh { r.hasherWG.Add(1) go r.hashData() @@ -172,7 +183,7 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { ReadSize: 0, FragmentSize: 0, } - chunkBytes := r.fileShardsDataBuffer[r.offset : r.offset+r.chunkDataSizePerRead : r.offset+r.totalChunkDataSizePerRead] + chunkBytes := r.fileShardsDataBuffer.B[r.offset : r.offset+r.chunkDataSizePerRead : r.offset+r.totalChunkDataSizePerRead] var ( readLen int err error @@ -296,8 +307,10 @@ func (r *chunkedUploadChunkReader) Close() { r.closeOnce.Do(func() { close(r.hasherDataChan) r.hasherWG.Wait() + uploadPool.Put(r.fileShardsDataBuffer) + r.fileShardsDataBuffer = nil }) - r.fileShardsDataBuffer = nil + } func (r *chunkedUploadChunkReader) GetFileHash() (string, error) { diff --git a/zboxcore/sdk/chunked_upload_hasher.go b/zboxcore/sdk/chunked_upload_hasher.go index e58da0220..9a0c96f99 100644 --- a/zboxcore/sdk/chunked_upload_hasher.go +++ b/zboxcore/sdk/chunked_upload_hasher.go @@ -11,6 +11,8 @@ import ( "github.com/0chain/gosdk/core/util" ) +// Hasher interface to gather all hasher related functions. +// A hasher is used to calculate the hash of a file, fixed merkle tree, and validation merkle tree. type Hasher interface { // GetFileHash get file hash GetFileHash() (string, error) diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index ec6788353..1d0b78c81 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -189,7 +189,8 @@ type UploadProgress struct { // UploadLength total bytes that has been uploaded to blobbers UploadLength int64 `json:"-"` // ReadLength total bytes that has been read from original reader (un-encoded, un-encrypted) - ReadLength int64 `json:"-"` + ReadLength int64 `json:"-"` + UploadMask zboxutil.Uint128 `json:"upload_mask"` Blobbers []*UploadBlobberStatus `json:"-"` } diff --git a/zboxcore/sdk/chunked_upload_option.go b/zboxcore/sdk/chunked_upload_option.go index a6396a1ee..38eddf491 100644 --- a/zboxcore/sdk/chunked_upload_option.go +++ b/zboxcore/sdk/chunked_upload_option.go @@ -11,7 +11,7 @@ import ( "github.com/klauspost/reedsolomon" ) -// ChunkedUploadOption set stream option +// ChunkedUploadOption Generic type for chunked upload option functions type ChunkedUploadOption func(su *ChunkedUpload) // WithThumbnail add thumbnail. stream mode is unnecessary for thumbnail @@ -37,7 +37,8 @@ func WithThumbnail(buf []byte) ChunkedUploadOption { } } -// WithThumbnailFile add thumbnail from file. stream mode is unnecessary for thumbnail +// WithThumbnailFile add thumbnail from file. stream mode is unnecessary for thumbnail. +// - fileName: file name of the thumbnail, which will be read and uploaded func WithThumbnailFile(fileName string) ChunkedUploadOption { buf, _ := os.ReadFile(fileName) @@ -46,6 +47,7 @@ func WithThumbnailFile(fileName string) ChunkedUploadOption { } // WithChunkNumber set the number of chunks should be upload in a request. ignore if size <=0 +// - num: number of chunks func WithChunkNumber(num int) ChunkedUploadOption { return func(su *ChunkedUpload) { if num > 0 { @@ -55,55 +57,64 @@ func WithChunkNumber(num int) ChunkedUploadOption { } // WithEncrypt turn on/off encrypt on upload. It is turn off as default. +// - on: true to turn on, false to turn off func WithEncrypt(on bool) ChunkedUploadOption { return func(su *ChunkedUpload) { su.encryptOnUpload = on } } -// WithStatusCallback register StatusCallback instance +// WithStatusCallback return a wrapper option function to set status callback of the chunked upload instance, which is used to track upload progress +// - callback: StatusCallback instance func WithStatusCallback(callback StatusCallback) ChunkedUploadOption { return func(su *ChunkedUpload) { su.statusCallback = callback } } +// WithProgressCallback return a wrapper option function to set progress callback of the chunked upload instance func WithProgressStorer(progressStorer ChunkedUploadProgressStorer) ChunkedUploadOption { return func(su *ChunkedUpload) { su.progressStorer = progressStorer } } +// WithUploadTimeout return a wrapper option function to set upload timeout of the chunked upload instance func WithUploadTimeout(t time.Duration) ChunkedUploadOption { return func(su *ChunkedUpload) { su.uploadTimeOut = t } } +// WithCommitTimeout return a wrapper option function to set commit timeout of the chunked upload instance func WithCommitTimeout(t time.Duration) ChunkedUploadOption { return func(su *ChunkedUpload) { su.commitTimeOut = t } } +// WithUploadMask return a wrapper option function to set upload mask of the chunked upload instance func WithMask(mask zboxutil.Uint128) ChunkedUploadOption { return func(su *ChunkedUpload) { su.uploadMask = mask } } +// WithEncryptedKeyPoint return a wrapper option function to set encrypted key point of the chunked upload instance func WithEncryptedPoint(point string) ChunkedUploadOption { return func(su *ChunkedUpload) { su.encryptedKeyPoint = point } } +// WithActualHash return a wrapper option function to set actual hash of the chunked upload instance func WithActualHash(hash string) ChunkedUploadOption { return func(su *ChunkedUpload) { su.fileMeta.ActualHash = hash } } +// WithActualSize return a wrapper option function to set the file hasher used in the chunked upload instance func WithFileHasher(h Hasher) ChunkedUploadOption { return func(su *ChunkedUpload) { su.fileHasher = h diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index 3ddeb90f4..5bd99a95d 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -156,7 +156,17 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, } obj := js.Global().Get("Object").New() obj.Set("fileMeta", fileMetaUint8) - obj.Set("formInfo", formInfoUint8) + if formInfo.OnlyHash && su.progress.UploadMask.And(zboxutil.NewUint128(1).Lsh(pos)).Equals64(0) { + //check if pos is set in upload mask in progress + formInfo.OnlyHash = false + noHashFormInfoJSON, _ := json.Marshal(formInfo) + noHashFormInfoUint8 := js.Global().Get("Uint8Array").New(len(noHashFormInfoJSON)) + js.CopyBytesToJS(noHashFormInfoUint8, noHashFormInfoJSON) + obj.Set("formInfo", noHashFormInfoUint8) + formInfo.OnlyHash = true //reset to true + } else { + obj.Set("formInfo", formInfoUint8) + } if len(thumbnailChunkData) > 0 { thumbnailChunkDataUint8 := js.Global().Get("Uint8Array").New(len(thumbnailChunkData)) @@ -296,6 +306,7 @@ func (su *ChunkedUpload) listen(allEventChan []chan worker.MessageEvent, respCha if errC >= int32(su.consensus.consensusThresh) { wgErrors <- thrown.New("upload_failed", fmt.Sprintf("Upload failed. %s", errMsgStr)) } + return } chunkEndIndexObj, _ := data.Get("chunkEndIndex") chunkEndIndex, _ := chunkEndIndexObj.Int() @@ -360,7 +371,7 @@ func (su *ChunkedUpload) listen(allEventChan []chan worker.MessageEvent, respCha } for chunkEndIndex, count := range su.processMap { if count >= su.consensus.consensusThresh { - su.updateProgress(chunkEndIndex) + su.updateProgress(chunkEndIndex, su.uploadMask) delete(su.processMap, chunkEndIndex) } } diff --git a/zboxcore/sdk/chunked_upload_progress_storer.go b/zboxcore/sdk/chunked_upload_progress_storer.go index 0b36d20d1..a21bc4a1d 100644 --- a/zboxcore/sdk/chunked_upload_progress_storer.go +++ b/zboxcore/sdk/chunked_upload_progress_storer.go @@ -12,6 +12,7 @@ import ( "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk/zboxcore/zboxutil" ) // ChunkedUploadProgressStorer load and save upload progress @@ -23,16 +24,17 @@ type ChunkedUploadProgressStorer interface { // Remove remove upload progress by id Remove(id string) error // Update update upload progress - Update(id string, chunkIndex int) + Update(id string, chunkIndex int, upMask zboxutil.Uint128) } // fsChunkedUploadProgressStorer load and save upload progress in file system type fsChunkedUploadProgressStorer struct { sync.Mutex - isRemoved bool - up UploadProgress - queue queue - next int + isRemoved bool + up UploadProgress + queue queue + next int + uploadMask zboxutil.Uint128 } type queue []int @@ -136,6 +138,7 @@ func (fs *fsChunkedUploadProgressStorer) Save(up UploadProgress) { fs.next = up.ChunkIndex + up.ChunkNumber } } + fs.up.UploadMask = fs.uploadMask buf, err := json.Marshal(fs.up) if err != nil { logger.Logger.Error("[progress] save ", fs.up, err) @@ -148,10 +151,11 @@ func (fs *fsChunkedUploadProgressStorer) Save(up UploadProgress) { } } -func (fs *fsChunkedUploadProgressStorer) Update(id string, chunkIndex int) { +func (fs *fsChunkedUploadProgressStorer) Update(id string, chunkIndex int, upMask zboxutil.Uint128) { fs.Lock() defer fs.Unlock() if !fs.isRemoved { + fs.uploadMask = upMask heap.Push(&fs.queue, chunkIndex) } } diff --git a/zboxcore/sdk/doc.go b/zboxcore/sdk/doc.go new file mode 100644 index 000000000..4503fd4a3 --- /dev/null +++ b/zboxcore/sdk/doc.go @@ -0,0 +1,2 @@ +// Main functionality of the SDK. +package sdk \ No newline at end of file diff --git a/zboxcore/sdk/download_progress_storer.go b/zboxcore/sdk/download_progress_storer.go index 23bed5aab..dce3ace95 100644 --- a/zboxcore/sdk/download_progress_storer.go +++ b/zboxcore/sdk/download_progress_storer.go @@ -33,6 +33,7 @@ type FsDownloadProgressStorer struct { queue queue } +// CreateFsDownloadProgress create a download progress storer instance to track download progress and queue func CreateFsDownloadProgress() *FsDownloadProgressStorer { down := &FsDownloadProgressStorer{ queue: make(queue, 0), diff --git a/zboxcore/sdk/downloader.go b/zboxcore/sdk/downloader.go index 18db2b520..b2aa4062f 100644 --- a/zboxcore/sdk/downloader.go +++ b/zboxcore/sdk/downloader.go @@ -41,7 +41,11 @@ type DownloadOptions struct { reqOpts []DownloadRequestOption } -// CreateDownloader create a downloander +// CreateDownloader create a downloander instance with options +// - allocationID: allocation id +// - localPath: local path to save the downloaded file +// - remotePath: remote path of the file to download +// - opts: download options as option functions func CreateDownloader(allocationID, localPath, remotePath string, opts ...DownloadOption) (Downloader, error) { do := DownloadOptions{ localPath: localPath, @@ -136,6 +140,7 @@ type baseDownloader struct { DownloadOptions } +// GetAllocation get the allocation object func (d *baseDownloader) GetAllocation() *Allocation { if d == nil { return nil @@ -143,6 +148,7 @@ func (d *baseDownloader) GetAllocation() *Allocation { return d.allocationObj } +// GetFileName get the file name func (d *baseDownloader) GetFileName() string { if d == nil { return "" diff --git a/zboxcore/sdk/downloader_option.go b/zboxcore/sdk/downloader_option.go index 78c9f335a..0dca50557 100644 --- a/zboxcore/sdk/downloader_option.go +++ b/zboxcore/sdk/downloader_option.go @@ -7,18 +7,26 @@ const DefaultBlocksPerMarker int = 100 // DownloadOption set download option type DownloadOption func(do *DownloadOptions) +// WithVerifyDownload set verify download option for the download request options. +// If true, the response will contain proof of the download to be verified at the client side. +// - shouldVerify: true to verify download, false to not verify download. func WithVerifyDownload(shouldVerify bool) DownloadOption { return func(do *DownloadOptions) { do.verifyDownload = shouldVerify } } +// WithAllocation set allocation object of the download option func WithAllocation(obj *Allocation) DownloadOption { return func(do *DownloadOptions) { do.allocationObj = obj } } +// WithBlocks set block range for the download request options. +// - start: start block number +// - end: end block number +// - blocksPerMarker: number of blocks to download func WithBlocks(start, end int64, blocksPerMarker int) DownloadOption { return func(do *DownloadOptions) { if start > 0 && end > 0 && end >= start { @@ -37,12 +45,18 @@ func WithBlocks(start, end int64, blocksPerMarker int) DownloadOption { } } +// WithOnlyThumbnail set thumbnail download option which makes the request download only the thumbnail. +// - thumbnail: true to download only thumbnail, false to download the file. func WithOnlyThumbnail(thumbnail bool) DownloadOption { return func(do *DownloadOptions) { do.isThumbnailDownload = thumbnail } } +// WithAuthTicket set auth ticket and lookup hash for the download request options +// This is used to download shared files. +// - authTicket: is the ticket that is generated by the owner of the file to access their shared file. +// - lookupHash: is an augmented hash of the allocation ID and the path of the file, used to locate the file. func WithAuthticket(authTicket, lookupHash string) DownloadOption { return func(do *DownloadOptions) { if len(authTicket) > 0 { @@ -53,6 +67,7 @@ func WithAuthticket(authTicket, lookupHash string) DownloadOption { } } +// WithFileHandler set file handler for the download request options func WithFileHandler(fileHandler sys.File) DownloadOption { return func(do *DownloadOptions) { do.fileHandler = fileHandler diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 94ab07879..a4c178efc 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -46,6 +46,8 @@ var ( type DownloadRequestOption func(dr *DownloadRequest) +// WithDownloadProgressStorer set download progress storer of download request options. +// - storer: download progress storer instance, used to store download progress. func WithDownloadProgressStorer(storer DownloadProgressStorer) DownloadRequestOption { return func(dr *DownloadRequest) { dr.downloadStorer = storer diff --git a/zboxcore/sdk/filemetaworker.go b/zboxcore/sdk/filemetaworker.go index b8600ce2b..068447800 100644 --- a/zboxcore/sdk/filemetaworker.go +++ b/zboxcore/sdk/filemetaworker.go @@ -24,6 +24,12 @@ type fileMetaResponse struct { err error } +type fileMetaByNameResponse struct { + filerefs []*fileref.FileRef + blobberIdx int + err error +} + func (req *ListRequest) getFileMetaInfoFromBlobber(blobber *blockchain.StorageNode, blobberIdx int, rspCh chan<- *fileMetaResponse) { body := new(bytes.Buffer) formWriter := multipart.NewWriter(body) @@ -104,6 +110,71 @@ func (req *ListRequest) getFileMetaInfoFromBlobber(blobber *blockchain.StorageNo }) } +func (req *ListRequest) getFileMetaByNameInfoFromBlobber(blobber *blockchain.StorageNode, blobberIdx int, rspCh chan<- *fileMetaByNameResponse) { + body := new(bytes.Buffer) + formWriter := multipart.NewWriter(body) + + var fileRef []*fileref.FileRef + var err error + fileMetaRetFn := func() { + rspCh <- &fileMetaByNameResponse{filerefs: fileRef, blobberIdx: blobberIdx, err: err} + } + defer fileMetaRetFn() + + if req.filename != "" { + err = formWriter.WriteField("name", req.filename) + if err != nil { + l.Logger.Error("File meta info request error: ", err.Error()) + return + } + } + if req.authToken != nil { + authTokenBytes, err := json.Marshal(req.authToken) + if err != nil { + l.Logger.Error(blobber.Baseurl, " creating auth token bytes", err) + return + } + err = formWriter.WriteField("auth_token", string(authTokenBytes)) + if err != nil { + l.Logger.Error(blobber.Baseurl, "error writing field", err) + return + } + } + formWriter.Close() + httpreq, err := zboxutil.NewFileMetaRequest(blobber.Baseurl, req.allocationID, req.allocationTx, body) + if err != nil { + l.Logger.Error("File meta info request error: ", err.Error()) + return + } + + httpreq.Header.Add("Content-Type", formWriter.FormDataContentType()) + ctx, cncl := context.WithTimeout(req.ctx, (time.Second * 30)) + err = zboxutil.HttpDo(ctx, cncl, httpreq, func(resp *http.Response, err error) error { + if err != nil { + l.Logger.Error("GetFileMeta : ", err) + return err + } + defer resp.Body.Close() + resp_body, err := io.ReadAll(resp.Body) + if err != nil { + return errors.Wrap(err, "Error: Resp") + } + // l.Logger.Info("File Meta result:", string(resp_body)) + l.Logger.Debug("File meta response status: ", resp.Status) + if resp.StatusCode == http.StatusOK { + err = json.Unmarshal(resp_body, &fileRef) + if err != nil { + return errors.Wrap(err, "file meta data response parse error") + } + return nil + } else if resp.StatusCode == http.StatusBadRequest { + return constants.ErrNotFound + } + return fmt.Errorf("unexpected response. status code: %d, response: %s", + resp.StatusCode, string(resp_body)) + }) +} + func (req *ListRequest) getFileMetaFromBlobbers() []*fileMetaResponse { numList := len(req.blobbers) rspCh := make(chan *fileMetaResponse, numList) @@ -118,6 +189,20 @@ func (req *ListRequest) getFileMetaFromBlobbers() []*fileMetaResponse { return fileInfos } +func (req *ListRequest) getFileMetaByNameFromBlobbers() []*fileMetaByNameResponse { + numList := len(req.blobbers) + rspCh := make(chan *fileMetaByNameResponse, numList) + for i := 0; i < numList; i++ { + go req.getFileMetaByNameInfoFromBlobber(req.blobbers[i], i, rspCh) + } + fileInfos := make([]*fileMetaByNameResponse, len(req.blobbers)) + for i := 0; i < numList; i++ { + ch := <-rspCh + fileInfos[ch.blobberIdx] = ch + } + return fileInfos +} + func (req *ListRequest) getFileConsensusFromBlobbers() (zboxutil.Uint128, zboxutil.Uint128, *fileref.FileRef, []*fileMetaResponse) { lR := req.getFileMetaFromBlobbers() var selected *fileMetaResponse @@ -168,4 +253,50 @@ func (req *ListRequest) getFileConsensusFromBlobbers() (zboxutil.Uint128, zboxut return foundMask, deleteMask, selected.fileref, lR } +func (req *ListRequest) getMultipleFileConsensusFromBlobbers() (zboxutil.Uint128, zboxutil.Uint128, []*fileref.FileRef, []*fileMetaByNameResponse) { + lR := req.getFileMetaByNameFromBlobbers() + var filerRefs []*fileref.FileRef + uniquePathHashes := map[string]bool{} + for i := 0; i < len(lR); i++ { + ti := lR[i] + if ti.err != nil || len(ti.filerefs) == 0 { + continue + } + for _, fileRef := range ti.filerefs { + uniquePathHashes[fileRef.PathHash] = true + } + } + // take the pathhash as unique and for each path hash append the fileref which have consensus. + + for pathHash := range uniquePathHashes { + req.consensus = 0 + retMap := make(map[string]int) + outerLoop: + for i := 0; i < len(lR); i++ { + ti := lR[i] + if ti.err != nil || len(ti.filerefs) == 0 { + continue + } + for _, fRef := range ti.filerefs { + if fRef == nil { + continue + } + if pathHash == fRef.PathHash { + fileMetaHash := fRef.FileMetaHash + retMap[fileMetaHash]++ + if retMap[fileMetaHash] > req.consensus { + req.consensus = retMap[fileMetaHash] + } + if req.isConsensusOk() { + filerRefs = append(filerRefs, fRef) + break outerLoop + } + break + } + } + } + } + return zboxutil.NewUint128(0), zboxutil.NewUint128(0), filerRefs, lR +} + // return upload mask and delete mask diff --git a/zboxcore/sdk/filestatsworker.go b/zboxcore/sdk/filestatsworker.go index a6e2805bf..70a3083d4 100644 --- a/zboxcore/sdk/filestatsworker.go +++ b/zboxcore/sdk/filestatsworker.go @@ -17,6 +17,7 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" ) +// FileStats - file stats structure type FileStats struct { Name string `json:"name"` Size int64 `json:"size"` diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index 18911e6f0..6706eef98 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -28,6 +28,7 @@ type ListRequest struct { blobbers []*blockchain.StorageNode remotefilepathhash string remotefilepath string + filename string authToken *marker.AuthTicket ctx context.Context forRepair bool @@ -44,6 +45,8 @@ type listResponse struct { err error } +// ListResult a wrapper around the result of directory listing command. +// It can represent a file or a directory. type ListResult struct { Name string `json:"name"` Path string `json:"path,omitempty"` @@ -275,7 +278,7 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { return result, nil } -// populateChildren calculates the children of a directory +// populateChildren calculates the children of a directory and populates the list result. func (lr *ListResult) populateChildren(children []fileref.RefEntity, childResultMap map[string]*ListResult, selected map[string]*ListResult, req *ListRequest) { for _, child := range children { diff --git a/zboxcore/sdk/live_upload.go b/zboxcore/sdk/live_upload.go index 63ea8fc73..37b22a7ca 100644 --- a/zboxcore/sdk/live_upload.go +++ b/zboxcore/sdk/live_upload.go @@ -26,7 +26,12 @@ type LiveUpload struct { statusCallback func() StatusCallback } -// CreateLiveUpload create a LiveChunkedUpload instance +// CreateLiveUpload create a LiveChunkedUpload instance to upload live streaming video +// - homedir: home directory of the allocation +// - allocationObj: allocation object +// - liveMeta: live meta data +// - liveReader: live reader to read video data +// - opts: live upload option functions which customize the LiveUpload instance. func CreateLiveUpload(homedir string, allocationObj *Allocation, liveMeta LiveMeta, liveReader LiveUploadReader, opts ...LiveUploadOption) *LiveUpload { u := &LiveUpload{ allocationObj: allocationObj, diff --git a/zboxcore/sdk/live_upload_option.go b/zboxcore/sdk/live_upload_option.go index 9e8da3273..96413c69e 100644 --- a/zboxcore/sdk/live_upload_option.go +++ b/zboxcore/sdk/live_upload_option.go @@ -3,7 +3,8 @@ package sdk // LiveUploadOption set live upload option type LiveUploadOption func(lu *LiveUpload) -// WithLiveDelay set delayed . ignore if delayed <=0 +// WithLiveDelay set number of seconds to wait before starting the live upload. Ignore if less than 0. +// - delaySeconds: number of seconds func WithLiveDelay(delaySeconds int) LiveUploadOption { return func(lu *LiveUpload) { if delaySeconds > 0 { @@ -12,7 +13,8 @@ func WithLiveDelay(delaySeconds int) LiveUploadOption { } } -// WithLiveChunkNumber set the number of chunks should be upload in a request. ignore if size <=0 +// WithLiveChunkNumber set the number of chunks should be upload in a live upload request. Ignore if size <=0. +// - num: number of chunks func WithLiveChunkNumber(num int) LiveUploadOption { return func(lu *LiveUpload) { if num > 0 { @@ -21,14 +23,16 @@ func WithLiveChunkNumber(num int) LiveUploadOption { } } -// WithLiveEncrypt trun on/off encrypt on upload. It is turn off as default. +// WithLiveEncrypt trun on/off encrypt on upload. It is turned off by default. +// - status: true to turn on, false to turn off func WithLiveEncrypt(status bool) LiveUploadOption { return func(lu *LiveUpload) { lu.encryptOnUpload = status } } -// WithLiveStatusCallback register StatusCallback instance +// WithLiveStatusCallback register StatusCallback instance to track live upload progress +// - callback: StatusCallback instance func WithLiveStatusCallback(callback func() StatusCallback) LiveUploadOption { return func(lu *LiveUpload) { lu.statusCallback = callback diff --git a/zboxcore/sdk/live_upload_reader_ffmpeg.go b/zboxcore/sdk/live_upload_reader_ffmpeg.go index 0e9c557e2..aefec2935 100644 --- a/zboxcore/sdk/live_upload_reader_ffmpeg.go +++ b/zboxcore/sdk/live_upload_reader_ffmpeg.go @@ -16,6 +16,8 @@ type FfmpegRecorder struct { } // CreateFfmpegRecorder create a ffmpeg commander to capture video and audio local camera and microphone +// - file: output file path +// - delay: delay in seconds func CreateFfmpegRecorder(file string, delay int) (*FfmpegRecorder, error) { builder := createFileNameBuilder(file) diff --git a/zboxcore/sdk/live_upload_reader_youtubedl.go b/zboxcore/sdk/live_upload_reader_youtubedl.go index 668848b7e..2d6646a25 100644 --- a/zboxcore/sdk/live_upload_reader_youtubedl.go +++ b/zboxcore/sdk/live_upload_reader_youtubedl.go @@ -24,6 +24,11 @@ type YoutubeDL struct { } // CreateYoutubeDL create a youtube-dl instance to download video file from youtube +// - localPath: output file path +// - feedURL: youtube video url +// - downloadArgs: youtube-dl download arguments +// - ffmpegArgs: ffmpeg arguments +// - delay: delay in seconds func CreateYoutubeDL(ctx context.Context, localPath string, feedURL string, downloadArgs []string, ffmpegArgs []string, delay int) (*YoutubeDL, error) { //youtube-dl -f best https://www.youtube.com/watch?v=RfUVIwnsvS8 --proxy http://127.0.0.1:8000 -o - | ffmpeg -i - -flags +cgop -g 30 -hls_time 5 youtube.m3u8 diff --git a/zboxcore/sdk/m3u8.go b/zboxcore/sdk/m3u8.go index 2684e372c..3accec4c1 100644 --- a/zboxcore/sdk/m3u8.go +++ b/zboxcore/sdk/m3u8.go @@ -26,7 +26,7 @@ import ( // #EXTINF:5.000000, // tv21.ts -// MediaPlaylist m3u8 encoder and decoder +// MediaPlaylist queue-based m3u8 playlist type MediaPlaylist struct { dir string delay int @@ -60,12 +60,12 @@ func NewMediaPlaylist(delay int, dir string, writer M3u8Writer) *MediaPlaylist { return m3u8 } -// Append append new item +// Append append new item into playlist func (m *MediaPlaylist) Append(item string) { m.next <- item } -// Play start to push item into playlist +// Play start to play the contents of the playlist with 1 second buffer between each item func (m *MediaPlaylist) Play() { for { diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index b42d7cc20..8c181b85f 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -36,6 +36,8 @@ type RepairStatusCB struct { statusCB StatusCallback } +var RepairBlocks = 100 + type getRes struct { oTR *ObjectTreeResult err error @@ -78,13 +80,21 @@ func (r *RepairRequest) processRepair(ctx context.Context, a *Allocation) { if r.checkForCancel(a) { return } - SetNumBlockDownloads(100) + SetNumBlockDownloads(RepairBlocks) + currBatchSize := BatchSize + BatchSize = BatchSize / 2 + defer func() { + BatchSize = currBatchSize + }() + if !singleClientMode { + SetSingleClietnMode(true) + defer SetSingleClietnMode(false) + } currentSize := MultiOpBatchSize SetMultiOpBatchSize(multiOpRepairBatchSize) defer SetMultiOpBatchSize(currentSize) r.allocation = a r.iterateDir(ctx) - if r.statusCB != nil { r.statusCB.RepairCompleted(r.filesRepaired) } diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 81cbc505c..a35c57f1c 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -231,6 +231,8 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error return thrown.New("rolback_error", fmt.Sprint("Rollback failed")) } +// CheckAllocStatus checks the status of the allocation +// and returns the status of the allocation and its blobbers. func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { wg := &sync.WaitGroup{} @@ -357,6 +359,9 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { return Rollback, blobberRes, nil } +// RollbackWithMask rolls back the latest operation from the allocation blobbers which ran it. +// The mask is used to specify which blobbers to rollback. +// - mask: 128-bitmask to specify which blobbers to rollback func (a *Allocation) RollbackWithMask(mask zboxutil.Uint128) { wg := &sync.WaitGroup{} diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 102a9191b..84fee6a61 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -81,14 +81,14 @@ func GetVersion() string { } // SetLogLevel set the log level. -// lvl - 0 disabled; higher number (upto 4) more verbosity +// - lvl: 0 disabled; higher number (upto 4) more verbosity func SetLogLevel(lvl int) { l.Logger.SetLevel(lvl) } -// SetLogFile -// logFile - Log file -// verbose - true - console output; false - no console output +// SetLogFile set the log file and verbosity levels +// - logFile: Log file +// - verbose: true - console output; false - no console output func SetLogFile(logFile string, verbose bool) { var ioWriter = &lumberjack.Logger{ Filename: logFile, @@ -103,10 +103,20 @@ func SetLogFile(logFile string, verbose bool) { l.Logger.Info("******* Storage SDK Version: ", version.VERSIONSTR, " *******") } +// GetLogger retrieves logger instance func GetLogger() *logger.Logger { return &l.Logger } +// InitStorageSDK Initialize the storage SDK +// +// - walletJSON: Client's wallet JSON +// - blockWorker: Block worker URL (block worker refers to 0DNS) +// - chainID: ID of the blokcchain network +// - signatureScheme: Signature scheme that will be used for signing transactions +// - preferredBlobbers: List of preferred blobbers to use when creating an allocation. This is usually configured by the client in the configuration files +// - nonce: Initial nonce value for the transactions +// - fee: Preferred value for the transaction fee, just the first value is taken func InitStorageSDK(walletJSON string, blockWorker, chainID, signatureScheme string, preferredBlobbers []string, @@ -135,6 +145,7 @@ func InitStorageSDK(walletJSON string, return nil } +// GetNetwork retrieves the network details func GetNetwork() *Network { return &Network{ Miners: blockchain.GetMiners(), @@ -142,6 +153,7 @@ func GetNetwork() *Network { } } +// SetMaxTxnQuery set the maximum number of transactions to query func SetMaxTxnQuery(num int) { blockchain.SetMaxTxnQuery(num) @@ -152,6 +164,7 @@ func SetMaxTxnQuery(num int) { } +// SetQuerySleepTime set the sleep time between queries func SetQuerySleepTime(time int) { blockchain.SetQuerySleepTime(time) @@ -162,23 +175,28 @@ func SetQuerySleepTime(time int) { } +// SetMinSubmit set the minimum number of miners to submit the transaction func SetMinSubmit(num int) { blockchain.SetMinSubmit(num) } + +// SetMinConfirmation set the minimum number of miners to confirm the transaction func SetMinConfirmation(num int) { blockchain.SetMinConfirmation(num) } +// SetNetwork set the network details, given the miners and sharders urls +// - miners: list of miner urls +// - sharders: list of sharder urls func SetNetwork(miners []string, sharders []string) { blockchain.SetMiners(miners) blockchain.SetSharders(sharders) node.InitCache(blockchain.Sharders) } -// -// read pool -// - +// CreateReadPool creates a read pool for the SDK client. +// Read pool is used to lock tokens for read operations. +// Currently, all read operations are free 🚀. func CreateReadPool() (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -204,6 +222,7 @@ type ReadPool struct { // GetReadPoolInfo for given client, or, if the given clientID is empty, // for current client of the sdk. +// - clientID: client ID func GetReadPoolInfo(clientID string) (info *ReadPool, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -232,6 +251,8 @@ func GetReadPoolInfo(clientID string) (info *ReadPool, err error) { } // ReadPoolLock locks given number of tokes for given duration in read pool. +// - tokens: number of tokens to lock +// - fee: transaction fee func ReadPoolLock(tokens, fee uint64) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -246,6 +267,7 @@ func ReadPoolLock(tokens, fee uint64) (hash string, nonce int64, err error) { } // ReadPoolUnlock unlocks tokens in expired read pool +// - fee: transaction fee func ReadPoolUnlock(fee uint64) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -293,7 +315,7 @@ type StakePoolDelegatePoolInfo struct { StakedAt common.Timestamp `json:"staked_at"` } -// StakePool full info. +// StakePool information of stake pool of a provider. type StakePoolInfo struct { ID common.Key `json:"pool_id"` // pool ID Balance common.Balance `json:"balance"` // total balance @@ -308,8 +330,9 @@ type StakePoolInfo struct { Settings blockchain.StakePoolSettings `json:"settings"` } -// GetStakePoolInfo for given client, or, if the given clientID is empty, -// for current client of the sdk. +// GetStakePoolInfo retrieve stake pool info for the current client configured to the sdk, given provider type and provider ID. +// - providerType: provider type +// - providerID: provider ID func GetStakePoolInfo(providerType ProviderType, providerID string) (info *StakePoolInfo, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -338,8 +361,11 @@ type StakePoolUserInfo struct { Pools map[common.Key][]*StakePoolDelegatePoolInfo `json:"pools"` } -// GetStakePoolUserInfo obtains blobbers/validators delegate pools statistic -// for a user. If given clientID is empty string, then current client used. +// GetStakePoolUserInfo obtains blobbers/validators delegate pools statistic for a user. +// If given clientID is empty string, then current client used. +// - clientID: client ID +// - offset: offset +// - limit: limit func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUserInfo, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -376,7 +402,14 @@ type stakePoolRequest struct { ProviderID string `json:"provider_id,omitempty"` } -// StakePoolLock locks tokens lack in stake pool +// StakePoolLock locks tokens in a stake pool. +// This function is the entry point for the staking operation. +// Provided the provider type and provider ID, the value is locked in the stake pool between the SDK client and the provider. +// Based on the locked amount, the client will get rewards as share of the provider's rewards. +// - providerType: provider type +// - providerID: provider ID +// - value: value to lock +// - fee: transaction fee func StakePoolLock(providerType ProviderType, providerID string, value, fee uint64) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -433,6 +466,9 @@ type stakePoolLock struct { // future. The time is maximal time that can be lesser in some cases. To // unlock tokens can't be unlocked now, wait the time and unlock them (call // this function again). +// - providerType: provider type +// - providerID: provider ID +// - fee: transaction fee func StakePoolUnlock(providerType ProviderType, providerID string, fee uint64) (unstake int64, nonce int64, err error) { if !sdkInitialized { return 0, 0, sdkNotInitialized @@ -488,6 +524,9 @@ func StakePoolUnlock(providerType ProviderType, providerID string, fee uint64) ( // // WritePoolLock locks given number of tokes for given duration in read pool. +// - allocID: allocation ID +// - tokens: number of tokens to lock +// - fee: transaction fee func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -509,7 +548,9 @@ func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64 return } -// WritePoolUnlock unlocks tokens in expired read pool +// WritePoolUnlock unlocks ALL tokens of a write pool. Needs to be cancelled first. +// - allocID: allocation ID +// - fee: transaction fee func WritePoolUnlock(allocID string, fee uint64) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -543,7 +584,8 @@ type ChallengePoolInfo struct { Finalized bool `json:"finalized"` } -// GetChallengePoolInfo for given allocation. +// GetChallengePoolInfo retrieve challenge pool info for given allocation. +// - allocID: allocation ID func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -568,6 +610,7 @@ func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { return } +// GetMptData retrieves mpt key data. func GetMptData(key string) ([]byte, error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -596,6 +639,7 @@ type InputMap struct { Fields map[string]interface{} `json:"fields"` } +// GetStorageSCConfig retrieves storage SC configurations. func GetStorageSCConfig() (conf *InputMap, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -620,24 +664,58 @@ func GetStorageSCConfig() (conf *InputMap, err error) { return } +// Blobber type represents blobber information. type Blobber struct { - ID common.Key `json:"id"` - BaseURL string `json:"url"` - Terms Terms `json:"terms"` - Capacity common.Size `json:"capacity"` - Allocated common.Size `json:"allocated"` - LastHealthCheck common.Timestamp `json:"last_health_check"` - PublicKey string `json:"-"` - StakePoolSettings blockchain.StakePoolSettings `json:"stake_pool_settings"` - TotalStake int64 `json:"total_stake"` - UsedAllocation int64 `json:"used_allocation"` - TotalOffers int64 `json:"total_offers"` - TotalServiceCharge int64 `json:"total_service_charge"` - UncollectedServiceCharge int64 `json:"uncollected_service_charge"` - IsKilled bool `json:"is_killed"` - IsShutdown bool `json:"is_shutdown"` - NotAvailable bool `json:"not_available"` - IsRestricted bool `json:"is_restricted"` + // ID of the blobber + ID common.Key `json:"id"` + + // BaseURL of the blobber + BaseURL string `json:"url"` + + // Terms of the blobber + Terms Terms `json:"terms"` + + // Capacity of the blobber + Capacity common.Size `json:"capacity"` + + // Allocated size of the blobber + Allocated common.Size `json:"allocated"` + + // LastHealthCheck of the blobber + LastHealthCheck common.Timestamp `json:"last_health_check"` + + // PublicKey of the blobber + PublicKey string `json:"-"` + + // StakePoolSettings settings of the blobber staking + StakePoolSettings blockchain.StakePoolSettings `json:"stake_pool_settings"` + + // TotalStake of the blobber in SAS + TotalStake int64 `json:"total_stake"` + + // UsedAllocation of the blobber in SAS + UsedAllocation int64 `json:"used_allocation"` + + // TotalOffers of the blobber in SAS + TotalOffers int64 `json:"total_offers"` + + // TotalServiceCharge of the blobber in SAS + TotalServiceCharge int64 `json:"total_service_charge"` + + // UncollectedServiceCharge of the blobber in SAS + UncollectedServiceCharge int64 `json:"uncollected_service_charge"` + + // IsKilled flag of the blobber, if true then the blobber is killed + IsKilled bool `json:"is_killed"` + + // IsShutdown flag of the blobber, if true then the blobber is shutdown + IsShutdown bool `json:"is_shutdown"` + + // NotAvailable flag of the blobber, if true then the blobber is not available + NotAvailable bool `json:"not_available"` + + // IsRestricted flag of the blobber, if true then the blobber is restricted + IsRestricted bool `json:"is_restricted"` } // UpdateBlobber is used during update blobber settings calls. @@ -662,6 +740,7 @@ type UpdateBlobber struct { IsRestricted *bool `json:"is_restricted,omitempty"` } +// ResetBlobberStatsDto represents blobber stats reset request. type ResetBlobberStatsDto struct { BlobberID string `json:"blobber_id"` PrevAllocated int64 `json:"prev_allocated"` @@ -670,6 +749,7 @@ type ResetBlobberStatsDto struct { NewSavedData int64 `json:"new_saved_data"` } +// Validator represents validator information. type Validator struct { ID common.Key `json:"validator_id"` BaseURL string `json:"url"` @@ -687,6 +767,9 @@ type Validator struct { IsShutdown bool `json:"is_shutdown"` } +// UpdateValidator is used during update validator settings calls. +// Note the types are of pointer types with omitempty json property. +// This is done to correctly identify which properties are actually changing. type UpdateValidator struct { ID common.Key `json:"validator_id"` BaseURL *string `json:"url,omitempty"` @@ -703,6 +786,7 @@ type UpdateValidator struct { IsShutdown *bool `json:"is_shutdown,omitempty"` } +// ConvertToValidationNode converts UpdateValidator request to blockchain.UpdateValidationNode. func (v *UpdateValidator) ConvertToValidationNode() *blockchain.UpdateValidationNode { blockValidator := &blockchain.UpdateValidationNode{ ID: string(v.ID), @@ -753,6 +837,9 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe return wrap.Nodes, nil } +// GetBlobbers returns list of blobbers. +// - active: if true then only active blobbers are returned +// - stakable: if true then only stakable blobbers are returned func GetBlobbers(active, stakable bool) (bs []*Blobber, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -785,10 +872,8 @@ func GetBlobbers(active, stakable bool) (bs []*Blobber, err error) { return blobbersSl, nil } -// GetBlobber instance. -// -// # Inputs -// - blobberID: the id of blobber +// GetBlobber retrieve blobber by id. +// - blobberID: the id of blobber func GetBlobber(blobberID string) (blob *Blobber, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -812,7 +897,8 @@ func GetBlobber(blobberID string) (blob *Blobber, err error) { return } -// GetValidator instance. +// GetValidator retrieve validator instance by id. +// - validatorID: the id of validator func GetValidator(validatorID string) (validator *Validator, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -836,7 +922,8 @@ func GetValidator(validatorID string) (validator *Validator, err error) { return } -// List all validators +// GetValidators returns list of validators. +// - stakable: if true then only stakable validators are returned func GetValidators(stakable bool) (validators []*Validator, err error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -861,10 +948,7 @@ func GetValidators(stakable bool) (validators []*Validator, err error) { return } -// -// --- -// - +// GetClientEncryptedPublicKey - get the client's public key func GetClientEncryptedPublicKey() (string, error) { if !sdkInitialized { return "", sdkNotInitialized @@ -877,6 +961,10 @@ func GetClientEncryptedPublicKey() (string, error) { return encScheme.GetPublicKey() } +// GetAllocationFromAuthTicket - get allocation from given auth ticket hash. +// AuthTicket is used to access free allocations, and it's generated by the Free Storage Assigner. +// - authTicket: the auth ticket hash +// returns the allocation instance and error if any func GetAllocationFromAuthTicket(authTicket string) (*Allocation, error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -893,6 +981,11 @@ func GetAllocationFromAuthTicket(authTicket string) (*Allocation, error) { return GetAllocation(at.AllocationID) } +// GetAllocation - get allocation from given allocation id +// +// - allocationID: the allocation id +// +// returns the allocation instance and error if any func GetAllocation(allocationID string) (*Allocation, error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -952,12 +1045,17 @@ func GetAllocationUpdates(allocation *Allocation) error { return nil } +// SetNumBlockDownloads - set the number of block downloads, needs to be between 1 and 500 (inclusive). Default is 20. +// - num: the number of block downloads func SetNumBlockDownloads(num int) { if num > 0 && num <= 500 { numBlockDownloads = num } } +// GetAllocations - get all allocations for the current client +// +// returns the list of allocations and error if any func GetAllocations() ([]*Allocation, error) { return GetAllocationsForClient(client.GetClientID()) } @@ -979,7 +1077,11 @@ func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, return allocations, nil } -// get paginated results +// GetAllocationsForClient - get all allocations for given client id +// +// - clientID: the client id +// +// returns the list of allocations and error if any func GetAllocationsForClient(clientID string) ([]*Allocation, error) { if !sdkInitialized { return nil, sdkNotInitialized @@ -1016,6 +1118,7 @@ type FileOptionParam struct { Value bool } +// FileOptionsParameters is used to specify the file options parameters for an allocation, which control the usage permissions of the files in the allocation. type FileOptionsParameters struct { ForbidUpload FileOptionParam ForbidDelete FileOptionParam @@ -1025,6 +1128,7 @@ type FileOptionsParameters struct { ForbidRename FileOptionParam } +// CreateAllocationOptions is used to specify the options for creating a new allocation. type CreateAllocationOptions struct { DataShards int ParityShards int @@ -1035,24 +1139,44 @@ type CreateAllocationOptions struct { BlobberIds []string BlobberAuthTickets []string ThirdPartyExtendable bool + IsEnterprise bool FileOptionsParams *FileOptionsParameters Force bool } +// CreateAllocationWith creates a new allocation with the given options for the current client using the SDK. +// Similar ro CreateAllocationForOwner but uses an options struct instead of individual parameters. +// - options is the options struct instance for creating the allocation. +// returns the hash of the new_allocation_request transaction, the nonce of the transaction, the transaction object and an error if any. func CreateAllocationWith(options CreateAllocationOptions) ( string, int64, *transaction.Transaction, error) { return CreateAllocationForOwner(client.GetClientID(), client.GetClientPublicKey(), options.DataShards, options.ParityShards, options.Size, options.ReadPrice, options.WritePrice, options.Lock, - options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.Force, options.FileOptionsParams) + options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams) } +// CreateAllocationForOwner creates a new allocation with the given options (txn: `storagesc.new_allocation_request`). +// +// - owner is the client id of the owner of the allocation. +// - ownerpublickey is the public key of the owner of the allocation. +// - datashards is the number of data shards for the allocation. +// - parityshards is the number of parity shards for the allocation. +// - size is the size of the allocation. +// - readPrice is the read price range for the allocation (Reads in Züs are free!). +// - writePrice is the write price range for the allocation. +// - lock is the lock value for the transaction (how much tokens to lock to the allocation, in SAS). +// - preferredBlobberIds is a list of preferred blobber ids for the allocation. +// - thirdPartyExtendable is a flag indicating whether the allocation can be extended by a third party. +// - fileOptionsParams is the file options parameters for the allocation, which control the usage permissions of the files in the allocation. +// +// returns the hash of the transaction, the nonce of the transaction, the transaction object and an error if any. func CreateAllocationForOwner( owner, ownerpublickey string, datashards, parityshards int, size int64, readPrice, writePrice PriceRange, - lock uint64, preferredBlobberIds, blobberAuthTickets []string, thirdPartyExtendable, force bool, fileOptionsParams *FileOptionsParameters, + lock uint64, preferredBlobberIds, blobberAuthTickets []string, thirdPartyExtendable, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, ) (hash string, nonce int64, txn *transaction.Transaction, err error) { if lock > math.MaxInt64 { @@ -1077,6 +1201,7 @@ func CreateAllocationForOwner( allocationRequest["owner_public_key"] = ownerpublickey allocationRequest["third_party_extendable"] = thirdPartyExtendable allocationRequest["file_options_changed"], allocationRequest["file_options"] = calculateAllocationFileOptions(63 /*0011 1111*/, fileOptionsParams) + allocationRequest["is_enterprise"] = IsEnterprise var sn = transaction.SmartContractTxnData{ Name: transaction.NEW_ALLOCATION_REQUEST, @@ -1086,6 +1211,16 @@ func CreateAllocationForOwner( return } +// GetAllocationBlobbers returns a list of blobber ids that can be used for a new allocation. +// +// - datashards is the number of data shards for the allocation. +// - parityshards is the number of parity shards for the allocation. +// - size is the size of the allocation. +// - readPrice is the read price range for the allocation (Reads in Züs are free!). +// - writePrice is the write price range for the allocation. +// - force is a flag indicating whether to force the allocation to be created. +// +// returns the list of blobber ids and an error if any. func GetAllocationBlobbers( datashards, parityshards int, size int64, @@ -1177,6 +1312,11 @@ func getNewAllocationBlobbers( }, nil } +// GetBlobberIds returns a list of blobber ids that can be used for a new allocation. +// +// - blobberUrls is a list of blobber urls. +// +// returns a list of blobber ids that can be used for the new allocation and an error if any. func GetBlobberIds(blobberUrls []string) ([]string, error) { if len(blobberUrls) == 0 { @@ -1204,6 +1344,11 @@ func GetBlobberIds(blobberUrls []string) ([]string, error) { return blobberIDs, nil } +// GetFreeAllocationBlobbers returns a list of blobber ids that can be used for a new free allocation. +// +// - request is the request data for the free allocation. +// +// returns a list of blobber ids that can be used for the new free allocation and an error if any. func GetFreeAllocationBlobbers(request map[string]interface{}) ([]string, error) { data, _ := json.Marshal(request) @@ -1224,6 +1369,15 @@ func GetFreeAllocationBlobbers(request map[string]interface{}) ([]string, error) return allocBlobberIDs, nil } +// AddFreeStorageAssigner adds a new free storage assigner (txn: `storagesc.add_free_allocation_assigner`). +// The free storage assigner is used to create free allocations. Can only be called by chain owner. +// +// - name is the name of the assigner. +// - publicKey is the public key of the assigner. +// - individualLimit is the individual limit of the assigner for a single free allocation request +// - totalLimit is the total limit of the assigner for all free allocation requests. +// +// returns the hash of the transaction, the nonce of the transaction and an error if any. func AddFreeStorageAssigner(name, publicKey string, individualLimit, totalLimit float64) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1245,6 +1399,11 @@ func AddFreeStorageAssigner(name, publicKey string, individualLimit, totalLimit return hash, n, err } +// CreateFreeAllocation creates a new free allocation (txn: `storagesc.free_allocation_request`). +// - marker is the marker for the free allocation. +// - value is the value of the free allocation. +// +// returns the hash of the transaction, the nonce of the transaction and an error if any. func CreateFreeAllocation(marker string, value uint64) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1272,6 +1431,19 @@ func CreateFreeAllocation(marker string, value uint64) (string, int64, error) { return hash, n, err } +// UpdateAllocation sends an update request for an allocation (txn: `storagesc.update_allocation_request`) +// +// - size is the size of the allocation. +// - extend is a flag indicating whether to extend the allocation. +// - allocationID is the id of the allocation. +// - lock is the lock value for the transaction (how much tokens to lock to the allocation, in SAS). +// - addBlobberId is the id of the blobber to add to the allocation. +// - addBlobberAuthTicket is the auth ticket of the blobber to add to the allocation, in case the blobber is restricted. +// - removeBlobberId is the id of the blobber to remove from the allocation. +// - setThirdPartyExtendable is a flag indicating whether the allocation can be extended by a third party. +// - fileOptionsParams is the file options parameters for the allocation, which control the usage permissions of the files in the allocation. +// +// returns the hash of the transaction, the nonce of the transaction and an error if any. func UpdateAllocation( size int64, extend bool, @@ -1314,6 +1486,11 @@ func UpdateAllocation( return } +// FinalizeAllocation sends a finalize request for an allocation (txn: `storagesc.finalize_allocation`) +// +// - allocID is the id of the allocation. +// +// returns the hash of the transaction, the nonce of the transaction and an error if any. func FinalizeAllocation(allocID string) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1326,6 +1503,11 @@ func FinalizeAllocation(allocID string) (hash string, nonce int64, err error) { return } +// CancelAllocation sends a cancel request for an allocation (txn: `storagesc.cancel_allocation`) +// +// - allocID is the id of the allocation. +// +// returns the hash of the transaction, the nonce of the transaction and an error if any. func CancelAllocation(allocID string) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1338,6 +1520,7 @@ func CancelAllocation(allocID string) (hash string, nonce int64, err error) { return } +// ProviderType is the type of the provider. type ProviderType int const ( @@ -1348,6 +1531,9 @@ const ( ProviderAuthorizer ) +// KillProvider kills a blobber or a validator (txn: `storagesc.kill_blobber` or `storagesc.kill_validator`) +// - providerId is the id of the provider. +// - providerType` is the type of the provider, either 3 for `ProviderBlobber` or 4 for `ProviderValidator. func KillProvider(providerId string, providerType ProviderType) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1371,6 +1557,9 @@ func KillProvider(providerId string, providerType ProviderType) (string, int64, return hash, n, err } +// ShutdownProvider shuts down a blobber or a validator (txn: `storagesc.shutdown_blobber` or `storagesc.shutdown_validator`) +// - providerId is the id of the provider. +// - providerType` is the type of the provider, either 3 for `ProviderBlobber` or 4 for `ProviderValidator. func ShutdownProvider(providerType ProviderType, providerID string) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1395,6 +1584,9 @@ func ShutdownProvider(providerType ProviderType, providerID string) (string, int return hash, n, err } +// CollectRewards collects the rewards for a provider (txn: `storagesc.collect_reward`) +// - providerId is the id of the provider. +// - providerType is the type of the provider. func CollectRewards(providerId string, providerType ProviderType) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1428,6 +1620,13 @@ func CollectRewards(providerId string, providerType ProviderType) (string, int64 return hash, n, err } +// TransferAllocation transfers the ownership of an allocation to a new owner. (txn: `storagesc.update_allocation_request`) +// +// - allocationId is the id of the allocation. +// - newOwner is the client id of the new owner. +// - newOwnerPublicKey is the public key of the new owner. +// +// returns the hash of the transaction, the nonce of the transaction and an error if any. func TransferAllocation(allocationId, newOwner, newOwnerPublicKey string) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1459,6 +1658,8 @@ func TransferAllocation(allocationId, newOwner, newOwnerPublicKey string) (strin return hash, n, err } +// UpdateBlobberSettings updates the settings of a blobber (txn: `storagesc.update_blobber_settings`) +// - blob is the update blobber request inputs. func UpdateBlobberSettings(blob *UpdateBlobber) (resp string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1471,6 +1672,8 @@ func UpdateBlobberSettings(blob *UpdateBlobber) (resp string, nonce int64, err e return } +// UpdateValidatorSettings updates the settings of a validator (txn: `storagesc.update_validator_settings`) +// - v is the update validator request inputs. func UpdateValidatorSettings(v *UpdateValidator) (resp string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1484,6 +1687,8 @@ func UpdateValidatorSettings(v *UpdateValidator) (resp string, nonce int64, err return } +// ResetBlobberStats resets the stats of a blobber (txn: `storagesc.reset_blobber_stats`) +// - rbs is the reset blobber stats dto, contains the blobber id and its stats. func ResetBlobberStats(rbs *ResetBlobberStatsDto) (string, int64, error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1700,7 +1905,13 @@ func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { return fabricResponse, err } -// expire in milliseconds +// GetAllocationMinLock calculates and returns the minimum lock demand for creating a new allocation, which represents the cost of the creation process. +// - datashards is the number of data shards for the allocation. +// - parityshards is the number of parity shards for the allocation. +// - size is the size of the allocation. +// - writePrice is the write price range for the allocation. +// +// returns the minimum lock demand for the creation process and an error if any. func GetAllocationMinLock( datashards, parityshards int, size int64, @@ -1723,6 +1934,15 @@ func GetAllocationMinLock( return i, nil } +// GetUpdateAllocationMinLock returns the minimum lock demand for updating an allocation, which represents the cost of the update operation. +// +// - allocationID is the id of the allocation. +// - size is the new size of the allocation. +// - extend is a flag indicating whether to extend the expiry of the allocation. +// - addBlobberId is the id of the blobber to add to the allocation. +// - removeBlobberId is the id of the blobber to remove from the allocation. +// +// returns the minimum lock demand for the update operation and an error if any. func GetUpdateAllocationMinLock( allocationID string, size int64, diff --git a/zboxcore/sdk/sync.go b/zboxcore/sdk/sync.go index 1659b7de6..0e40ba150 100644 --- a/zboxcore/sdk/sync.go +++ b/zboxcore/sdk/sync.go @@ -21,14 +21,26 @@ import ( // For sync app const ( - Upload = "Upload" - Download = "Download" - Update = "Update" - Delete = "Delete" - Conflict = "Conflict" + // Upload - Upload file to remote + Upload = "Upload" + + // Download - Download file from remote + Download = "Download" + + // Update - Update file in remote + Update = "Update" + + // Delete - Delete file from remote + Delete = "Delete" + + // Conflict - Conflict in file + Conflict = "Conflict" + + // LocalDelete - Delete file from local LocalDelete = "LocalDelete" ) +// FileInfo file information representation for sync type FileInfo struct { Size int64 `json:"size"` MimeType string `json:"mimetype"` @@ -41,6 +53,7 @@ type FileInfo struct { UpdatedAt common.Timestamp `json:"updated_at"` } +// FileDiff file difference representation for sync type FileDiff struct { Op string `json:"operation"` Path string `json:"path"` @@ -79,6 +92,9 @@ func (a *Allocation) getRemoteFilesAndDirs(dirList []string, fMap map[string]Fil return childDirList, nil } +// GetRemoteFileMap retrieve the remote file map +// - exclMap is the exclude map, a map of paths to exclude +// - remotepath is the remote path to get the file map func (a *Allocation) GetRemoteFileMap(exclMap map[string]int, remotepath string) (map[string]FileInfo, error) { // 1. Iteratively get dir and files separately till no more dirs left remoteList := make(map[string]FileInfo) @@ -135,7 +151,7 @@ func addLocalFileList(root string, fMap map[string]FileInfo, dirList *[]string, l.Logger.Error("getting relative path failed", err) } // Allocation paths are like unix, so we modify all the backslashes - // to forward slashes. File path in windows contain backslashes. + // to forward slashes. File path in windows contain backslashes. lPath = "/" + strings.ReplaceAll(lPath, "\\", "/") // Exclude if _, ok := exclMap[lPath]; ok { @@ -290,6 +306,12 @@ func findDelta(rMap map[string]FileInfo, lMap map[string]FileInfo, prevMap map[s return lFDiff } +// GetAllocationDiff retrieves the difference between the remote and local filesystem representation of the allocation +// - lastSyncCachePath is the path to the last sync cache file, which carries exact state of the remote filesystem +// - localRootPath is the local root path of the allocation +// - localFileFilters is the list of local file filters +// - remoteExcludePath is the list of remote exclude paths +// - remotePath is the remote path of the allocation func (a *Allocation) GetAllocationDiff(lastSyncCachePath string, localRootPath string, localFileFilters []string, remoteExcludePath []string, remotePath string) ([]FileDiff, error) { var lFdiff []FileDiff prevRemoteFileMap := make(map[string]FileInfo) @@ -334,8 +356,10 @@ func (a *Allocation) GetAllocationDiff(lastSyncCachePath string, localRootPath s return lFdiff, nil } -// SaveRemoteSnapShot - Saves the remote current information to the given file +// SaveRemoteSnapshot saves the remote current information to the given file. // This file can be passed to GetAllocationDiff to exactly find the previous sync state to current. +// - pathToSave is the path to save the remote snapshot +// - remoteExcludePath is the list of paths to exclude func (a *Allocation) SaveRemoteSnapshot(pathToSave string, remoteExcludePath []string) error { bIsFileExists := false // Validate path diff --git a/zboxcore/zboxutil/doc.go b/zboxcore/zboxutil/doc.go new file mode 100644 index 000000000..d3419ee76 --- /dev/null +++ b/zboxcore/zboxutil/doc.go @@ -0,0 +1,2 @@ +// Utility functions to support the functionality of the SDK. +package zboxutil \ No newline at end of file diff --git a/zboxcore/zboxutil/download_buffer.go b/zboxcore/zboxutil/download_buffer.go index ec7ad52a3..ab1e17f70 100644 --- a/zboxcore/zboxutil/download_buffer.go +++ b/zboxcore/zboxutil/download_buffer.go @@ -6,6 +6,7 @@ import ( "time" "github.com/0chain/gosdk/core/sys" + "github.com/valyala/bytebufferpool" ) type DownloadBuffer interface { @@ -72,21 +73,21 @@ func (r *DownloadBufferWithChan) ClearBuffer() { } type DownloadBufferWithMask struct { - buf []byte - length int - reqSize int - numBlocks int - mask uint32 - mu sync.Mutex + downloadBuf []*bytebufferpool.ByteBuffer + length int + reqSize int + numBlocks int + mask uint32 + mu sync.Mutex } func NewDownloadBufferWithMask(size, numBlocks, effectiveBlockSize int) *DownloadBufferWithMask { numBlocks++ return &DownloadBufferWithMask{ - buf: make([]byte, size*numBlocks*effectiveBlockSize), - length: size, - reqSize: effectiveBlockSize * numBlocks, - mask: (1 << size) - 1, + length: size, + reqSize: effectiveBlockSize * numBlocks, + mask: (1 << size) - 1, + downloadBuf: make([]*bytebufferpool.ByteBuffer, size), } } @@ -113,8 +114,15 @@ func (r *DownloadBufferWithMask) RequestChunk(ctx context.Context, num int) []by } // assign the chunk by clearing the bit r.mask &= ^(1 << num) + if r.downloadBuf[num] == nil { + buff := BufferPool.Get() + if cap(buff.B) < r.reqSize { + buff.B = make([]byte, r.reqSize) + } + r.downloadBuf[num] = buff + } r.mu.Unlock() - return r.buf[num*r.reqSize : (num+1)*r.reqSize : (num+1)*r.reqSize] + return r.downloadBuf[num].B[:r.reqSize:r.reqSize] } } @@ -127,5 +135,10 @@ func (r *DownloadBufferWithMask) ReleaseChunk(num int) { } func (r *DownloadBufferWithMask) ClearBuffer() { - r.buf = nil + for _, buff := range r.downloadBuf { + if buff != nil { + BufferPool.Put(buff) + } + } + r.downloadBuf = nil } diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 65f038c88..63a8d748a 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -33,6 +33,11 @@ const SLEEP_BETWEEN_RETRIES = 5 // In percentage const consensusThresh = float32(25.0) +// SCRestAPIHandler is a function type to handle the response from the SC Rest API +// +// `response` - the response from the SC Rest API +// `numSharders` - the number of sharders that responded +// `err` - the error if any type SCRestAPIHandler func(response map[string][]byte, numSharders int, err error) type HttpClient interface { @@ -46,10 +51,13 @@ type FastClient interface { var ( Client HttpClient FastHttpClient FastClient - hostLock sync.RWMutex log logger.Logger ) +const ( + respBodyPoolLimit = 1024 * 1024 * 16 //16MB +) + func GetLogger() *logger.Logger { return &log } @@ -175,6 +183,7 @@ func init() { MaxResponseBodySize: 1024 * 1024 * 64, //64MB MaxConnsPerHost: 1024, } + fasthttp.SetBodySizePoolLimit(respBodyPoolLimit, respBodyPoolLimit) envProxy.initialize() log.Init(logger.DEBUG, "0box-sdk") } @@ -898,6 +907,11 @@ func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body return req, nil } +// MakeSCRestAPICall makes a rest api call to the sharders. +// - scAddress is the address of the smart contract +// - relativePath is the relative path of the api +// - params is the query parameters +// - handler is the handler function to handle the response func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, handler SCRestAPIHandler) ([]byte, error) { numSharders := len(blockchain.GetSharders()) sharders := blockchain.GetSharders() diff --git a/zboxcore/zboxutil/uint128.go b/zboxcore/zboxutil/uint128.go index 7554c15b6..e653d6a7b 100644 --- a/zboxcore/zboxutil/uint128.go +++ b/zboxcore/zboxutil/uint128.go @@ -3,46 +3,46 @@ package zboxutil import "math/bits" type Uint128 struct { - high uint64 - low uint64 + High uint64 + Low uint64 } func NewUint128(x uint64) Uint128 { - return Uint128{low: x} + return Uint128{Low: x} } // Add returns x+y. func (x Uint128) Add(y Uint128) Uint128 { - low, carry := bits.Add64(x.low, y.low, 0) - high, carry := bits.Add64(x.high, y.high, carry) + Low, carry := bits.Add64(x.Low, y.Low, 0) + High, carry := bits.Add64(x.High, y.High, carry) if carry != 0 { - panic("overflow") + panic("overfLow") } - return Uint128{high, low} + return Uint128{High, Low} } // Add64 returns x+y. func (x Uint128) Add64(y uint64) Uint128 { - low, carry := bits.Add64(x.low, y, 0) - high, carry := bits.Add64(x.high, 0, carry) + Low, carry := bits.Add64(x.Low, y, 0) + High, carry := bits.Add64(x.High, 0, carry) if carry != 0 { - panic("overflow") + panic("overfLow") } - return Uint128{high, low} + return Uint128{High, Low} } // Sub returns x-y. func (x Uint128) Sub(y Uint128) Uint128 { - low, borrow := bits.Sub64(x.low, y.low, 0) - high, _ := bits.Sub64(x.high, y.high, borrow) - return Uint128{high, low} + Low, borrow := bits.Sub64(x.Low, y.Low, 0) + High, _ := bits.Sub64(x.High, y.High, borrow) + return Uint128{High, Low} } // Sub64 returns x-y. func (x Uint128) Sub64(y uint64) Uint128 { - low, borrow := bits.Sub64(x.low, y, 0) - high, _ := bits.Sub64(x.high, 0, borrow) - return Uint128{high, low} + Low, borrow := bits.Sub64(x.Low, y, 0) + High, _ := bits.Sub64(x.High, 0, borrow) + return Uint128{High, Low} } // Equals returns true if x == y. @@ -52,28 +52,28 @@ func (x Uint128) Equals(y Uint128) bool { // Equals64 returns true if x == y. func (x Uint128) Equals64(y uint64) bool { - return x.low == y && x.high == 0 + return x.Low == y && x.High == 0 } // And returns x&y. func (x Uint128) And(v Uint128) Uint128 { - return Uint128{x.high & v.high, x.low & v.low} + return Uint128{x.High & v.High, x.Low & v.Low} } // And64 returns x&y. func (x Uint128) And64(y uint64) Uint128 { - return Uint128{low: x.low & y} + return Uint128{Low: x.Low & y} } // Lsh returns x< 64 { - z.low = 0 - z.high = x.low << (y - 64) + z.Low = 0 + z.High = x.Low << (y - 64) } else { - z.low = x.low << y - z.high = x.high<>(64-y) + z.Low = x.Low << y + z.High = x.High<>(64-y) } return z @@ -81,28 +81,28 @@ func (x Uint128) Lsh(y uint64) Uint128 { // Not returns ^x. func (x Uint128) Not() Uint128 { - return Uint128{^x.high, ^x.low} + return Uint128{^x.High, ^x.Low} } // Or returns x|y. func (x Uint128) Or(v Uint128) Uint128 { - return Uint128{x.high | v.high, x.low | v.low} + return Uint128{x.High | v.High, x.Low | v.Low} } // Xor returns x^y. func (x Uint128) Xor(v Uint128) Uint128 { - return Uint128{x.high ^ v.high, x.low ^ v.low} + return Uint128{x.High ^ v.High, x.Low ^ v.Low} } // CountOnes return num of 1 bits in x. func (x Uint128) CountOnes() int { - return bits.OnesCount64(x.low) + bits.OnesCount64(x.high) + return bits.OnesCount64(x.Low) + bits.OnesCount64(x.High) } // TrailingZeros returns the number of trailing zero bits in x; the result is 128 for x == 0. func (x Uint128) TrailingZeros() int { - if x.low > 0 { - return bits.TrailingZeros64(x.low) + if x.Low > 0 { + return bits.TrailingZeros64(x.Low) } - return 64 + bits.TrailingZeros64(x.high) + return 64 + bits.TrailingZeros64(x.High) } diff --git a/zboxcore/zboxutil/uint128_test.go b/zboxcore/zboxutil/uint128_test.go index d43294d22..0e12a3ae6 100644 --- a/zboxcore/zboxutil/uint128_test.go +++ b/zboxcore/zboxutil/uint128_test.go @@ -21,21 +21,21 @@ func TestNewUint128(t *testing.T) { name: "OK", args: args{x: 5}, want: Uint128{ - low: 5, + Low: 5, }, }, { name: "0_OK", args: args{x: 0}, want: Uint128{ - low: 0, + Low: 0, }, }, { name: "Max_OK", args: args{x: math.MaxUint64}, want: Uint128{ - low: math.MaxUint64, + Low: math.MaxUint64, }, }, } @@ -60,22 +60,22 @@ func TestUint128_Add(t *testing.T) { x: NewUint128(^uint64(0)), y: NewUint128(1), want: Uint128{ - high: 1, - low: 0, + High: 1, + Low: 0, }, }, { x: NewUint128(^uint64(0)), y: NewUint128(^uint64(0)), want: Uint128{ - high: 1, - low: ^uint64(0) - 1, + High: 1, + Low: ^uint64(0) - 1, }, }, { x: Uint128{ - low: ^uint64(0), - high: ^uint64(0), + Low: ^uint64(0), + High: ^uint64(0), }, y: NewUint128(1), wantPanic: true, diff --git a/zboxcore/zboxutil/util.go b/zboxcore/zboxutil/util.go index 3c38d91f9..0e7ca3815 100644 --- a/zboxcore/zboxutil/util.go +++ b/zboxcore/zboxutil/util.go @@ -25,12 +25,15 @@ import ( "github.com/hitenjain14/fasthttp" "github.com/lithammer/shortuuid/v3" "github.com/minio/sha256-simd" + "github.com/valyala/bytebufferpool" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/scrypt" ) const EncryptedFolderName = "encrypted" +var BufferPool bytebufferpool.Pool + type lazybuf struct { path string buf []byte @@ -66,6 +69,9 @@ func (b *lazybuf) string() string { return b.volAndPath[:b.volLen] + string(b.buf[:b.w]) } +// GetFileContentType returns the content type of the file based on reading the first 10KB of the file +// - ext is the extension of the file, shouldn't be empty +// - out is the file content func GetFileContentType(ext string, out io.ReadSeeker) (string, error) { if ext != "" { @@ -91,6 +97,9 @@ func GetFileContentType(ext string, out io.ReadSeeker) (string, error) { return kind.MIME.Value, nil } +// GetFullRemotePath returns the full remote path by combining the local path and remote path +// - localPath is the local path of the file +// - remotePath is the remote path of the file func GetFullRemotePath(localPath, remotePath string) string { if remotePath == "" || strings.HasSuffix(remotePath, "/") { remotePath = strings.TrimRight(remotePath, "/") @@ -100,15 +109,21 @@ func GetFullRemotePath(localPath, remotePath string) string { return remotePath } -// NewConnectionId generate new connection id +// NewConnectionId generate new connection id. +// Connection is used to track the upload/download progress and redeem the cost of the operation from the network. +// It's in the short uuid format. Check here for more on this format: https://pkg.go.dev/github.com/lithammer/shortuuid/v3@v3.0.7 func NewConnectionId() string { return shortuuid.New() } +// IsRemoteAbs returns true if the path is remote absolute path +// - path is the path to check func IsRemoteAbs(path string) bool { return strings.HasPrefix(path, "/") } +// RemoteClean returns the cleaned remote path +// - path is the path to clean func RemoteClean(path string) string { originalPath := path volLen := 0 //volumeNameLen(path) diff --git a/zcnbridge/README.MD b/zcnbridge/README.MD index e7dacc1e2..ecf6af832 100644 --- a/zcnbridge/README.MD +++ b/zcnbridge/README.MD @@ -1,57 +1,970 @@ -# Bridge SDK documentation + -This bridge SDK comprises 3 types of client and following available methods +# zcnbridge -1. Bridge deployer/owner *for* `Authorizer Smart Contract` -2. Customer/client *to execute* `Bridge Smart contract` burn and mint transactions -3. Token bridge authorizer *for* signing payload for 0Chain and Ethereum chain +```go +import "github.com/0chain/gosdk/zcnbridge" +``` + +## Index + +- [Constants](<#constants>) +- [Variables](<#variables>) +- [func AccountExists\(homedir, address string\) bool](<#AccountExists>) +- [func ConfirmEthereumTransaction\(hash string, times int, duration time.Duration\) \(int, error\)](<#ConfirmEthereumTransaction>) +- [func ConvertIntToHex\(value int64\) string](<#ConvertIntToHex>) +- [func CreateKeyStorage\(homedir, password string\) error](<#CreateKeyStorage>) +- [func DeleteAccount\(homedir, address string\) bool](<#DeleteAccount>) +- [func EncodePackInt64\(key string, param int64\) common.Hash](<#EncodePackInt64>) +- [func GetAuthorizer\(id string, cb zcncore.GetInfoCallback\) \(err error\)](<#GetAuthorizer>) +- [func GetAuthorizers\(active bool, cb zcncore.GetInfoCallback\) \(err error\)](<#GetAuthorizers>) +- [func GetGlobalConfig\(cb zcncore.GetInfoCallback\) \(err error\)](<#GetGlobalConfig>) +- [func GetTransactionStatus\(hash string\) \(int, error\)](<#GetTransactionStatus>) +- [func ImportAccount\(homedir, mnemonic, password string, accountAddrIndex ...AccountAddressIndex\) \(string, error\)](<#ImportAccount>) +- [func ListStorageAccounts\(homedir string\) \[\]common.Address](<#ListStorageAccounts>) +- [type AccountAddressIndex](<#AccountAddressIndex>) +- [type AlchemyGasEstimationRequest](<#AlchemyGasEstimationRequest>) +- [type AuthorizerNode](<#AuthorizerNode>) +- [type AuthorizerNodesResponse](<#AuthorizerNodesResponse>) +- [type AuthorizerResponse](<#AuthorizerResponse>) +- [type BancorTokenDetails](<#BancorTokenDetails>) +- [type BridgeClient](<#BridgeClient>) + - [func NewBridgeClient\(bridgeAddress, tokenAddress, authorizersAddress, uniswapAddress, ethereumAddress, ethereumNodeURL, password string, gasLimit uint64, consensusThreshold float64, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore\) \*BridgeClient](<#NewBridgeClient>) + - [func SetupBridgeClientSDK\(cfg \*BridgeSDKConfig\) \*BridgeClient](<#SetupBridgeClientSDK>) + - [func \(b \*BridgeClient\) AddEthereumAuthorizer\(ctx context.Context, address common.Address\) \(\*types.Transaction, error\)](<#BridgeClient.AddEthereumAuthorizer>) + - [func \(b \*BridgeClient\) AddEthereumAuthorizers\(configDir string\)](<#BridgeClient.AddEthereumAuthorizers>) + - [func \(b \*BridgeClient\) ApproveUSDCSwap\(ctx context.Context, source uint64\) \(\*types.Transaction, error\)](<#BridgeClient.ApproveUSDCSwap>) + - [func \(b \*BridgeClient\) BurnWZCN\(ctx context.Context, amountTokens uint64\) \(\*types.Transaction, error\)](<#BridgeClient.BurnWZCN>) + - [func \(b \*BridgeClient\) BurnZCN\(ctx context.Context, amount, txnfee uint64\) \(transaction.Transaction, error\)](<#BridgeClient.BurnZCN>) + - [func \(b \*BridgeClient\) CreateSignedTransactionFromKeyStore\(client EthereumClient, gasLimitUnits uint64\) \*bind.TransactOpts](<#BridgeClient.CreateSignedTransactionFromKeyStore>) + - [func \(b \*BridgeClient\) EstimateBurnWZCNGasAmount\(ctx context.Context, from, to, amountTokens string\) \(float64, error\)](<#BridgeClient.EstimateBurnWZCNGasAmount>) + - [func \(b \*BridgeClient\) EstimateGasPrice\(ctx context.Context\) \(float64, error\)](<#BridgeClient.EstimateGasPrice>) + - [func \(b \*BridgeClient\) EstimateMintWZCNGasAmount\(ctx context.Context, from, to, zcnTransactionRaw, amountToken string, nonceRaw int64, signaturesRaw \[\]\[\]byte\) \(float64, error\)](<#BridgeClient.EstimateMintWZCNGasAmount>) + - [func \(b \*BridgeClient\) GetETHSwapAmount\(ctx context.Context, source uint64\) \(\*big.Int, error\)](<#BridgeClient.GetETHSwapAmount>) + - [func \(b \*BridgeClient\) GetTokenBalance\(\) \(\*big.Int, error\)](<#BridgeClient.GetTokenBalance>) + - [func \(b \*BridgeClient\) GetUserNonceMinted\(ctx context.Context, rawEthereumAddress string\) \(\*big.Int, error\)](<#BridgeClient.GetUserNonceMinted>) + - [func \(b \*BridgeClient\) IncreaseBurnerAllowance\(ctx context.Context, allowanceAmount uint64\) \(\*types.Transaction, error\)](<#BridgeClient.IncreaseBurnerAllowance>) + - [func \(b \*BridgeClient\) MintWZCN\(ctx context.Context, payload \*ethereum.MintPayload\) \(\*types.Transaction, error\)](<#BridgeClient.MintWZCN>) + - [func \(b \*BridgeClient\) MintZCN\(ctx context.Context, payload \*zcnsc.MintPayload\) \(string, error\)](<#BridgeClient.MintZCN>) + - [func \(b \*BridgeClient\) NFTConfigGetAddress\(ctx context.Context, key string\) \(string, string, error\)](<#BridgeClient.NFTConfigGetAddress>) + - [func \(b \*BridgeClient\) NFTConfigGetUint256\(ctx context.Context, key string, keyParam ...int64\) \(string, int64, error\)](<#BridgeClient.NFTConfigGetUint256>) + - [func \(b \*BridgeClient\) NFTConfigSetAddress\(ctx context.Context, key, address string\) \(\*types.Transaction, error\)](<#BridgeClient.NFTConfigSetAddress>) + - [func \(b \*BridgeClient\) NFTConfigSetUint256\(ctx context.Context, key string, value int64\) \(\*types.Transaction, error\)](<#BridgeClient.NFTConfigSetUint256>) + - [func \(b \*BridgeClient\) NFTConfigSetUint256Raw\(ctx context.Context, key common.Hash, value int64\) \(\*types.Transaction, error\)](<#BridgeClient.NFTConfigSetUint256Raw>) + - [func \(b \*BridgeClient\) QueryEthereumBurnEvents\(startNonce string\) \(\[\]\*ethereum.BurnEvent, error\)](<#BridgeClient.QueryEthereumBurnEvents>) + - [func \(b \*BridgeClient\) QueryEthereumMintPayload\(zchainBurnHash string\) \(\*ethereum.MintPayload, error\)](<#BridgeClient.QueryEthereumMintPayload>) + - [func \(b \*BridgeClient\) QueryZChainMintPayload\(ethBurnHash string\) \(\*zcnsc.MintPayload, error\)](<#BridgeClient.QueryZChainMintPayload>) + - [func \(b \*BridgeClient\) RemoveEthereumAuthorizer\(ctx context.Context, address common.Address\) \(\*types.Transaction, error\)](<#BridgeClient.RemoveEthereumAuthorizer>) + - [func \(b \*BridgeClient\) ResetUserNonceMinted\(ctx context.Context\) \(\*types.Transaction, error\)](<#BridgeClient.ResetUserNonceMinted>) + - [func \(b \*BridgeClient\) SignWithEthereumChain\(message string\) \(\[\]byte, error\)](<#BridgeClient.SignWithEthereumChain>) + - [func \(b \*BridgeClient\) SwapETH\(ctx context.Context, source uint64, target uint64\) \(\*types.Transaction, error\)](<#BridgeClient.SwapETH>) + - [func \(b \*BridgeClient\) SwapUSDC\(ctx context.Context, source uint64, target uint64\) \(\*types.Transaction, error\)](<#BridgeClient.SwapUSDC>) + - [func \(b \*BridgeClient\) VerifyZCNTransaction\(ctx context.Context, hash string\) \(transaction.Transaction, error\)](<#BridgeClient.VerifyZCNTransaction>) +- [type BridgeSDKConfig](<#BridgeSDKConfig>) +- [type DetailedAccount](<#DetailedAccount>) +- [type EthereumBurnEvents](<#EthereumBurnEvents>) + - [func \(r \*EthereumBurnEvents\) Data\(\) interface\{\}](<#EthereumBurnEvents.Data>) + - [func \(r \*EthereumBurnEvents\) Error\(\) error](<#EthereumBurnEvents.Error>) + - [func \(r \*EthereumBurnEvents\) GetAuthorizerID\(\) string](<#EthereumBurnEvents.GetAuthorizerID>) + - [func \(r \*EthereumBurnEvents\) SetAuthorizerID\(id string\)](<#EthereumBurnEvents.SetAuthorizerID>) +- [type EthereumClient](<#EthereumClient>) +- [type GasEstimationRequest](<#GasEstimationRequest>) +- [type GasPriceEstimationResult](<#GasPriceEstimationResult>) +- [type JobError](<#JobError>) + - [func \(e \*JobError\) MarshalJSON\(\) \(\[\]byte, error\)](<#JobError.MarshalJSON>) + - [func \(e \*JobError\) UnmarshalJSON\(buf \[\]byte\) error](<#JobError.UnmarshalJSON>) +- [type JobResult](<#JobResult>) +- [type JobStatus](<#JobStatus>) +- [type KeyStore](<#KeyStore>) + - [func NewKeyStore\(path string\) KeyStore](<#NewKeyStore>) +- [type ProofEthereumBurn](<#ProofEthereumBurn>) +- [type ProofZCNBurn](<#ProofZCNBurn>) + - [func \(r \*ProofZCNBurn\) Data\(\) interface\{\}](<#ProofZCNBurn.Data>) + - [func \(r \*ProofZCNBurn\) Error\(\) error](<#ProofZCNBurn.Error>) + - [func \(r \*ProofZCNBurn\) GetAuthorizerID\(\) string](<#ProofZCNBurn.GetAuthorizerID>) + - [func \(r \*ProofZCNBurn\) SetAuthorizerID\(id string\)](<#ProofZCNBurn.SetAuthorizerID>) +- [type WZCNBurnEvent](<#WZCNBurnEvent>) + - [func \(r \*WZCNBurnEvent\) Data\(\) interface\{\}](<#WZCNBurnEvent.Data>) + - [func \(r \*WZCNBurnEvent\) Error\(\) error](<#WZCNBurnEvent.Error>) + - [func \(r \*WZCNBurnEvent\) GetAuthorizerID\(\) string](<#WZCNBurnEvent.GetAuthorizerID>) + - [func \(r \*WZCNBurnEvent\) SetAuthorizerID\(id string\)](<#WZCNBurnEvent.SetAuthorizerID>) -## Bridge owner SDK -**Deployer or Owner SDK** is required to Add or Remove Authorizers from `Authorizers Smart Contract` +## Constants + + + +```go +const ( + TenderlyProvider = iota + AlchemyProvider + UnknownProvider +) +``` + + + +```go +const ( + UniswapRouterAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D" + UsdcTokenAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + WethTokenAddress = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" +) +``` + + + +```go +const ( + EthereumWalletStorageDir = "wallets" +) +``` + +## Variables + + + +```go +var ( + DefaultClientIDEncoder = func(id string) []byte { + result, err := hex.DecodeString(id) + if err != nil { + Logger.Fatal(err) + } + return result + } +) +``` + + + +```go +var Logger logger.Logger +``` + + +## func [AccountExists]() + +```go +func AccountExists(homedir, address string) bool +``` -Configuration file: ```~/.zcn/owner.yaml``` to initialize owner +AccountExists checks if account exists -```yaml -owner: - # Address of Ethereum authorizers contract - AuthorizersAddress: "0xFE20Ce9fBe514397427d20C91CB657a4478A0FFa" - OwnerEthereumMnemonic: "add here the owner mnemonic that has deployed auth and bridge contracts" + +## func [ConfirmEthereumTransaction]() + +```go +func ConfirmEthereumTransaction(hash string, times int, duration time.Duration) (int, error) +``` + + + + +## func [ConvertIntToHex]() + +```go +func ConvertIntToHex(value int64) string +``` + +ConvertIntToHex converts given int value to hex string. + + +## func [CreateKeyStorage]() + +```go +func CreateKeyStorage(homedir, password string) error +``` + +CreateKeyStorage create, restore or unlock key storage + + +## func [DeleteAccount]() + +```go +func DeleteAccount(homedir, address string) bool +``` + +DeleteAccount deletes account from wallet + + +## func [EncodePackInt64]() + +```go +func EncodePackInt64(key string, param int64) common.Hash +``` + +EncodePackInt do abi.encodedPack\(string, int\), it is used for setting plan id for royalty + + +## func [GetAuthorizer]() + +```go +func GetAuthorizer(id string, cb zcncore.GetInfoCallback) (err error) ``` -Authorizes config: `~/.zcn/authorizers.yaml` to add authorizers +GetAuthorizer returned authorizer by ID -**Example:** + +## func [GetAuthorizers]() ```go -transaction, err := owner.AddEthereumAuthorizer(context.TODO(), wallet.Address) -if err != nil { - fmt.Println(err) +func GetAuthorizers(active bool, cb zcncore.GetInfoCallback) (err error) +``` + +GetAuthorizers Returns all or only active authorizers + + +## func [GetGlobalConfig]() + +```go +func GetGlobalConfig(cb zcncore.GetInfoCallback) (err error) +``` + +GetGlobalConfig Returns global config + + +## func [GetTransactionStatus]() + +```go +func GetTransactionStatus(hash string) (int, error) +``` + + + + +## func [ImportAccount]() + +```go +func ImportAccount(homedir, mnemonic, password string, accountAddrIndex ...AccountAddressIndex) (string, error) +``` + +ImportAccount imports account using mnemonic + + +## func [ListStorageAccounts]() + +```go +func ListStorageAccounts(homedir string) []common.Address +``` + +ListStorageAccounts List available accounts + + +## type [AccountAddressIndex]() + + + +```go +type AccountAddressIndex struct { + AccountIndex int + AddressIndex int + Bip32 bool } +``` + + +## type [AlchemyGasEstimationRequest]() + +AlchemyGasEstimationRequest describes request used for Alchemy enhanced JSON\-RPC API. + +```go +type AlchemyGasEstimationRequest struct { + From string `json:"from"` + To string `json:"to"` + Value string `json:"value"` + Data string `json:"data"` +} +``` -status, err := zcnbridge.ConfirmEthereumTransaction(transaction.Hash().String(), 5, time.Second*5) -if err != nil { - fmt.Println(err) + +## type [AuthorizerNode]() + + + +```go +type AuthorizerNode struct { + ID string `json:"id"` + URL string `json:"url"` } +``` + + +## type [AuthorizerNodesResponse]() + + +```go +type AuthorizerNodesResponse struct { + Nodes []*AuthorizerNode `json:"nodes"` +} ``` -## Client SDK + +## type [AuthorizerResponse]() + + + +```go +type AuthorizerResponse struct { + AuthorizerID string `json:"id"` + URL string `json:"url"` + + // Configuration + Fee common.Balance `json:"fee"` + + // Geolocation + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` -This SDK is used to execute mint and burn transaction on both chains, Ethereum and 0Chain + // Stats + LastHealthCheck int64 `json:"last_health_check"` -Configuration file: ```~/.zcn/bridge.yaml``` to initialize the client + // stake_pool_settings + DelegateWallet string `json:"delegate_wallet"` + MinStake common.Balance `json:"min_stake"` + MaxStake common.Balance `json:"max_stake"` + NumDelegates int `json:"num_delegates"` + ServiceCharge float64 `json:"service_charge"` +} +``` -Functionality: + +## type [BancorTokenDetails]() -- Burn (0Chain and Ethereum) -- Mint (0Chain and Ethereum) +BancorTokenDetails describes Bancor ZCN zcntoken pool details -For more detailed information please find documentation [here](https://github.com/0chain/0chain/blob/staging/code/go/0chain.net/smartcontract/zcnsc/README.MD) +```go +type BancorTokenDetails struct { + Data struct { + Rate struct { + ETH string `json:"eth"` + BNT string `json:"bnt"` + USDC string `json:"usd"` + EURC string `json:"eur"` + } + } `json:"data"` +} +``` + + +## type [BridgeClient]() + + + +```go +type BridgeClient struct { + BridgeAddress, + TokenAddress, + AuthorizersAddress, + UniswapAddress, + NFTConfigAddress, + EthereumAddress, + EthereumNodeURL, + Password string + + BancorAPIURL string + + ConsensusThreshold float64 + GasLimit uint64 + // contains filtered or unexported fields +} +``` + + +### func [NewBridgeClient]() + +```go +func NewBridgeClient(bridgeAddress, tokenAddress, authorizersAddress, uniswapAddress, ethereumAddress, ethereumNodeURL, password string, gasLimit uint64, consensusThreshold float64, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient +``` + +NewBridgeClient creates BridgeClient with the given parameters. + + +### func [SetupBridgeClientSDK]() + +```go +func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient +``` + +SetupBridgeClientSDK initializes new bridge client. Meant to be used from standalone application with 0chain SDK initialized. + + +### func \(\*BridgeClient\) [AddEthereumAuthorizer]() + +```go +func (b *BridgeClient) AddEthereumAuthorizer(ctx context.Context, address common.Address) (*types.Transaction, error) +``` + +AddEthereumAuthorizer Adds authorizer to Ethereum bridge. Only contract deployer can call this method + + +### func \(\*BridgeClient\) [AddEthereumAuthorizers]() + +```go +func (b *BridgeClient) AddEthereumAuthorizers(configDir string) +``` + + + + +### func \(\*BridgeClient\) [ApproveUSDCSwap]() + +```go +func (b *BridgeClient) ApproveUSDCSwap(ctx context.Context, source uint64) (*types.Transaction, error) +``` + +ApproveUSDCSwap provides opportunity to approve swap operation for ERC20 tokens + + +### func \(\*BridgeClient\) [BurnWZCN]() + +```go +func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*types.Transaction, error) +``` + +BurnWZCN Burns WZCN tokens on behalf of the 0ZCN client amountTokens \- ZCN tokens clientID \- 0ZCN client ERC20 signature: "burn\(uint256,bytes\)" + + +### func \(\*BridgeClient\) [BurnZCN]() + +```go +func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (transaction.Transaction, error) +``` + +BurnZCN burns ZCN tokens before conversion from ZCN to WZCN as a first step + + +### func \(\*BridgeClient\) [CreateSignedTransactionFromKeyStore]() + +```go +func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient, gasLimitUnits uint64) *bind.TransactOpts +``` + + + + +### func \(\*BridgeClient\) [EstimateBurnWZCNGasAmount]() + +```go +func (b *BridgeClient) EstimateBurnWZCNGasAmount(ctx context.Context, from, to, amountTokens string) (float64, error) +``` + +EstimateBurnWZCNGasAmount performs gas amount estimation for the given wzcn burn transaction. + + +### func \(\*BridgeClient\) [EstimateGasPrice]() + +```go +func (b *BridgeClient) EstimateGasPrice(ctx context.Context) (float64, error) +``` + +EstimateGasPrice performs gas estimation for the given transaction. + + +### func \(\*BridgeClient\) [EstimateMintWZCNGasAmount]() + +```go +func (b *BridgeClient) EstimateMintWZCNGasAmount(ctx context.Context, from, to, zcnTransactionRaw, amountToken string, nonceRaw int64, signaturesRaw [][]byte) (float64, error) +``` + +EstimateMintWZCNGasAmount performs gas amount estimation for the given wzcn mint transaction. + + +### func \(\*BridgeClient\) [GetETHSwapAmount]() + +```go +func (b *BridgeClient) GetETHSwapAmount(ctx context.Context, source uint64) (*big.Int, error) +``` + +GetETHSwapAmount retrieves ETH swap amount from the given source. + + +### func \(\*BridgeClient\) [GetTokenBalance]() + +```go +func (b *BridgeClient) GetTokenBalance() (*big.Int, error) +``` + +GetTokenBalance returns balance of the current client for the zcntoken address + + +### func \(\*BridgeClient\) [GetUserNonceMinted]() + +```go +func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddress string) (*big.Int, error) +``` + +GetUserNonceMinted Returns nonce for a specified Ethereum address + + +### func \(\*BridgeClient\) [IncreaseBurnerAllowance]() + +```go +func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmount uint64) (*types.Transaction, error) +``` + +IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer ERC\-20 tokens on behalf of the zcntoken owner to the Burn TokenPool During the burn the script transfers amount from zcntoken owner to the bridge burn zcntoken pool Example: owner wants to burn some amount. The contract will transfer some amount from owner address to the pool. So the owner must call IncreaseAllowance of the WZCN zcntoken with 2 parameters: spender address which is the bridge contract and amount to be burned \(transferred\) Token signature: "increaseApproval\(address,uint256\)" + + +### func \(\*BridgeClient\) [MintWZCN]() + +```go +func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPayload) (*types.Transaction, error) +``` + +MintWZCN Mint ZCN tokens on behalf of the 0ZCN client payload: received from authorizers + + +### func \(\*BridgeClient\) [MintZCN]() + +```go +func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) +``` + +MintZCN mints ZCN tokens after receiving proof\-of\-burn of WZCN tokens + + +### func \(\*BridgeClient\) [NFTConfigGetAddress]() + +```go +func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (string, string, error) +``` + + + + +### func \(\*BridgeClient\) [NFTConfigGetUint256]() + +```go +func (b *BridgeClient) NFTConfigGetUint256(ctx context.Context, key string, keyParam ...int64) (string, int64, error) +``` + + + + +### func \(\*BridgeClient\) [NFTConfigSetAddress]() + +```go +func (b *BridgeClient) NFTConfigSetAddress(ctx context.Context, key, address string) (*types.Transaction, error) +``` + + + + +### func \(\*BridgeClient\) [NFTConfigSetUint256]() + +```go +func (b *BridgeClient) NFTConfigSetUint256(ctx context.Context, key string, value int64) (*types.Transaction, error) +``` + +NFTConfigSetUint256 call setUint256 method of NFTConfig contract + + +### func \(\*BridgeClient\) [NFTConfigSetUint256Raw]() + +```go +func (b *BridgeClient) NFTConfigSetUint256Raw(ctx context.Context, key common.Hash, value int64) (*types.Transaction, error) +``` + + + + +### func \(\*BridgeClient\) [QueryEthereumBurnEvents]() + +```go +func (b *BridgeClient) QueryEthereumBurnEvents(startNonce string) ([]*ethereum.BurnEvent, error) +``` + +QueryEthereumBurnEvents gets ethereum burn events + + +### func \(\*BridgeClient\) [QueryEthereumMintPayload]() + +```go +func (b *BridgeClient) QueryEthereumMintPayload(zchainBurnHash string) (*ethereum.MintPayload, error) +``` + +QueryEthereumMintPayload gets burn ticket and creates mint payload to be minted in the Ethereum chain zchainBurnHash \- Ethereum burn transaction hash + + +### func \(\*BridgeClient\) [QueryZChainMintPayload]() + +```go +func (b *BridgeClient) QueryZChainMintPayload(ethBurnHash string) (*zcnsc.MintPayload, error) +``` + +QueryZChainMintPayload gets burn ticket and creates mint payload to be minted in the ZChain ethBurnHash \- Ethereum burn transaction hash + + +### func \(\*BridgeClient\) [RemoveEthereumAuthorizer]() + +```go +func (b *BridgeClient) RemoveEthereumAuthorizer(ctx context.Context, address common.Address) (*types.Transaction, error) +``` + +RemoveEthereumAuthorizer Removes authorizer from Ethereum bridge. Only contract deployer can call this method + + +### func \(\*BridgeClient\) [ResetUserNonceMinted]() + +```go +func (b *BridgeClient) ResetUserNonceMinted(ctx context.Context) (*types.Transaction, error) +``` + +ResetUserNonceMinted Resets nonce for a specified Ethereum address + + +### func \(\*BridgeClient\) [SignWithEthereumChain]() + +```go +func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) +``` + +SignWithEthereumChain signs the digest with Ethereum chain signer taking key from the current user key storage + + +### func \(\*BridgeClient\) [SwapETH]() + +```go +func (b *BridgeClient) SwapETH(ctx context.Context, source uint64, target uint64) (*types.Transaction, error) +``` + +SwapETH provides opportunity to perform zcn token swap operation using ETH as source token. + + +### func \(\*BridgeClient\) [SwapUSDC]() + +```go +func (b *BridgeClient) SwapUSDC(ctx context.Context, source uint64, target uint64) (*types.Transaction, error) +``` + +SwapUSDC provides opportunity to perform zcn token swap operation using USDC as source token. + + +### func \(\*BridgeClient\) [VerifyZCNTransaction]() + +```go +func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (transaction.Transaction, error) +``` + +VerifyZCNTransaction verifies 0CHain transaction + + +## type [BridgeSDKConfig]() + + + +```go +type BridgeSDKConfig struct { + LogLevel *string + LogPath *string + ConfigChainFile *string + ConfigDir *string + Development *bool +} +``` + + +## type [DetailedAccount]() + +DetailedAccount describes detailed account + +```go +type DetailedAccount struct { + EthereumAddress, + PublicKey, + PrivateKey accounts.Account +} +``` + + +## type [EthereumBurnEvents]() + +EthereumBurnEvents represents burn events returned by authorizers + +```go +type EthereumBurnEvents struct { + AuthorizerID string `json:"authorizer_id,omitempty"` + BurnEvents []struct { + Nonce int64 `json:"nonce"` + Amount int64 `json:"amount"` + TransactionHash string `json:"transaction_hash"` + } `json:"burn_events"` +} +``` + + +### func \(\*EthereumBurnEvents\) [Data]() + +```go +func (r *EthereumBurnEvents) Data() interface{} +``` + + + + +### func \(\*EthereumBurnEvents\) [Error]() + +```go +func (r *EthereumBurnEvents) Error() error +``` + + + + +### func \(\*EthereumBurnEvents\) [GetAuthorizerID]() + +```go +func (r *EthereumBurnEvents) GetAuthorizerID() string +``` + + + + +### func \(\*EthereumBurnEvents\) [SetAuthorizerID]() + +```go +func (r *EthereumBurnEvents) SetAuthorizerID(id string) +``` + + + + +## type [EthereumClient]() + +EthereumClient describes Ethereum JSON\-RPC client generealized interface + +```go +type EthereumClient interface { + bind.ContractBackend + + ChainID(ctx context.Context) (*big.Int, error) +} +``` + + +## type [GasEstimationRequest]() + +GasEstimationRequest describes request used for Alchemy enhanced JSON\-RPC API. + +```go +type GasEstimationRequest struct { + From string `json:"from"` + To string `json:"to"` + Value string `json:"value"` +} +``` + + +## type [GasPriceEstimationResult]() + +GasPriceEstimationResult represents result of the gas price estimation operation execution. + +```go +type GasPriceEstimationResult struct { + Value float64 `json:"value"` +} +``` + + +## type [JobError]() + +JobError result of internal request wrapped in authorizer job + +```go +type JobError struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*JobError\) [MarshalJSON]() + +```go +func (e *JobError) MarshalJSON() ([]byte, error) +``` + + + + +### func \(\*JobError\) [UnmarshalJSON]() + +```go +func (e *JobError) UnmarshalJSON(buf []byte) error +``` + + + + +## type [JobResult]() + +JobResult = Authorizer task result, it wraps actual result of the query inside authorizer + +```go +type JobResult interface { + // Error = Status of Authorizer job on authorizer server + Error() error + // Data returns the actual result + Data() interface{} + // SetAuthorizerID Assigns authorizer ID to the Job + SetAuthorizerID(ID string) + // GetAuthorizerID returns authorizer ID + GetAuthorizerID() string +} +``` + + +## type [JobStatus]() + +JobStatus = Ethereum transaction status + +```go +type JobStatus uint +``` + + +## type [KeyStore]() + +KeyStore is a wrapper, which exposes Ethereum KeyStore methods used by DEX bridge. + +```go +type KeyStore interface { + Find(accounts.Account) (accounts.Account, error) + TimedUnlock(accounts.Account, string, time.Duration) error + SignHash(account accounts.Account, hash []byte) ([]byte, error) + GetEthereumKeyStore() *keystore.KeyStore +} +``` + + +### func [NewKeyStore]() + +```go +func NewKeyStore(path string) KeyStore +``` + +NewKeyStore creates new KeyStore wrapper instance + + +## type [ProofEthereumBurn]() + +ProofEthereumBurn Authorizer returns this type for Ethereum transaction + +```go +type ProofEthereumBurn struct { + TxnID string `json:"ethereum_txn_id"` + Nonce int64 `json:"nonce"` + Amount int64 `json:"amount"` + ReceivingClientID string `json:"receiving_client_id"` // 0ZCN address + Signature string `json:"signature"` +} +``` + + +## type [ProofZCNBurn]() + +ProofZCNBurn Authorizer returns this type for ZCN transaction + +```go +type ProofZCNBurn struct { + AuthorizerID string `json:"authorizer_id,omitempty"` + TxnID string `json:"0chain_txn_id"` + To string `json:"to"` + Nonce int64 `json:"nonce"` + Amount int64 `json:"amount"` + Signature []byte `json:"signature"` +} +``` + + +### func \(\*ProofZCNBurn\) [Data]() + +```go +func (r *ProofZCNBurn) Data() interface{} +``` + + + + +### func \(\*ProofZCNBurn\) [Error]() + +```go +func (r *ProofZCNBurn) Error() error +``` + + + + +### func \(\*ProofZCNBurn\) [GetAuthorizerID]() + +```go +func (r *ProofZCNBurn) GetAuthorizerID() string +``` + + + + +### func \(\*ProofZCNBurn\) [SetAuthorizerID]() + +```go +func (r *ProofZCNBurn) SetAuthorizerID(id string) +``` + + + + +## type [WZCNBurnEvent]() + +WZCNBurnEvent returned from burn ticket handler of: /v1/ether/burnticket/get + +```go +type WZCNBurnEvent struct { + // AuthorizerID Authorizer ID + AuthorizerID string `json:"authorizer_id,omitempty"` + // BurnTicket Returns burn ticket + BurnTicket *ProofEthereumBurn `json:"ticket,omitempty"` + // Err gives error of job on server side + Err *JobError `json:"err,omitempty"` + // Status gives job status on server side (authoriser) + Status JobStatus `json:"status,omitempty"` +} +``` + + +### func \(\*WZCNBurnEvent\) [Data]() + +```go +func (r *WZCNBurnEvent) Data() interface{} +``` + + + + +### func \(\*WZCNBurnEvent\) [Error]() + +```go +func (r *WZCNBurnEvent) Error() error +``` + + + + +### func \(\*WZCNBurnEvent\) [GetAuthorizerID]() + +```go +func (r *WZCNBurnEvent) GetAuthorizerID() string +``` + + + + +### func \(\*WZCNBurnEvent\) [SetAuthorizerID]() + +```go +func (r *WZCNBurnEvent) SetAuthorizerID(id string) +``` -## Token Bridge SDK -Functionality: -1. Used by token bridge to sign payloads for 0Chain and Ethereum chains -2. Checks transactions status and give the client payload to +Generated by [gomarkdoc]() diff --git a/zcnbridge/authorizer/doc.go b/zcnbridge/authorizer/doc.go new file mode 100644 index 000000000..1f6be900b --- /dev/null +++ b/zcnbridge/authorizer/doc.go @@ -0,0 +1,3 @@ +// Methods and types to interact with the authorizer nodes. +// Authorizer nodes are the nodes that authorize the burn operations, whether on to be able to perform corresponding mint operations. +package authorizer \ No newline at end of file diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 6929ce8a1..3cbf6b866 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -4,12 +4,13 @@ import ( "context" "encoding/hex" "fmt" - "github.com/0chain/gosdk/zcnbridge/ethereum/uniswapnetwork" - "github.com/0chain/gosdk/zcnbridge/ethereum/uniswaprouter" "math/big" "strings" "time" + "github.com/0chain/gosdk/zcnbridge/ethereum/uniswapnetwork" + "github.com/0chain/gosdk/zcnbridge/ethereum/uniswaprouter" + "github.com/ybbus/jsonrpc/v3" "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" @@ -67,6 +68,9 @@ var ( } ) +// CreateSignedTransactionFromKeyStore creates signed transaction from key store +// - client - Ethereum client +// - gasLimitUnits - gas limit in units func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient, gasLimitUnits uint64) *bind.TransactOpts { var ( signerAddress = common.HexToAddress(b.EthereumAddress) @@ -115,6 +119,8 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient } // AddEthereumAuthorizer Adds authorizer to Ethereum bridge. Only contract deployer can call this method +// - ctx go context instance to run the transaction +// - address Ethereum address of the authorizer func (b *BridgeClient) AddEthereumAuthorizer(ctx context.Context, address common.Address) (*types.Transaction, error) { instance, transactOpts, err := b.prepareAuthorizers(ctx, "addAuthorizers", address) if err != nil { @@ -131,6 +137,8 @@ func (b *BridgeClient) AddEthereumAuthorizer(ctx context.Context, address common } // RemoveEthereumAuthorizer Removes authorizer from Ethereum bridge. Only contract deployer can call this method +// - ctx go context instance to run the transaction +// - address Ethereum address of the authorizer func (b *BridgeClient) RemoveEthereumAuthorizer(ctx context.Context, address common.Address) (*types.Transaction, error) { instance, transactOpts, err := b.prepareAuthorizers(ctx, "removeAuthorizers", address) if err != nil { @@ -146,6 +154,8 @@ func (b *BridgeClient) RemoveEthereumAuthorizer(ctx context.Context, address com return tran, err } +// AddEthereumAuthorizers add bridge authorizers to the Ethereum authorizers contract +// - configDir - configuration directory func (b *BridgeClient) AddEthereumAuthorizers(configDir string) { cfg := viper.New() cfg.AddConfigPath(configDir) @@ -233,6 +243,8 @@ func (b *BridgeClient) prepareNFTConfig(ctx context.Context, method string, para } // EncodePackInt do abi.encodedPack(string, int), it is used for setting plan id for royalty +// - key key for the plan +// - param plan id func EncodePackInt64(key string, param int64) common.Hash { return crypto.Keccak256Hash( []byte(key), @@ -240,12 +252,19 @@ func EncodePackInt64(key string, param int64) common.Hash { ) } -// NFTConfigSetUint256 call setUint256 method of NFTConfig contract +// NFTConfigSetUint256 sets a uint256 field in the NFT config, given the key as a string +// - ctx go context instance to run the transaction +// - key key for this field +// - value value to set func (b *BridgeClient) NFTConfigSetUint256(ctx context.Context, key string, value int64) (*types.Transaction, error) { kkey := crypto.Keccak256Hash([]byte(key)) return b.NFTConfigSetUint256Raw(ctx, kkey, value) } +// NFTConfigSetUint256Raw sets a uint256 field in the NFT config, given the key as a Keccak256 hash +// - ctx go context instance to run the transaction +// - key key for this field (hased) +// - value value to set func (b *BridgeClient) NFTConfigSetUint256Raw(ctx context.Context, key common.Hash, value int64) (*types.Transaction, error) { if value < 0 { return nil, errors.New("value must be greater than zero") @@ -267,6 +286,10 @@ func (b *BridgeClient) NFTConfigSetUint256Raw(ctx context.Context, key common.Ha return tran, err } +// NFTConfigGetUint256 retrieves a uint256 field in the NFT config, given the key as a string +// - ctx go context instance to run the transaction +// - key key for this field +// - keyParam additional key parameter, only the first item is used func (b *BridgeClient) NFTConfigGetUint256(ctx context.Context, key string, keyParam ...int64) (string, int64, error) { kkey := crypto.Keccak256Hash([]byte(key)) if len(keyParam) > 0 { @@ -289,6 +312,10 @@ func (b *BridgeClient) NFTConfigGetUint256(ctx context.Context, key string, keyP return kkey.String(), v.Int64(), err } +// NFTConfigSetAddress sets an address field in the NFT config, given the key as a string +// - ctx go context instance to run the transaction +// - key key for this field +// - address address to set func (b *BridgeClient) NFTConfigSetAddress(ctx context.Context, key, address string) (*types.Transaction, error) { kkey := crypto.Keccak256Hash([]byte(key)) // return b.NFTConfigSetAddress(ctx, kkey, address) @@ -312,6 +339,9 @@ func (b *BridgeClient) NFTConfigSetAddress(ctx context.Context, key, address str return tran, err } +// NFTConfigGetAddress retrieves an address field in the NFT config, given the key as a string +// - ctx go context instance to run the transaction +// - key key for this field func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (string, string, error) { kkey := crypto.Keccak256Hash([]byte(key)) @@ -339,6 +369,8 @@ func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (str // So the owner must call IncreaseAllowance of the WZCN zcntoken with 2 parameters: // spender address which is the bridge contract and amount to be burned (transferred) // Token signature: "increaseApproval(address,uint256)" +// - ctx go context instance to run the transaction +// - allowanceAmount amount to increase // //nolint:funlen func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmount uint64) (*types.Transaction, error) { @@ -411,11 +443,14 @@ func (b *BridgeClient) GetTokenBalance() (*big.Int, error) { } // VerifyZCNTransaction verifies 0CHain transaction +// - ctx go context instance to run the transaction +// - hash transaction hash func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (transaction.Transaction, error) { return transaction.Verify(ctx, hash) } // SignWithEthereumChain signs the digest with Ethereum chain signer taking key from the current user key storage +// - message message to sign func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { hash := crypto.Keccak256Hash([]byte(message)) @@ -441,6 +476,8 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { } // GetUserNonceMinted Returns nonce for a specified Ethereum address +// - ctx go context instance to run the transaction +// - rawEthereumAddress Ethereum address func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddress string) (*big.Int, error) { ethereumAddress := common.HexToAddress(rawEthereumAddress) @@ -464,6 +501,7 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres } // ResetUserNonceMinted Resets nonce for a specified Ethereum address +// - ctx go context instance to run the transaction func (b *BridgeClient) ResetUserNonceMinted(ctx context.Context) (*types.Transaction, error) { bridgeInstance, transactOpts, err := b.prepareBridge(ctx, b.EthereumAddress, "resetUserNonceMinted") if err != nil { @@ -486,7 +524,10 @@ func (b *BridgeClient) ResetUserNonceMinted(ctx context.Context) (*types.Transac } // MintWZCN Mint ZCN tokens on behalf of the 0ZCN client -// payload: received from authorizers +// - ctx go context instance to run the transaction +// - payload received from authorizers +// +// ERC20 signature: "mint(address,uint256,bytes,uint256,bytes[])" func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPayload) (*types.Transaction, error) { if DefaultClientIDEncoder == nil { return nil, errors.New("DefaultClientIDEncoder must be setup") @@ -545,8 +586,9 @@ func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPaylo } // BurnWZCN Burns WZCN tokens on behalf of the 0ZCN client -// amountTokens - ZCN tokens -// clientID - 0ZCN client +// - ctx go context instance to run the transaction +// - amountTokens amount of tokens to burn +// // ERC20 signature: "burn(uint256,bytes)" func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*types.Transaction, error) { if DefaultClientIDEncoder == nil { @@ -586,6 +628,8 @@ func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*type } // MintZCN mints ZCN tokens after receiving proof-of-burn of WZCN tokens +// - ctx go context instance to run the transaction +// - payload received from authorizers func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) { trx, err := b.transactionProvider.NewTransactionEntity(0) if err != nil { @@ -618,6 +662,9 @@ func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) } // BurnZCN burns ZCN tokens before conversion from ZCN to WZCN as a first step +// - ctx go context instance to run the transaction +// - amount amount of tokens to burn +// - txnfee transaction fee func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (transaction.Transaction, error) { payload := zcnsc.BurnPayload{ EthereumAddress: b.EthereumAddress, @@ -665,6 +712,8 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran } // ApproveUSDCSwap provides opportunity to approve swap operation for ERC20 tokens +// - ctx go context instance to run the transaction +// - source source amount func (b *BridgeClient) ApproveUSDCSwap(ctx context.Context, source uint64) (*types.Transaction, error) { // 1. USDC token smart contract address tokenAddress := common.HexToAddress(UsdcTokenAddress) @@ -698,6 +747,8 @@ func (b *BridgeClient) ApproveUSDCSwap(ctx context.Context, source uint64) (*typ } // GetETHSwapAmount retrieves ETH swap amount from the given source. +// - ctx go context instance to run the transaction +// - source source amount func (b *BridgeClient) GetETHSwapAmount(ctx context.Context, source uint64) (*big.Int, error) { // 1. Uniswap smart contract address contractAddress := common.HexToAddress(UniswapRouterAddress) @@ -736,6 +787,9 @@ func (b *BridgeClient) GetETHSwapAmount(ctx context.Context, source uint64) (*bi } // SwapETH provides opportunity to perform zcn token swap operation using ETH as source token. +// - ctx go context instance to run the transaction +// - source source amount +// - target target amount func (b *BridgeClient) SwapETH(ctx context.Context, source uint64, target uint64) (*types.Transaction, error) { // 1. Swap source amount parameter. sourceInt := big.NewInt(int64(source)) @@ -765,6 +819,9 @@ func (b *BridgeClient) SwapETH(ctx context.Context, source uint64, target uint64 } // SwapUSDC provides opportunity to perform zcn token swap operation using USDC as source token. +// - ctx go context instance to run the transaction +// - source source amount +// - target target amount func (b *BridgeClient) SwapUSDC(ctx context.Context, source uint64, target uint64) (*types.Transaction, error) { // 1. Swap target amount parameter. sourceInt := big.NewInt(int64(source)) @@ -1010,6 +1067,10 @@ func (b *BridgeClient) estimateAlchemyGasAmount(ctx context.Context, from, to, d } // EstimateBurnWZCNGasAmount performs gas amount estimation for the given wzcn burn transaction. +// - ctx go context instance to run the transaction +// - from source address +// - to target address +// - amountTokens amount of tokens to burn func (b *BridgeClient) EstimateBurnWZCNGasAmount(ctx context.Context, from, to, amountTokens string) (float64, error) { switch b.getProviderType() { case AlchemyProvider: @@ -1040,6 +1101,13 @@ func (b *BridgeClient) EstimateBurnWZCNGasAmount(ctx context.Context, from, to, } // EstimateMintWZCNGasAmount performs gas amount estimation for the given wzcn mint transaction. +// - ctx go context instance to run the transaction +// - from source address +// - to target address +// - zcnTransactionRaw zcn transaction (hashed) +// - amountToken amount of tokens to mint +// - nonceRaw nonce +// - signaturesRaw authorizer signatures func (b *BridgeClient) EstimateMintWZCNGasAmount( ctx context.Context, from, to, zcnTransactionRaw, amountToken string, nonceRaw int64, signaturesRaw [][]byte) (float64, error) { switch b.getProviderType() { @@ -1108,6 +1176,7 @@ func (b *BridgeClient) estimateAlchemyGasPrice(ctx context.Context) (float64, er } // EstimateGasPrice performs gas estimation for the given transaction. +// - ctx go context instance to run the transaction func (b *BridgeClient) EstimateGasPrice(ctx context.Context) (float64, error) { switch b.getProviderType() { case AlchemyProvider: diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go index 8ffb69dcc..724b2d4e4 100644 --- a/zcnbridge/bridge_helper.go +++ b/zcnbridge/bridge_helper.go @@ -51,6 +51,10 @@ func GetTransactionStatus(hash string) (int, error) { return zcncore.CheckEthHashStatus(hash), nil } +// ConfirmEthereumTransaction confirms Ethereum transaction by hash. +// - hash is the transaction hash to confirm. +// - times is the number of times to try confirming the transaction. +// - duration is the duration to wait between each confirmation attempt. func ConfirmEthereumTransaction(hash string, times int, duration time.Duration) (int, error) { var ( res = 0 diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 15134dde7..09bae207a 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -31,6 +31,7 @@ const ( WethTokenAddress = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" ) +// BridgeSDKConfig describes the configuration for the bridge SDK. type BridgeSDKConfig struct { LogLevel *string LogPath *string @@ -46,6 +47,7 @@ type EthereumClient interface { ChainID(ctx context.Context) (*big.Int, error) } +// BridgeClient is a wrapper, which exposes Ethereum KeyStore methods used by DEX bridge. type BridgeClient struct { keyStore KeyStore transactionProvider transaction.TransactionProvider @@ -67,6 +69,19 @@ type BridgeClient struct { } // NewBridgeClient creates BridgeClient with the given parameters. +// - bridgeAddress is the address of the bridge smart contract on the Ethereum network. +// - tokenAddress is the address of the token smart contract on the Ethereum network. +// - authorizersAddress is the address of the authorizers smart contract on the Ethereum network. +// - authorizersAddress is the address of the authorizers smart contract on the Ethereum network. +// - uniswapAddress is the address of the user's ethereum wallet (on UniSwap). +// - ethereumAddress is the address of the user's ethereum wallet. +// - ethereumNodeURL is the URL of the Ethereum node. +// - password is the password for the user's ethereum wallet. +// - gasLimit is the gas limit for the transactions. +// - consensusThreshold is the consensus threshold, the minimum percentage of authorizers that need to agree on a transaction. +// - ethereumClient is the Ethereum JSON-RPC client. +// - transactionProvider provider interface for the transaction entity. +// - keyStore is the Ethereum KeyStore instance. func NewBridgeClient( bridgeAddress, tokenAddress, @@ -120,6 +135,7 @@ func readConfig(sdkConfig *BridgeSDKConfig, getConfigName func() string) *viper. // SetupBridgeClientSDK initializes new bridge client. // Meant to be used from standalone application with 0chain SDK initialized. +// - cfg is the configuration for the bridge SDK. func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { log.InitLogging(*cfg.Development, *cfg.LogPath, *cfg.LogLevel) diff --git a/zcnbridge/crypto/hash.go b/zcnbridge/crypto/hash.go index 9806762ff..de4dc4304 100644 --- a/zcnbridge/crypto/hash.go +++ b/zcnbridge/crypto/hash.go @@ -1,3 +1,4 @@ +// Methods and types to support cryptographic operations. package crypto import ( diff --git a/zcnbridge/doc.go b/zcnbridge/doc.go new file mode 100644 index 000000000..241d25f3d --- /dev/null +++ b/zcnbridge/doc.go @@ -0,0 +1,4 @@ +// Methods and types to interact with the Bridge protocol. +// Bridge protocol defines how clients can exchange tokens between 0chain and Ethereum blockchains. +// It defines the functionality to Mint/Burn native or ERC20 Züs tokens. +package zcnbridge \ No newline at end of file diff --git a/zcnbridge/errors/errors.go b/zcnbridge/errors/errors.go index e556ccd38..2737754ee 100644 --- a/zcnbridge/errors/errors.go +++ b/zcnbridge/errors/errors.go @@ -1,3 +1,4 @@ +// Error struct and functions. package errors import ( @@ -68,8 +69,9 @@ func ExitMsg(text string, code int) { os.Exit(code) } -// Is wraps function errors.Is from stdlib to avoid import it -// in other places of the magma smart contract (magmasc) package. +// Is checks if error is equal to target error. +// - err: error to check +// - target: target error to compare func Is(err, target error) bool { return errors.Is(err, target) } @@ -94,6 +96,9 @@ func (err *Error) Error() string { return fmt.Sprintf("%s: %s", err.Code, err.Msg) } +// NewError create a new error instance given a code and a message. +// - code: error code +// - msg: error message func NewError(code string, msg string) *Error { return &Error{Code: code, Msg: msg} } diff --git a/zcnbridge/ethereum/doc.go b/zcnbridge/ethereum/doc.go new file mode 100644 index 000000000..7e2f0203a --- /dev/null +++ b/zcnbridge/ethereum/doc.go @@ -0,0 +1,3 @@ +// Methods and types to interact with Züs smart contracts on the Ethereum blockchain (Züs ERC20 tokens). +// All sub-packages are autogenerated. +package ethereum diff --git a/zcnbridge/http/doc.go b/zcnbridge/http/doc.go new file mode 100644 index 000000000..fd578c520 --- /dev/null +++ b/zcnbridge/http/doc.go @@ -0,0 +1,2 @@ +// Utility methods and types to work with HTTP requests and responses. +package http \ No newline at end of file diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 101662b59..4794681ce 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -59,6 +59,7 @@ func (k *keyStore) GetEthereumKeyStore() *keystore.KeyStore { } // ListStorageAccounts List available accounts +// - homedir is the home directory func ListStorageAccounts(homedir string) []common.Address { keyDir := path.Join(homedir, EthereumWalletStorageDir) ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) @@ -70,6 +71,8 @@ func ListStorageAccounts(homedir string) []common.Address { } // DeleteAccount deletes account from wallet +// - homedir is the home directory +// - address is the account address func DeleteAccount(homedir, address string) bool { keyDir := path.Join(homedir, EthereumWalletStorageDir) ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) @@ -89,6 +92,8 @@ func DeleteAccount(homedir, address string) bool { } // AccountExists checks if account exists +// - homedir is the home directory +// - address is the account address func AccountExists(homedir, address string) bool { keyDir := path.Join(homedir, EthereumWalletStorageDir) ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) @@ -113,6 +118,8 @@ func AccountExists(homedir, address string) bool { } // CreateKeyStorage create, restore or unlock key storage +// - homedir is the home directory +// - password is the password func CreateKeyStorage(homedir, password string) error { keyDir := path.Join(homedir, EthereumWalletStorageDir) ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) @@ -125,13 +132,20 @@ func CreateKeyStorage(homedir, password string) error { return nil } +// AccountAddressIndex represents client account and address indexes for multi-key wallet. Used to derive ethereum account. type AccountAddressIndex struct { AccountIndex int AddressIndex int - Bip32 bool + + // Bip32 flag indicates if the account is derived using BIP32 derivation path. + Bip32 bool } // ImportAccount imports account using mnemonic +// - homedir is the home directory +// - mnemonic is the mnemonic phrase +// - password is the password +// - accountAddrIndex is the account and address indexes used for the derivation of the ethereum account func ImportAccount(homedir, mnemonic, password string, accountAddrIndex ...AccountAddressIndex) (string, error) { // 1. Create storage and account if it doesn't exist and add account to it diff --git a/zcnbridge/log/doc.go b/zcnbridge/log/doc.go new file mode 100644 index 000000000..dee00abe6 --- /dev/null +++ b/zcnbridge/log/doc.go @@ -0,0 +1,2 @@ +// Logging methods and types for the ZCN bridge SDK. +package log \ No newline at end of file diff --git a/zcnbridge/mocks/doc.go b/zcnbridge/mocks/doc.go new file mode 100644 index 000000000..d5f5048fa --- /dev/null +++ b/zcnbridge/mocks/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! Do not use. +package mocks \ No newline at end of file diff --git a/zcnbridge/rest.go b/zcnbridge/rest.go index 44751ed71..866d9beb5 100644 --- a/zcnbridge/rest.go +++ b/zcnbridge/rest.go @@ -12,6 +12,7 @@ import ( // Models +// AuthorizerResponse represents the response of the request to get authorizer info from the sharders. type AuthorizerResponse struct { AuthorizerID string `json:"id"` URL string `json:"url"` @@ -34,10 +35,12 @@ type AuthorizerResponse struct { ServiceCharge float64 `json:"service_charge"` } +// AuthorizerNodesResponse represents the response of the request to get authorizers type AuthorizerNodesResponse struct { Nodes []*AuthorizerNode `json:"nodes"` } +// AuthorizerNode represents an authorizer node type AuthorizerNode struct { ID string `json:"id"` URL string `json:"url"` @@ -71,7 +74,9 @@ func getAuthorizers(active bool) ([]*AuthorizerNode, error) { return authorizers.Nodes, nil } -// GetAuthorizer returned authorizer by ID +// GetAuthorizer returned authorizer information from Züs Blockchain by the ID +// - id is the authorizer ID +// - cb is the callback function to handle the response asynchronously func GetAuthorizer(id string, cb zcncore.GetInfoCallback) (err error) { err = zcncore.CheckConfig() if err != nil { @@ -91,6 +96,8 @@ func GetAuthorizer(id string, cb zcncore.GetInfoCallback) (err error) { } // GetAuthorizers Returns all or only active authorizers +// - active is the flag to get only active authorizers +// - cb is the callback function to handle the response asynchronously func GetAuthorizers(active bool, cb zcncore.GetInfoCallback) (err error) { err = zcncore.CheckConfig() if err != nil { @@ -101,6 +108,7 @@ func GetAuthorizers(active bool, cb zcncore.GetInfoCallback) (err error) { } // GetGlobalConfig Returns global config +// - cb is the callback function to handle the response asynchronously func GetGlobalConfig(cb zcncore.GetInfoCallback) (err error) { err = zcncore.CheckConfig() if err != nil { diff --git a/zcnbridge/time/doc.go b/zcnbridge/time/doc.go new file mode 100644 index 000000000..2feb4fd7d --- /dev/null +++ b/zcnbridge/time/doc.go @@ -0,0 +1,2 @@ +// Utility functions to handle the time. +package time diff --git a/zcnbridge/transaction/doc.go b/zcnbridge/transaction/doc.go new file mode 100644 index 000000000..7c7450aee --- /dev/null +++ b/zcnbridge/transaction/doc.go @@ -0,0 +1,2 @@ +// Methods and types to interact with native Züs transactions. +package transaction \ No newline at end of file diff --git a/zcnbridge/transaction/functions.go b/zcnbridge/transaction/functions.go index bf9845645..07d803e36 100644 --- a/zcnbridge/transaction/functions.go +++ b/zcnbridge/transaction/functions.go @@ -8,6 +8,9 @@ import ( "github.com/0chain/gosdk/zcncore" ) +// AddAuthorizer adds authorizer to the bridge +// - ctx is the context of the request. +// - input is the payload of the request. func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { @@ -32,6 +35,9 @@ func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (Tr return t, nil } +// AuthorizerHealthCheck performs health check of the authorizer +// - ctx is the context of the request. +// - input is the payload of the request. func AuthorizerHealthCheck(ctx context.Context, input *zcncore.AuthorizerHealthCheckPayload) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { diff --git a/zcnbridge/transaction/mocks/doc.go b/zcnbridge/transaction/mocks/doc.go new file mode 100644 index 000000000..d5f5048fa --- /dev/null +++ b/zcnbridge/transaction/mocks/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! Do not use. +package mocks \ No newline at end of file diff --git a/zcnbridge/utils/convert.go b/zcnbridge/utils/convert.go index 0dad0ad82..a3bf4d776 100644 --- a/zcnbridge/utils/convert.go +++ b/zcnbridge/utils/convert.go @@ -1,3 +1,4 @@ +// Miscellaneous utility functions. package utils import ( diff --git a/zcnbridge/wallet/doc.go b/zcnbridge/wallet/doc.go new file mode 100644 index 000000000..ca7daf1aa --- /dev/null +++ b/zcnbridge/wallet/doc.go @@ -0,0 +1,2 @@ +// Methods and types to represent client's wallet. +package wallet \ No newline at end of file diff --git a/zcnbridge/wallet/status.go b/zcnbridge/wallet/status.go index 48dbef449..df9b8306f 100644 --- a/zcnbridge/wallet/status.go +++ b/zcnbridge/wallet/status.go @@ -11,6 +11,7 @@ import ( "github.com/0chain/gosdk/zcncore" ) +// ZCNStatus represents the status of a ZCN operation. type ZCNStatus struct { walletString string balance int64 @@ -20,6 +21,8 @@ type ZCNStatus struct { Err error } +// NewZCNStatus creates a new ZCNStatus instance. +// - value: value to be stored in the ZCNStatus instance func NewZCNStatus(value interface{}) (zcns *ZCNStatus) { return &ZCNStatus{ Wg: new(sync.WaitGroup), @@ -27,15 +30,21 @@ func NewZCNStatus(value interface{}) (zcns *ZCNStatus) { } } +// Begin starts the wait group func (zcn *ZCNStatus) Begin() { zcn.Wg.Add(1) } +// Wait waits for the wait group to finish func (zcn *ZCNStatus) Wait() error { zcn.Wg.Wait() return zcn.Err } +// OnBalanceAvailable callback when balance is available +// - status: status of the operation +// - value: balance value +// - third parameter is not used, it is kept for compatibility func (zcn *ZCNStatus) OnBalanceAvailable(status int, value int64, _ string) { defer zcn.Wg.Done() if status == zcncore.StatusSuccess { @@ -46,6 +55,9 @@ func (zcn *ZCNStatus) OnBalanceAvailable(status int, value int64, _ string) { zcn.balance = value } +// OnTransactionComplete callback when a transaction is completed +// - t: transaction object +// - status: status of the transaction func (zcn *ZCNStatus) OnTransactionComplete(t *zcncore.Transaction, status int) { defer zcn.Wg.Done() if status == zcncore.StatusSuccess { @@ -55,6 +67,9 @@ func (zcn *ZCNStatus) OnTransactionComplete(t *zcncore.Transaction, status int) } } +// OnVerifyComplete callback when a transaction is verified +// - t: transaction object +// - status: status of the transaction func (zcn *ZCNStatus) OnVerifyComplete(t *zcncore.Transaction, status int) { defer zcn.Wg.Done() if status == zcncore.StatusSuccess { @@ -64,10 +79,14 @@ func (zcn *ZCNStatus) OnVerifyComplete(t *zcncore.Transaction, status int) { } } +// OnTransferComplete callback when a transfer is completed. Not used in this implementation func (zcn *ZCNStatus) OnAuthComplete(_ *zcncore.Transaction, status int) { Logger.Info("Authorization complete with status: ", status) } +// OnWalletCreateComplete callback when a wallet is created +// - status: status of the operation +// - wallet: wallet json string func (zcn *ZCNStatus) OnWalletCreateComplete(status int, wallet string, err string) { defer zcn.Wg.Done() if status != zcncore.StatusSuccess { @@ -81,6 +100,11 @@ func (zcn *ZCNStatus) OnWalletCreateComplete(status int, wallet string, err stri zcn.walletString = wallet } +// OnInfoAvailable callback when information is available +// - op`: operation type (check `zcncore.Op* constants) +// - status: status of the operation +// - info: information represneted as a string +// - err: error message func (zcn *ZCNStatus) OnInfoAvailable(op int, status int, info string, err string) { defer zcn.Wg.Done() @@ -114,10 +138,20 @@ func (zcn *ZCNStatus) OnInfoAvailable(op int, status int, info string, err strin zcn.Success = true } +// OnSetupComplete callback when setup is completed. +// Paramters are not used in this implementation, +// just kept for compatibility. func (zcn *ZCNStatus) OnSetupComplete(_ int, _ string) { defer zcn.Wg.Done() } +// OnAuthorizeSendComplete callback when authorization is completed +// - status: status of the operation +// - 2nd parameter is not used, it is kept for compatibility +// - 3rd parameter is not used, it is kept for compatibility +// - 4th parameter is not used, it is kept for compatibility +// - creationDate: timestamp of the creation date +// - signature: signature of the operation func (zcn *ZCNStatus) OnAuthorizeSendComplete(status int, _ string, _ int64, _ string, creationDate int64, signature string) { defer zcn.Wg.Done() @@ -127,6 +161,9 @@ func (zcn *ZCNStatus) OnAuthorizeSendComplete(status int, _ string, _ int64, _ s } // OnVoteComplete callback when a multisig vote is completed +// - status: status of the operation +// - proposal: proposal json string +// - err: error message func (zcn *ZCNStatus) OnVoteComplete(status int, proposal string, err string) { defer zcn.Wg.Done() if status != zcncore.StatusSuccess { diff --git a/zcnbridge/zcnsc/doc.go b/zcnbridge/zcnsc/doc.go new file mode 100644 index 000000000..25a1aa998 --- /dev/null +++ b/zcnbridge/zcnsc/doc.go @@ -0,0 +1,2 @@ +// Utilities to interact with native ZCN smart contract functions. +package zcnsc \ No newline at end of file diff --git a/zcncore/doc.go b/zcncore/doc.go new file mode 100644 index 000000000..1e9ce0fa8 --- /dev/null +++ b/zcncore/doc.go @@ -0,0 +1,2 @@ +// Contains sub-packages and modules for managing users' wallets and issuing transactions. +package zcncore \ No newline at end of file diff --git a/zcncore/ethhdwallet/hdwallet.go b/zcncore/ethhdwallet/hdwallet.go index b42c0a7ec..ec5afbb51 100644 --- a/zcncore/ethhdwallet/hdwallet.go +++ b/zcncore/ethhdwallet/hdwallet.go @@ -1,3 +1,4 @@ +// Utilities to interact with ethereum wallet. package hdwallet import ( diff --git a/zcncore/ethwallet_base.go b/zcncore/ethwallet_base.go index f53aaa9c5..1a6cbd93b 100644 --- a/zcncore/ethwallet_base.go +++ b/zcncore/ethwallet_base.go @@ -120,8 +120,8 @@ func IsValidEthAddress(ethAddr string) (bool, error) { return isValidEthAddress(ethAddr, client) } -// IsEthTransactionVerified - checks if the transaction is verified -// with a help of the given transaction hash +// IsEthTransactionVerified checks if the transaction - given its hash - is verified on the ethereum network +// - txHash: transaction hash func IsEthTransactionVerified(txHash string) (bool, error) { client, err := getEthClient() if err != nil { @@ -191,6 +191,7 @@ func CheckEthHashStatus(hash string) int { } // ConvertZcnTokenToETH - converting Zcn tokens to Eth +// - f: ZCN tokens amount func ConvertZcnTokenToETH(f float64) (float64, error) { ethRate, err := tokenrate.GetUSD(context.TODO(), "eth") if err != nil { diff --git a/zcncore/mocks/doc.go b/zcncore/mocks/doc.go new file mode 100644 index 000000000..d5f5048fa --- /dev/null +++ b/zcncore/mocks/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! Do not use. +package mocks \ No newline at end of file diff --git a/zcncore/networkworker.go b/zcncore/networkworker.go index e267c5f4a..2ce4943cb 100644 --- a/zcncore/networkworker.go +++ b/zcncore/networkworker.go @@ -21,6 +21,7 @@ const NETWORK_ENDPOINT = "/network" var networkWorkerTimerInHours = 1 +// Network details of the network nodes type Network struct { Miners []string `json:"miners"` Sharders []string `json:"sharders"` @@ -116,6 +117,7 @@ func GetNetworkDetails() (*Network, error) { } +// GetNetwork retrieve the registered network details. func GetNetwork() *Network { return &Network{ Miners: _config.chain.Miners, @@ -123,6 +125,9 @@ func GetNetwork() *Network { } } +// SetNetwork set the global network details for the SDK, including urls of the miners and sharders, which are the nodes of the network. +// - miners: miner urls. +// - sharders: sharder urls. func SetNetwork(miners []string, sharders []string) { _config.chain.Miners = miners _config.chain.Sharders = sharders @@ -144,6 +149,7 @@ func SetNetwork(miners []string, sharders []string) { }) } +// GetNetworkJSON retrieve the registered network details in JSON format. func GetNetworkJSON() string { network := GetNetwork() networkBytes, _ := json.Marshal(network) diff --git a/zcncore/networkworker_mobile.go b/zcncore/networkworker_mobile.go index ca0863ff8..92be91f0c 100644 --- a/zcncore/networkworker_mobile.go +++ b/zcncore/networkworker_mobile.go @@ -20,18 +20,22 @@ const NETWORK_ENDPOINT = "/network" var networkWorkerTimerInHours = 1 +// Network details of the network type Network struct { net network } +// NewNetwork create a new network func NewNetwork() *Network { return &Network{} } +// AddMiner add miner to the network func (net *Network) AddMiner(miner string) { net.net.Miners = append(net.net.Miners, miner) } +// AddSharder add sharder to the network func (net *Network) AddSharder(sharder string) { net.net.Sharders = append(net.net.Sharders, sharder) } @@ -60,6 +64,7 @@ func updateNetworkDetailsWorker(ctx context.Context) { } } +// UpdateNetworkDetails update network details func UpdateNetworkDetails() error { networkDetails, err := GetNetworkDetails() if err != nil { @@ -126,6 +131,7 @@ func GetNetworkDetails() (*Network, error) { return &Network{net: networkResponse}, nil } +// GetNetwork - get network details func GetNetwork() *Network { return &Network{ net: network{ @@ -135,6 +141,8 @@ func GetNetwork() *Network { } } +// SetNetwork set network details +// - net: network details func SetNetwork(net *Network) { _config.chain.Miners = net.net.Miners _config.chain.Sharders = net.net.Sharders diff --git a/zcncore/sample/0Wallet.go b/zcncore/sample/0Wallet.go index d98d32746..07f109b25 100644 --- a/zcncore/sample/0Wallet.go +++ b/zcncore/sample/0Wallet.go @@ -1,6 +1,7 @@ //go:build ignore // +build ignore +// Sample usage of the Wallet SDK - do not use. package main import ( diff --git a/zcncore/transaction.go b/zcncore/transaction.go index 5c811cb09..df8128970 100644 --- a/zcncore/transaction.go +++ b/zcncore/transaction.go @@ -21,6 +21,7 @@ import ( "github.com/0chain/gosdk/core/util" ) +// Provider represents the type of provider. type Provider int const ( @@ -46,6 +47,8 @@ type ConfirmationStatus int const ( Undefined ConfirmationStatus = iota Success + + // ChargeableError is an error that still charges the user for the transaction. ChargeableError ) @@ -61,11 +64,13 @@ type Miner struct { Stat interface{} `json:"stat"` } +// Node represents a node (miner or sharder) in the network. type Node struct { Miner Miner `json:"simple_miner"` StakePool `json:"stake_pool"` } +// MinerSCNodes list of nodes registered to the miner smart contract type MinerSCNodes struct { Nodes []Node `json:"Nodes"` } @@ -106,6 +111,7 @@ type MinerSCDelegatePoolInfo struct { Status string `json:"status"` } +// MinerSCUserPoolsInfo represents the user stake pools information type MinerSCUserPoolsInfo struct { Pools map[string][]*MinerSCDelegatePoolInfo `json:"pools"` } @@ -192,9 +198,9 @@ type CreateAllocationRequest struct { } type StakePoolSettings struct { - DelegateWallet *string `json:"delegate_wallet,omitempty"` - NumDelegates *int `json:"num_delegates,omitempty"` - ServiceCharge *float64 `json:"service_charge,omitempty"` + DelegateWallet *string `json:"delegate_wallet,omitempty"` + NumDelegates *int `json:"num_delegates,omitempty"` + ServiceCharge *float64 `json:"service_charge,omitempty"` } type Terms struct { @@ -203,16 +209,28 @@ type Terms struct { MaxOfferDuration time.Duration `json:"max_offer_duration"` } +// Blobber represents a blobber node. type Blobber struct { - ID common.Key `json:"id"` - BaseURL string `json:"url"` - Terms Terms `json:"terms"` - Capacity common.Size `json:"capacity"` - Allocated common.Size `json:"allocated"` - LastHealthCheck common.Timestamp `json:"last_health_check"` + // ID is the blobber ID. + ID common.Key `json:"id"` + // BaseURL is the blobber's base URL used to access the blobber + BaseURL string `json:"url"` + // Terms of storage service of the blobber (read/write price, max offer duration) + Terms Terms `json:"terms"` + // Capacity is the total capacity of the blobber + Capacity common.Size `json:"capacity"` + // Used is the capacity of the blobber used to create allocations + Allocated common.Size `json:"allocated"` + // LastHealthCheck is the last time the blobber was checked for health + LastHealthCheck common.Timestamp `json:"last_health_check"` + // StakePoolSettings is the settings of the blobber's stake pool StakePoolSettings StakePoolSettings `json:"stake_pool_settings"` - NotAvailable bool `json:"not_available"` - IsRestricted bool `json:"is_restricted"` + // NotAvailable is true if the blobber is not available + NotAvailable bool `json:"not_available"` + // IsRestricted is true if the blobber is restricted. + // Restricted blobbers needs to be authenticated using AuthTickets in order to be used for allocation creation. + // Check Restricted Blobbers documentation for more details. + IsRestricted bool `json:"is_restricted"` } type Validator struct { @@ -221,35 +239,43 @@ type Validator struct { StakePoolSettings StakePoolSettings `json:"stake_pool_settings"` } +// AddAuthorizerPayload represents the payload for adding an authorizer. type AddAuthorizerPayload struct { PublicKey string `json:"public_key"` URL string `json:"url"` StakePoolSettings AuthorizerStakePoolSettings `json:"stake_pool_settings"` // Used to initially create stake pool } +// DeleteAuthorizerPayload represents the payload for deleting an authorizer. type DeleteAuthorizerPayload struct { ID string `json:"id"` // authorizer ID } +// AuthorizerHealthCheckPayload represents the payload for authorizer health check. type AuthorizerHealthCheckPayload struct { ID string `json:"id"` // authorizer ID } +// AuthorizerStakePoolSettings represents the settings for an authorizer's stake pool. type AuthorizerStakePoolSettings struct { - DelegateWallet string `json:"delegate_wallet"` - NumDelegates int `json:"num_delegates"` - ServiceCharge float64 `json:"service_charge"` + DelegateWallet string `json:"delegate_wallet"` + NumDelegates int `json:"num_delegates"` + ServiceCharge float64 `json:"service_charge"` } type AuthorizerConfig struct { Fee common.Balance `json:"fee"` } +// InputMap represents a map of input fields. type InputMap struct { Fields map[string]string `json:"Fields"` } -// NewTransaction allocation new generic transaction object for any operation +// NewTransaction new generic transaction object for any operation +// - cb: callback for transaction state +// - txnFee: Transaction fees (in SAS tokens) +// - nonce: latest nonce of current wallet. please set it with 0 if you don't know the latest value func NewTransaction(cb TransactionCallback, txnFee uint64, nonce int64) (TransactionScheme, error) { err := CheckConfig() if err != nil { @@ -890,10 +916,12 @@ type MinerSCDelegatePool struct { Settings StakePoolSettings `json:"settings"` } +// SimpleMiner represents a node in the network, miner or sharder. type SimpleMiner struct { ID string `json:"id"` } +// MinerSCMinerInfo interface for miner/sharder info functions on miner smart contract. type MinerSCMinerInfo struct { SimpleMiner `json:"simple_miner"` MinerSCDelegatePool `json:"stake_pool"` @@ -943,6 +971,7 @@ func (t *Transaction) MinerSCDeleteSharder(info *MinerSCMinerInfo) (err error) { return } +// AuthorizerNode represents an authorizer node in the network type AuthorizerNode struct { ID string `json:"id"` URL string `json:"url"` @@ -1110,6 +1139,9 @@ func GetLatestFinalized(ctx context.Context, numSharders int) (b *block.Header, return } +// GetLatestFinalizedMagicBlock gets latest finalized magic block +// - numSharders: number of sharders +// - timeout: request timeout func GetLatestFinalizedMagicBlock(ctx context.Context, numSharders int) (m *block.MagicBlock, err error) { var result = make(chan *util.GetResponse, numSharders) defer close(result) @@ -1232,10 +1264,13 @@ func GetBlockByRound(ctx context.Context, numSharders int, round int64) (b *bloc return Sharders.GetBlockByRound(ctx, numSharders, round) } +// GetRoundFromSharders returns the current round number from the sharders func GetRoundFromSharders() (int64, error) { return Sharders.GetRoundFromSharders() } +// GetHardForkRound returns the round number of the hard fork +// - hardFork: hard fork name func GetHardForkRound(hardFork string) (int64, error) { return Sharders.GetHardForkRound(hardFork) } @@ -1343,6 +1378,8 @@ func (nc *NonceCache) Evict(clientId string) { delete(nc.cache, clientId) } +// WithEthereumNode set the ethereum node used for bridge operations. +// - uri: ethereum node uri func WithEthereumNode(uri string) func(c *ChainConfig) error { return func(c *ChainConfig) error { c.EthNode = uri @@ -1350,6 +1387,8 @@ func WithEthereumNode(uri string) func(c *ChainConfig) error { } } +// WithChainID set the chain id. Chain ID is a unique identifier for the blockchain which is set at the time of its creation. +// - id: chain id func WithChainID(id string) func(c *ChainConfig) error { return func(c *ChainConfig) error { c.ChainID = id @@ -1357,6 +1396,8 @@ func WithChainID(id string) func(c *ChainConfig) error { } } +// WithMinSubmit set the minimum submit, minimum number of miners that should receive the transaction submission. +// - m: minimum submit func WithMinSubmit(m int) func(c *ChainConfig) error { return func(c *ChainConfig) error { c.MinSubmit = m @@ -1364,6 +1405,8 @@ func WithMinSubmit(m int) func(c *ChainConfig) error { } } +// WithMinConfirmation set the minimum confirmation, minimum number of nodes that should confirm the transaction. +// - m: minimum confirmation func WithMinConfirmation(m int) func(c *ChainConfig) error { return func(c *ChainConfig) error { c.MinConfirmation = m @@ -1371,6 +1414,8 @@ func WithMinConfirmation(m int) func(c *ChainConfig) error { } } +// WithConfirmationChainLength set the confirmation chain length, which is the number of blocks that need to be confirmed. +// - m: confirmation chain length func WithConfirmationChainLength(m int) func(c *ChainConfig) error { return func(c *ChainConfig) error { c.ConfirmationChainLength = m diff --git a/zcncore/transaction_base.go b/zcncore/transaction_base.go index f6eaa7e00..89fc1c520 100644 --- a/zcncore/transaction_base.go +++ b/zcncore/transaction_base.go @@ -116,7 +116,10 @@ type ChainConfig struct { var Sharders *node.NodeHolder -// InitZCNSDK initializes the SDK with miner, sharder and signature scheme provided. +// InitZCNSDK initializes the SDK given block worker and signature scheme provided. +// - blockWorker: block worker, which is the url for the DNS service for locating miners and sharders +// - signscheme: signature scheme to be used for signing the transactions +// - configs: configuration options func InitZCNSDK(blockWorker string, signscheme string, configs ...func(*ChainConfig) error) error { if signscheme != "ed25519" && signscheme != "bls0chain" { return errors.New("", "invalid/unsupported signature scheme") @@ -199,6 +202,7 @@ func (bh *blockHeader) getCreationDate(defaultTime int64) int64 { return bh.CreationDate } +// Transaction data structure that provides the transaction details type Transaction struct { txn *transaction.Transaction txnOut string @@ -296,10 +300,12 @@ func txnTypeString(t int) string { } } +// Output implements the output of transaction func (t *Transaction) Output() []byte { return []byte(t.txnOut) } +// Hash implements the hash of transaction func (t *Transaction) Hash() string { return t.txn.Hash } @@ -446,6 +452,7 @@ func newTransaction(cb TransactionCallback, txnFee uint64, nonce int64) (*Transa return t, nil } +// SetTransactionCallback implements storing the callback func (t *Transaction) SetTransactionCallback(cb TransactionCallback) error { if t.txnStatus != StatusUnknown { return errors.New("", "transaction already exists. cannot set transaction hash.") @@ -454,6 +461,7 @@ func (t *Transaction) SetTransactionCallback(cb TransactionCallback) error { return nil } +// SetTransactionNonce implements method to set the transaction nonce func (t *Transaction) SetTransactionNonce(txnNonce int64) error { if t.txnStatus != StatusUnknown { return errors.New("", "transaction already exists. cannot set transaction fee.") @@ -462,6 +470,7 @@ func (t *Transaction) SetTransactionNonce(txnNonce int64) error { return nil } +// StoreData implements store the data to blockchain func (t *Transaction) StoreData(data string) error { go func() { t.txn.TransactionType = transaction.TxnTypeData @@ -564,6 +573,8 @@ func (t *Transaction) ExecuteFaucetSCWallet(walletStr string, methodName string, return nil } +// SetTransactionHash implements verify a previous transaction status +// - hash: transaction hash func (t *Transaction) SetTransactionHash(hash string) error { if t.txnStatus != StatusUnknown { return errors.New("", "transaction already exists. cannot set transaction hash.") @@ -572,6 +583,7 @@ func (t *Transaction) SetTransactionHash(hash string) error { return nil } +// GetTransactionHash implements retrieval of hash of the submitted transaction func (t *Transaction) GetTransactionHash() string { if t.txnHash != "" { return t.txnHash @@ -772,6 +784,8 @@ func (t *Transaction) isTransactionExpired(lfbCreationTime, currentTime int64) b sys.Sleep(defaultWaitSeconds) return false } + +// GetVerifyOutput implements the verification output from sharders func (t *Transaction) GetVerifyOutput() string { if t.verifyStatus == StatusSuccess { return t.verifyOut @@ -779,6 +793,7 @@ func (t *Transaction) GetVerifyOutput() string { return "" } +// GetTransactionError implements error string in case of transaction failure func (t *Transaction) GetTransactionError() string { if t.txnStatus != StatusSuccess { return t.txnError.Error() @@ -786,6 +801,7 @@ func (t *Transaction) GetTransactionError() string { return "" } +// GetVerifyError implements error string in case of verify failure error func (t *Transaction) GetVerifyError() string { if t.verifyStatus != StatusSuccess { return t.verifyError.Error() diff --git a/zcncore/transaction_mobile.go b/zcncore/transaction_mobile.go index 84135ecfa..89bf53175 100644 --- a/zcncore/transaction_mobile.go +++ b/zcncore/transaction_mobile.go @@ -24,9 +24,12 @@ import ( const ( Undefined int = iota Success + + // ChargeableError is an error that still charges the user for the transaction. ChargeableError ) +// Provider represents the type of provider. type Provider int const ( @@ -225,10 +228,13 @@ func (v *validator) SetStakePoolSettings(delegateWallet string, numDelegates int } } +// AddAuthorizerPayload is the interface gathering the functions to add a new authorizer. type AddAuthorizerPayload interface { + // SetStakePoolSettings sets the stake pool settings for the authorizer. SetStakePoolSettings(delegateWallet string, numDelegates int, serviceCharge float64) } +// NewAddAuthorizerPayload creates a new AddAuthorizerPayload concrete instance. func NewAddAuthorizerPayload(pubKey, url string) AddAuthorizerPayload { return &addAuthorizerPayload{ PublicKey: pubKey, @@ -242,6 +248,7 @@ type addAuthorizerPayload struct { StakePoolSettings AuthorizerStakePoolSettings `json:"stake_pool_settings"` // Used to initially create stake pool } +// SetStakePoolSettings sets the stake pool settings for the authorizer. func (a *addAuthorizerPayload) SetStakePoolSettings(delegateWallet string, numDelegates int, serviceCharge float64) { a.StakePoolSettings = AuthorizerStakePoolSettings{ DelegateWallet: delegateWallet, @@ -254,12 +261,14 @@ type AuthorizerHealthCheckPayload struct { ID string `json:"id"` // authorizer ID } +// AuthorizerStakePoolSettings represents configuration of an authorizer stake pool. type AuthorizerStakePoolSettings struct { DelegateWallet string `json:"delegate_wallet"` NumDelegates int `json:"num_delegates"` ServiceCharge float64 `json:"service_charge"` } +// AuthorizerConfig represents configuration of an authorizer node. type AuthorizerConfig struct { Fee int64 `json:"fee"` } @@ -292,7 +301,11 @@ func (vr *vestingAddRequest) AddDestinations(id string, amount int64) { vr.Destinations = append(vr.Destinations, &VestingDest{ID: id, Amount: amount}) } +// InputMap represents an interface of functions to add fields to a map. type InputMap interface { + // AddField adds a field to the map. + // - key: field key + // - value: field value AddField(key, value string) } @@ -300,6 +313,7 @@ type inputMap struct { Fields map[string]string `json:"fields"` } +// NewInputMap creates a new InputMap concrete instance. func NewInputMap() InputMap { return &inputMap{ Fields: make(map[string]string), @@ -323,10 +337,9 @@ func parseCoinStr(vs string) (uint64, error) { return v, nil } -// NewTransaction allocation new generic transaction object for any operation -// # Inputs +// NewTransaction new generic transaction object for any operation // - cb: callback for transaction state -// - txnFee: ZCN tokens +// - txnFee: Transaction fees (in SAS tokens) // - nonce: latest nonce of current wallet. please set it with 0 if you don't know the latest value func NewTransaction(cb TransactionCallback, txnFee string, nonce int64) (TransactionScheme, error) { v, err := parseCoinStr(txnFee) @@ -350,6 +363,7 @@ func NewTransaction(cb TransactionCallback, txnFee string, nonce int64) (Transac return t, err } +// ExecuteSmartContract prepare and send a smart contract transaction to the blockchain func (t *Transaction) ExecuteSmartContract(address, methodName string, input string, val string) error { v, err := parseCoinStr(val) if err != nil { @@ -374,6 +388,7 @@ func (t *Transaction) setTransactionFee(fee uint64) error { return nil } +// Send to send a transaction to a given clientID func (t *Transaction) Send(toClientID string, val string, desc string) error { v, err := parseCoinStr(val) if err != nil { @@ -394,6 +409,13 @@ func (t *Transaction) Send(toClientID string, val string, desc string) error { return nil } +// SendWithSignatureHash to send a transaction to a given clientID with a signature hash +// - toClientID: client ID in the To field of the transaction +// - val: amount of tokens to send +// - desc: description of the transaction +// - sig: signature hash +// - CreationDate: creation date of the transaction +// - hash: hash of the transaction func (t *Transaction) SendWithSignatureHash(toClientID string, val string, desc string, sig string, CreationDate int64, hash string) error { v, err := parseCoinStr(val) if err != nil { @@ -808,10 +830,19 @@ func (t *Transaction) GetVerifyConfirmationStatus() int { return int(t.verifyConfirmationStatus) } +// MinerSCMinerInfo interface for miner info functions on miner smart contract. type MinerSCMinerInfo interface { + // GetID returns the ID of the miner GetID() string } +// NewMinerSCMinerInfo creates a new miner info. +// - id: miner ID +// - delegateWallet: delegate wallet +// - minStake: minimum stake +// - maxStake: maximum stake +// - numDelegates: number of delegates +// - serviceCharge: service charge func NewMinerSCMinerInfo(id string, delegateWallet string, minStake int64, maxStake int64, numDelegates int, serviceCharge float64) MinerSCMinerInfo { return &minerSCMinerInfo{ @@ -887,10 +918,13 @@ func (t *Transaction) MinerSCDeleteSharder(info MinerSCMinerInfo) (err error) { return } +// AuthorizerNode interface for authorizer node functions. type AuthorizerNode interface { + // GetID returns the ID of the authorizer node. GetID() string } +// NewAuthorizerNode creates a new authorizer node. func NewAuthorizerNode(id string, fee int64) AuthorizerNode { return &authorizerNode{ ID: id, @@ -1042,7 +1076,6 @@ func ConvertTokenToSAS(token float64) uint64 { } // ConvertToValue converts ZCN tokens to SAS tokens with string format -// # Inputs // - token: ZCN tokens func ConvertToValue(token float64) string { return strconv.FormatUint(ConvertTokenToSAS(token), 10) @@ -1106,6 +1139,9 @@ func GetLatestFinalized(numSharders int, timeout RequestTimeout) (b *BlockHeader return } +// GetLatestFinalizedMagicBlock gets latest finalized magic block +// - numSharders: number of sharders +// - timeout: request timeout func GetLatestFinalizedMagicBlock(numSharders int, timeout RequestTimeout) ([]byte, error) { var result = make(chan *util.GetResponse, numSharders) defer close(result) diff --git a/zcncore/wallet.go b/zcncore/wallet.go index f16adf299..90c0b8b7c 100644 --- a/zcncore/wallet.go +++ b/zcncore/wallet.go @@ -13,6 +13,8 @@ func GetWallet(walletStr string) (*zcncrypto.Wallet, error) { return getWallet(walletStr) } +// GetWalletBalance retrieve wallet balance from sharders +// - id: client id func GetWalletBalance(clientId string) (common.Balance, int64, error) { return getWalletBalance(clientId) } diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index b2b76e137..ab2c3e5fb 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -134,6 +134,7 @@ const ( var defaultLogLevel = logger.DEBUG var logging logger.Logger +// GetLogger returns the logger instance func GetLogger() *logger.Logger { return &logging } @@ -153,24 +154,61 @@ const ( OpGetNotProcessedBurnTickets OpGetMintNonce // storage SC ops + // OpStorageSCGetConfig Get global storage SC config OpStorageSCGetConfig + + // OpStorageSCGetChallengePoolInfo Get challenge pool info OpStorageSCGetChallengePoolInfo + + // OpStorageSCGetAllocation Get allocation info OpStorageSCGetAllocation + + // OpStorageSCGetAllocations Get all allocations OpStorageSCGetAllocations + + // OpStorageSCGetReadPoolInfo Get read pool info OpStorageSCGetReadPoolInfo + + // OpStorageSCGetStakePoolInfo Get stake pool info OpStorageSCGetStakePoolInfo + + // OpStorageSCGetStakePoolUserInfo Get blobbers OpStorageSCGetBlobbers + + // OpStorageSCGetBlobber Get blobber information OpStorageSCGetBlobber + + // OpStorageSCGetValidator Get transaction info OpStorageSCGetTransactions + + // OpStorageSCGetSnapshots Get global snapshots OpStorageSCGetSnapshots + + // OpStorageSCGetBlobberSnapshots Get blobber snapshots OpStorageSCGetBlobberSnapshots + + // OpStorageSCGetMinerSnapshots Get miner snapshots OpStorageSCGetMinerSnapshots + + // OpStorageSCGetSharderSnapshots Get sharder snapshots OpStorageSCGetSharderSnapshots + + // OpStorageSCGetAuthorizerSnapshots Get authorizer snapshots OpStorageSCGetAuthorizerSnapshots + + // OpStorageSCGetValidatorSnapshots Get validator snapshots OpStorageSCGetValidatorSnapshots + + // OpStorageSCGetUserSnapshots Get user snapshots OpStorageSCGetUserSnapshots + + // OpStorageSCGetUserLockedTotal Get global configuration OpZCNSCGetGlobalConfig + + // OpZCNSCGetMintNonce Get authorizer information OpZCNSCGetAuthorizer + + // OpZCNSCGetAuthorizerNodes Get authorizer nodes OpZCNSCGetAuthorizerNodes ) @@ -184,7 +222,7 @@ type GetBalanceCallback interface { OnBalanceAvailable(status int, value int64, info string) } -// BurnTicket model used for deserialization of the response received from sharders +// BurnTicket represents the burn ticket of native ZCN tokens used by the bridge protocol to mint ERC20 tokens type BurnTicket struct { Hash string `json:"hash"` Amount int64 `json:"amount"` @@ -208,7 +246,7 @@ func (g *GetNonceCallbackStub) OnNonceAvailable(status int, nonce int64, info st g.info = info } -// GetInfoCallback needs to be implemented by the caller of GetLockTokenConfig() and GetLockedTokens() +// GetInfoCallback represents the functions that will be called when the response of a GET request to the sharders is available type GetInfoCallback interface { // OnInfoAvailable will be called when GetLockTokenConfig is complete // if status == StatusSuccess then info is valid @@ -311,13 +349,14 @@ func GetVersion() string { } // SetLogLevel set the log level. -// lvl - 0 disabled; higher number (upto 4) more verbosity +// - lvl: 0 disabled; higher number (upto 4) more verbosity func SetLogLevel(lvl int) { logging.SetLevel(lvl) } // SetLogFile - sets file path to write log -// verbose - true - console output; false - no console output +// - logFile: log file path +// - verbose: true - console output; false - no console output func SetLogFile(logFile string, verbose bool) { ioWriter := &lumberjack.Logger{ Filename: logFile, @@ -386,6 +425,7 @@ func Init(chainConfigJSON string) error { } // InitSignatureScheme initializes signature scheme only. +// - scheme: signature scheme func InitSignatureScheme(scheme string) { _config.chain.SignatureScheme = scheme } @@ -405,6 +445,7 @@ func CreateWalletOffline() (string, error) { } // RecoverOfflineWallet recovers the previously generated wallet using the mnemonic. +// - mnemonic: mnemonics to recover func RecoverOfflineWallet(mnemonic string) (string, error) { if !zcncrypto.IsMnemonicValid(mnemonic) { return "", errors.New("", "Invalid mnemonic") @@ -493,10 +534,8 @@ func GetClientDetails(clientID string) (*GetClientResponse, error) { return &clientDetails, nil } -// IsMnemonicValid is an utility function to check the mnemonic valid -// -// # Inputs -// - mnemonic: mnemonics +// IsMnemonicValid is a utility function to check the mnemonic valid +// - mnemonic: mnemonics to check func IsMnemonicValid(mnemonic string) bool { return zcncrypto.IsMnemonicValid(mnemonic) } @@ -518,24 +557,10 @@ func GetWalletRaw() zcncrypto.Wallet { return _config.wallet } -// SetWalletInfo should be set before any transaction or client specific APIs -// splitKeyWallet parameter is valid only if SignatureScheme is "BLS0Chain" -// -// # Inputs -// - jsonWallet: json format of wallet -// { -// "client_id":"30764bcba73216b67c36b05a17b4dd076bfdc5bb0ed84856f27622188c377269", -// "client_key":"1f495df9605a4479a7dd6e5c7a78caf9f9d54e3a40f62a3dd68ed377115fe614d8acf0c238025f67a85163b9fbf31d10fbbb4a551d1cf00119897edf18b1841c", -// "keys":[ -// {"public_key":"1f495df9605a4479a7dd6e5c7a78caf9f9d54e3a40f62a3dd68ed377115fe614d8acf0c238025f67a85163b9fbf31d10fbbb4a551d1cf00119897edf18b1841c","private_key":"41729ed8d82f782646d2d30b9719acfd236842b9b6e47fee12b7bdbd05b35122"} -// ], -// "mnemonics":"glare mistake gun joke bid spare across diagram wrap cube swear cactus cave repeat you brave few best wild lion pitch pole original wasp", -// "version":"1.0", -// "date_created":"1662534022", -// "nonce":0 -// } -// -// - splitKeyWallet: if wallet keys is split +// SetWalletInfo should be set before any transaction or client specific APIs. +// "splitKeyWallet" parameter is valid only if SignatureScheme is "BLS0Chain" +// - jsonWallet: json format of wallet +// - splitKeyWallet: if wallet keys is split func SetWalletInfo(jsonWallet string, splitKeyWallet bool) error { err := json.Unmarshal([]byte(jsonWallet), &_config.wallet) if err == nil { @@ -583,7 +608,7 @@ func getWalletBalance(clientId string) (common.Balance, int64, error) { cb.Wait() var clientState struct { - Nonce int64 `json:"nonce"` + Nonce int64 `json:"nonce"` } err = json.Unmarshal([]byte(cb.info), &clientState) if err != nil { @@ -594,9 +619,7 @@ func getWalletBalance(clientId string) (common.Balance, int64, error) { } // GetBalance retrieve wallet balance from sharders -// -// # Inputs -// - cb: callback for checking result +// - cb: info callback instance, carries the response of the GET request to the sharders func GetBalance(cb GetBalanceCallback) error { err := CheckConfig() if err != nil { @@ -614,7 +637,8 @@ func GetBalance(cb GetBalanceCallback) error { return nil } -// GetMintNonce retrieve mint nonce from sharders +// GetMintNonce retrieve the client's latest mint nonce from sharders +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMintNonce(cb GetInfoCallback) error { err := CheckConfig() if err != nil { @@ -627,7 +651,10 @@ func GetMintNonce(cb GetInfoCallback) error { return nil } -// GetNotProcessedZCNBurnTickets retrieve wallet burn tickets from sharders +// GetNotProcessedZCNBurnTickets retrieve burn tickets that are not compensated by minting +// - ethereumAddress: ethereum address for the issuer of the burn tickets +// - startNonce: start nonce for the burn tickets +// - cb: info callback instance, carries the response of the GET request to the sharders func GetNotProcessedZCNBurnTickets(ethereumAddress, startNonce string, cb GetInfoCallback) error { err := CheckConfig() if err != nil { @@ -642,7 +669,8 @@ func GetNotProcessedZCNBurnTickets(ethereumAddress, startNonce string, cb GetInf return nil } -// GetBalance retrieve wallet nonce from sharders +// GetNonce retrieve wallet nonce from sharders +// - cb: info callback instance, carries the response of the GET request to the sharders func GetNonce(cb GetNonceCallback) error { if cb == nil { cb = &GetNonceCallbackStub{} @@ -668,6 +696,7 @@ func GetNonce(cb GetNonceCallback) error { } // GetWalletBalance retrieve wallet nonce from sharders +// - clientID: client id func GetWalletNonce(clientID string) (int64, error) { cb := &GetNonceCallbackStub{} @@ -698,6 +727,8 @@ func GetWalletNonce(clientID string) (int64, error) { } // GetBalanceWallet retreives wallet balance from sharders +// - walletStr: wallet string +// - cb: info callback instance, carries the response of the GET request to the sharders func GetBalanceWallet(walletStr string, cb GetBalanceCallback) error { w, err := getWallet(walletStr) if err != nil { @@ -726,12 +757,13 @@ func getNonceFromSharders(clientID string) (int64, string, error) { } // ConvertToToken converts the SAS tokens to ZCN tokens -// # Inputs -// - token: SAS tokens +// - token: SAS tokens amount func ConvertToToken(token int64) float64 { return float64(token) / float64(common.TokenUnit) } +// ConvertTokenToUSD converts the ZCN tokens to USD amount +// - token: ZCN tokens amount func ConvertTokenToUSD(token float64) (float64, error) { zcnRate, err := getTokenUSDRate() if err != nil { @@ -740,6 +772,8 @@ func ConvertTokenToUSD(token float64) (float64, error) { return token * zcnRate, nil } +// ConvertUSDToToken converts the USD amount to ZCN tokens +// - usd: USD amount func ConvertUSDToToken(usd float64) (float64, error) { zcnRate, err := getTokenUSDRate() if err != nil { @@ -764,7 +798,8 @@ func getWallet(walletStr string) (*zcncrypto.Wallet, error) { return &w, nil } -// GetWalletClientID -- given a walletstr return ClientID +// GetWalletClientID extract wallet client id from wallet string +// - walletStr: wallet string to get client id func GetWalletClientID(walletStr string) (string, error) { w, err := getWallet(walletStr) if err != nil { @@ -802,6 +837,8 @@ func SetupAuth(authHost, clientID, clientKey, publicKey, privateKey, localPublic return nil } +// GetIdForUrl retrieve the ID of the network node (miner/sharder) given its url. +// - url: url of the node. func GetIdForUrl(url string) string { url = strings.TrimRight(url, "/") url = fmt.Sprintf("%v/_nh/whoami", url) @@ -845,12 +882,11 @@ func (p Params) Query() string { // // GetMiners obtains list of all active miners. -// -// # Inputs -// - cb: callback for checking result -// - limit: how many miners should be fetched -// - offset: how many miners should be skipped -// - active: only fetch active miners +// - cb: info callback instance, carries the response of the GET request to the sharders +// - limit: how many miners should be fetched +// - offset: how many miners should be skipped +// - active: retrieve only active miners +// - stakable: retreive only stakable miners func GetMiners(cb GetInfoCallback, limit, offset int, active bool, stakable bool) { getMinersInternal(cb, active, stakable, limit, offset) } @@ -861,22 +897,21 @@ func getMinersInternal(cb GetInfoCallback, active, stakable bool, limit, offset } var url = withParams(GET_MINERSC_MINERS, Params{ - "active": strconv.FormatBool(active), + "active": strconv.FormatBool(active), "stakable": strconv.FormatBool(stakable), - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), + "offset": strconv.FormatInt(int64(offset), 10), + "limit": strconv.FormatInt(int64(limit), 10), }) go GetInfoFromSharders(url, 0, cb) } -// GetSharders obtains list of all active sharders. -// # Inputs -// - cb: callback for checking result +// GetSharders obtains a list of sharders given the following parameters. +// - cb: info callback instance, carries the response of the GET request to the sharders // - limit: how many sharders should be fetched // - offset: how many sharders should be skipped -// - active: only fetch active sharders -// - stakable: only fetch sharders that can be staked +// - active: retrieve only active sharders +// - stakable: retrieve only sharders that can be staked func GetSharders(cb GetInfoCallback, limit, offset int, active, stakable bool) { getShardersInternal(cb, active, stakable, limit, offset) } @@ -887,10 +922,10 @@ func getShardersInternal(cb GetInfoCallback, active, stakable bool, limit, offse } var url = withParams(GET_MINERSC_SHARDERS, Params{ - "active": strconv.FormatBool(active), + "active": strconv.FormatBool(active), "stakable": strconv.FormatBool(stakable), - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), + "offset": strconv.FormatInt(int64(offset), 10), + "limit": strconv.FormatInt(int64(limit), 10), }) go GetInfoFromSharders(url, 0, cb) @@ -901,9 +936,8 @@ func withParams(uri string, params Params) string { } // GetMinerSCNodeInfo get miner information from sharders -// # Inputs // - id: the id of miner -// - cb: callback for checking result +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSCNodeInfo(id string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { @@ -916,6 +950,9 @@ func GetMinerSCNodeInfo(id string, cb GetInfoCallback) (err error) { return } +// GetMinerSCNodePool get miner smart contract node pool +// - id: the id of miner +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSCNodePool(id string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -928,10 +965,9 @@ func GetMinerSCNodePool(id string, cb GetInfoCallback) (err error) { return } -// GetMinerSCUserInfo get user pool -// # Inputs -// - clientID: the id of wallet -// - cb: callback for checking result +// GetMinerSCUserInfo retrieve user stake pools for the providers related to the Miner SC (miners/sharders). +// - clientID: user's wallet id +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSCUserInfo(clientID string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -946,6 +982,8 @@ func GetMinerSCUserInfo(clientID string, cb GetInfoCallback) (err error) { return } +// GetMinerSCConfig get miner SC configuration +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSCConfig(cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -954,6 +992,8 @@ func GetMinerSCConfig(cb GetInfoCallback) (err error) { return } +// GetMinerSCGlobals get miner SC globals +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSCGlobals(cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -967,6 +1007,7 @@ func GetMinerSCGlobals(cb GetInfoCallback) (err error) { // // GetStorageSCConfig obtains Storage SC configurations. +// - cb: info callback instance, carries the response of the GET request to the sharders func GetStorageSCConfig(cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1014,7 +1055,12 @@ func GetAllocations(clientID string, cb GetInfoCallback) (err error) { return } -// GetSnapshots obtains list of allocations of a user. +// GetSnapshots obtains list of global snapshots, given an initial round and a limit. +// Global snapshots are historical records of some aggregate data related +// to the network (like total staked amount and total reward amount). +// - round: round number to start fetching snapshots +// - limit: how many snapshots should be fetched +// - cb: info callback instance, carries the response of the GET request to the sharders func GetSnapshots(round int64, limit int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1028,6 +1074,13 @@ func GetSnapshots(round int64, limit int64, cb GetInfoCallback) (err error) { } // GetBlobberSnapshots obtains list of allocations of a blobber. +// Blobber snapshots are historical records of the blobber instance to track its change over time and serve graph requests, +// which are requests that need multiple data points, distributed over an interval of time, usually to plot them on a +// graph. +// - round: round number +// - limit: how many blobber snapshots should be fetched +// - offset: how many blobber snapshots should be skipped +// - cb: info callback instance, carries the response of the GET request to the sharders func GetBlobberSnapshots(round int64, limit int64, offset int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1041,7 +1094,14 @@ func GetBlobberSnapshots(round int64, limit int64, offset int64, cb GetInfoCallb return } -// GetMinerSnapshots obtains list of allocations of a miner. +// GetMinerSnapshots obtains a list of miner snapshots starting from a specific round. +// Miner snapshots are historical records of the miner instance to track its change over time and serve graph requests, +// which are requests that need multiple data points, distributed over an interval of time, usually to plot them on a +// graph. +// - round: round number to start fetching snapshots +// - limit: how many miner snapshots should be fetched +// - offset: how many miner snapshots should be skipped +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSnapshots(round int64, limit int64, offset int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1055,7 +1115,14 @@ func GetMinerSnapshots(round int64, limit int64, offset int64, cb GetInfoCallbac return } -// GetSharderSnapshots obtains list of allocations of a sharder. +// GetSharderSnapshots obtains a list of sharder snapshots starting from a specific round. +// Sharder snapshots are historical records of the sharder instance to track its change over time and serve graph requests, +// which are requests that need multiple data points, distributed over an interval of time, usually to plot them on a +// graph. +// - round: round number to start fetching snapshots +// - limit: how many sharder snapshots should be fetched +// - offset: how many sharder snapshots should be skipped +// - cb: info callback instance, carries the response of the GET request to the sharders func GetSharderSnapshots(round int64, limit int64, offset int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1069,7 +1136,14 @@ func GetSharderSnapshots(round int64, limit int64, offset int64, cb GetInfoCallb return } -// GetValidatorSnapshots obtains list of allocations of a validator. +// GetValidatorSnapshots obtains list of validator snapshots from the sharders. +// Validator snapshots are historical records of the validator instance to track its change over time and serve graph requests, +// which are requests that need multiple data points, distributed over an interval of time, usually to plot them on a +// graph. +// - round: round number to start fetching snapshots +// - limit: how many validator snapshots should be fetched +// - offset: how many validator snapshots should be skipped +// - cb: info callback instance, carries the response of the GET request to the sharders func GetValidatorSnapshots(round int64, limit int64, offset int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1083,7 +1157,14 @@ func GetValidatorSnapshots(round int64, limit int64, offset int64, cb GetInfoCal return } -// GetAuthorizerSnapshots obtains list of allocations of an authorizer. +// GetAuthorizerSnapshots obtains list of authorizers snapshots from the sharders. +// Authorizer snapshots are historical records of the authorizer instance to track its change over time and serve graph requests, +// which are requests that need multiple data points, distributed over an interval of time, usually to plot them on a +// graph. +// - round: round number to start fetching snapshots +// - limit: how many authorizer snapshots should be fetched +// - offset: how many authorizer snapshots should be skipped +// - cb: info callback instance, carries the response of the GET request to the sharders func GetAuthorizerSnapshots(round int64, limit int64, offset int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1097,7 +1178,14 @@ func GetAuthorizerSnapshots(round int64, limit int64, offset int64, cb GetInfoCa return } -// GetUserSnapshots replicates user aggregates from events_db. +// GetUserSnapshots replicates user snapshots from the sharders +// User snapshots are historical records of the client data to track its change over time and serve graph requests, +// which are requests that need multiple data points, distributed over an interval of time, usually to plot them on a +// graph. +// - round: round number to start fetching snapshots +// - limit: how many user snapshots should be fetched +// - offset: how many user snapshots should be skipped +// - cb: info callback instance, carries the response of the GET request to the sharders func GetUserSnapshots(round int64, limit int64, offset int64, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1142,7 +1230,7 @@ func GetStakePoolInfo(blobberID string, cb GetInfoCallback) (err error) { // GetStakePoolUserInfo for a user. // # Inputs // - clientID: the id of wallet -// - cb: callback for checking result +// - cb: info callback instance, carries the response of the GET request to the sharders func GetStakePoolUserInfo(clientID string, offset, limit int, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1162,7 +1250,7 @@ func GetStakePoolUserInfo(clientID string, offset, limit int, cb GetInfoCallback // GetStakeableBlobbers obtains list of all active blobbers that can be staked (i.e. still number of delegations < max_delegations) // # Inputs -// - cb: callback for checking result +// - cb: info callback instance, carries the response of the GET request to the sharders // - limit: how many blobbers should be fetched // - offset: how many blobbers should be skipped // - active: only fetch active blobbers @@ -1171,8 +1259,7 @@ func GetStakableBlobbers(cb GetInfoCallback, limit, offset int, active bool) { } // GetBlobbers obtains list of all active blobbers. -// # Inputs -// - cb: callback for checking result +// - cb: info callback instance, carries the response of the GET request to the sharders // - limit: how many blobbers should be fetched // - offset: how many blobbers should be skipped // - active: only fetch active blobbers @@ -1186,9 +1273,9 @@ func getBlobbersInternal(cb GetInfoCallback, active bool, limit, offset int, sta } var url = withParams(STORAGESC_GET_BLOBBERS, Params{ - "active": strconv.FormatBool(active), - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), + "active": strconv.FormatBool(active), + "offset": strconv.FormatInt(int64(offset), 10), + "limit": strconv.FormatInt(int64(limit), 10), "stakable": strconv.FormatBool(stakable), }) @@ -1196,6 +1283,8 @@ func getBlobbersInternal(cb GetInfoCallback, active bool, limit, offset int, sta } // GetBlobber obtains blobber information. +// - blobberID: blobber id +// - cb: info callback instance, carries the response of the GET request to the sharders func GetBlobber(blobberID string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1207,6 +1296,9 @@ func GetBlobber(blobberID string, cb GetInfoCallback) (err error) { return } +// GetValidator obtains validator information. +// - validatorID: validator id +// - cb: info callback instance, carries the response of the GET request to the sharders func GetValidator(validatorID string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1218,6 +1310,9 @@ func GetValidator(validatorID string, cb GetInfoCallback) (err error) { return } +// GetAuthorizer obtains authorizer information from the sharders. +// - authorizerID: authorizer id +// - cb: info callback instance, carries the response of the GET request to the sharders func GetAuthorizer(authorizerID string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1229,6 +1324,9 @@ func GetAuthorizer(authorizerID string, cb GetInfoCallback) (err error) { return } +// GetMinerSharder obtains miner sharder information from the sharders. +// - id: miner sharder id +// - cb: info callback instance, carries the response of the GET request to the sharders func GetMinerSharder(id string, cb GetInfoCallback) (err error) { if err = CheckConfig(); err != nil { return @@ -1291,6 +1389,9 @@ func Encrypt(key, text string) (string, error) { return hex.EncodeToString(response), nil } +// Decrypt decrypts encrypted text using the key. +// - key: key to use for decryption +// - text: text to decrypt func Decrypt(key, text string) (string, error) { keyBytes := []byte(key) textBytes, _ := hex.DecodeString(text) @@ -1322,6 +1423,7 @@ func CryptoJsDecrypt(passphrase, encryptedMessage string) (string, error) { return string(dec), nil } +// GetPublicEncryptionKey returns the public encryption key for the given mnemonic func GetPublicEncryptionKey(mnemonic string) (string, error) { encScheme := encryption.NewEncryptionScheme() _, err := encScheme.Initialize(mnemonic) diff --git a/zcncore/wallet_mobile.go b/zcncore/wallet_mobile.go index 30dc9718b..3eae952e8 100644 --- a/zcncore/wallet_mobile.go +++ b/zcncore/wallet_mobile.go @@ -7,7 +7,9 @@ import ( "github.com/0chain/gosdk/core/zcncrypto" ) +// Wallet interface to gather all wallet related functions type Wallet interface { + // Sign sign the hash Sign(hash string) (string, error) } @@ -15,6 +17,7 @@ type wallet struct { zcncrypto.Wallet } +// Sign sign the given string using the wallet's private key func (w *wallet) Sign(hash string) (string, error) { sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) err := sigScheme.SetPrivateKey(w.Keys[0].PrivateKey) @@ -24,8 +27,10 @@ func (w *wallet) Sign(hash string) (string, error) { return sigScheme.Sign(hash) } +// GetWalletBalance retrieve wallet balance from sharders +// - id: client id func GetWalletBalance(id string) (int64, error) { - balance, _ , err := getWalletBalance(id) + balance, _, err := getWalletBalance(id) if err != nil { return 0, err } diff --git a/zmagmacore/build/info.go b/zmagmacore/build/info.go index 69746403f..f75decb53 100644 --- a/zmagmacore/build/info.go +++ b/zmagmacore/build/info.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package build var ( diff --git a/zmagmacore/chain/entity.go b/zmagmacore/chain/entity.go index e0f687f9d..c57bdb243 100644 --- a/zmagmacore/chain/entity.go +++ b/zmagmacore/chain/entity.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package chain import ( diff --git a/zmagmacore/config/chain.go b/zmagmacore/config/chain.go index a96e59b0a..872deecd3 100644 --- a/zmagmacore/config/chain.go +++ b/zmagmacore/config/chain.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package config type ( diff --git a/zmagmacore/crypto/hash.go b/zmagmacore/crypto/hash.go index 9806762ff..cffb0d197 100644 --- a/zmagmacore/crypto/hash.go +++ b/zmagmacore/crypto/hash.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package crypto import ( diff --git a/zmagmacore/doc.go b/zmagmacore/doc.go new file mode 100644 index 000000000..99d371946 --- /dev/null +++ b/zmagmacore/doc.go @@ -0,0 +1,2 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. +package zmagmacore diff --git a/zmagmacore/errors/errors.go b/zmagmacore/errors/errors.go index 94ee1f84a..28e44b3e7 100644 --- a/zmagmacore/errors/errors.go +++ b/zmagmacore/errors/errors.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package errors import ( diff --git a/zmagmacore/http/client.go b/zmagmacore/http/client.go index acb2dbce9..318d6c14c 100644 --- a/zmagmacore/http/client.go +++ b/zmagmacore/http/client.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package http import ( diff --git a/zmagmacore/limiter/limiter.go b/zmagmacore/limiter/limiter.go index e697aa2d6..c324facc4 100644 --- a/zmagmacore/limiter/limiter.go +++ b/zmagmacore/limiter/limiter.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package limiter import ( diff --git a/zmagmacore/log/handler.go b/zmagmacore/log/handler.go index 0fe16b478..acafcf141 100644 --- a/zmagmacore/log/handler.go +++ b/zmagmacore/log/handler.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package log import ( diff --git a/zmagmacore/magmasc/acknowledgment.go b/zmagmacore/magmasc/acknowledgment.go index 08dc8b857..bef901ccf 100644 --- a/zmagmacore/magmasc/acknowledgment.go +++ b/zmagmacore/magmasc/acknowledgment.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package magmasc import ( diff --git a/zmagmacore/node/self.go b/zmagmacore/node/self.go index 125fb7155..563523484 100644 --- a/zmagmacore/node/self.go +++ b/zmagmacore/node/self.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package node import ( diff --git a/zmagmacore/registration/node.go b/zmagmacore/registration/node.go index 96b233def..b6f3a2184 100644 --- a/zmagmacore/registration/node.go +++ b/zmagmacore/registration/node.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package registration import ( diff --git a/zmagmacore/shutdown/shutdown.go b/zmagmacore/shutdown/shutdown.go index ad6dd3523..34837d8ad 100644 --- a/zmagmacore/shutdown/shutdown.go +++ b/zmagmacore/shutdown/shutdown.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package shutdown import ( diff --git a/zmagmacore/storage/interface.go b/zmagmacore/storage/interface.go index f056b4cdd..0a1b86aca 100644 --- a/zmagmacore/storage/interface.go +++ b/zmagmacore/storage/interface.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package storage import ( diff --git a/zmagmacore/time/time.go b/zmagmacore/time/time.go index 2095bbe32..3478d5314 100644 --- a/zmagmacore/time/time.go +++ b/zmagmacore/time/time.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package time import ( diff --git a/zmagmacore/transaction/callback.go b/zmagmacore/transaction/callback.go index a98a80124..c8b7356a8 100644 --- a/zmagmacore/transaction/callback.go +++ b/zmagmacore/transaction/callback.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package transaction import ( diff --git a/zmagmacore/wallet/balance.go b/zmagmacore/wallet/balance.go index fe4df64f9..1bd1c7165 100644 --- a/zmagmacore/wallet/balance.go +++ b/zmagmacore/wallet/balance.go @@ -1,3 +1,4 @@ +// DEPRECATED: This package is deprecated and will be removed in a future release. package wallet import ( diff --git a/znft/README.MD b/znft/README.MD index 3f1dd7bdb..78750d679 100644 --- a/znft/README.MD +++ b/znft/README.MD @@ -1,25 +1,1308 @@ -# 0Chain dStorage backed NFT API + -### Components and legend +# znft -`studio client` - UI for creating NFTs -`nft_factory_contract` - FactoryModuleERC721, FactoryModuleERC721Fixed, FactoryModuleERC721Random -`nft_contract` - DStorageERC721, DStorageERC721Fixed, DStorageERC721Pack, DStorageERC721Random -`royalty_contract` - is to handle routing for fee sharing -`0chain_api` - blobber storage API -`0nft` - is the service for exposing files on 0chain as a normal public url -`auth ticker` - is the auth ticket generated on the 0chain side and passed to the 0nft service +```go +import "github.com/0chain/gosdk/znft" +``` -### Current deployments +## Index -Network: **Rinkeby** +- [Constants](<#constants>) +- [Variables](<#variables>) +- [func AccountExists\(homedir, address string\) bool](<#AccountExists>) +- [func CreateEthClient\(ethereumNodeURL string\) \(\*ethclient.Client, error\)](<#CreateEthClient>) +- [func CreateKeyStorage\(homedir, password string\) error](<#CreateKeyStorage>) +- [func DeleteAccount\(homedir, address string\) bool](<#DeleteAccount>) +- [func GetConfigDir\(\) string](<#GetConfigDir>) +- [func ImportAccount\(homedir, mnemonic, password string\) \(string, error\)](<#ImportAccount>) +- [func ListStorageAccounts\(homedir string\) \[\]common.Address](<#ListStorageAccounts>) +- [func UpdateClientEthereumAddress\(homedir, address string\) \(err error\)](<#UpdateClientEthereumAddress>) +- [type Configuration](<#Configuration>) +- [type FactoryERC721](<#FactoryERC721>) + - [func \(s \*FactoryERC721\) CreateToken\(owner, name, symbol, uri string, max \*big.Int, data \[\]byte\) error](<#FactoryERC721.CreateToken>) +- [type FactoryFixed](<#FactoryFixed>) + - [func \(s \*FactoryFixed\) CreateToken\(owner, name, symbol, uri string, max, price, batch \*big.Int, calldata \[\]byte\) error](<#FactoryFixed.CreateToken>) +- [type FactoryPack](<#FactoryPack>) + - [func \(s \*FactoryPack\) CreateToken\(owner, name, symbol, uri string, max, price, batch \*big.Int, calldata \[\]byte\) error](<#FactoryPack.CreateToken>) +- [type FactoryRandom](<#FactoryRandom>) + - [func \(s \*FactoryRandom\) CreateToken\(owner, name, symbol, uri string, max, price, batch \*big.Int, calldata \[\]byte\) error](<#FactoryRandom.CreateToken>) +- [type IFactoryERC721](<#IFactoryERC721>) +- [type IFactoryFixed](<#IFactoryFixed>) +- [type IFactoryPack](<#IFactoryPack>) +- [type IFactoryRandom](<#IFactoryRandom>) +- [type IStorageECR721](<#IStorageECR721>) +- [type IStorageECR721Fixed](<#IStorageECR721Fixed>) +- [type IStorageECR721Pack](<#IStorageECR721Pack>) +- [type IStorageECR721Random](<#IStorageECR721Random>) +- [type StorageECR721](<#StorageECR721>) + - [func \(s \*StorageECR721\) Allocation\(\) \(string, error\)](<#StorageECR721.Allocation>) + - [func \(s \*StorageECR721\) Batch\(\) \(\*big.Int, error\)](<#StorageECR721.Batch>) + - [func \(s \*StorageECR721\) Max\(\) \(\*big.Int, error\)](<#StorageECR721.Max>) + - [func \(s \*StorageECR721\) Mint\(amount \*big.Int\) error](<#StorageECR721.Mint>) + - [func \(s \*StorageECR721\) MintOwner\(amount \*big.Int\) error](<#StorageECR721.MintOwner>) + - [func \(s \*StorageECR721\) Mintable\(\) \(bool, error\)](<#StorageECR721.Mintable>) + - [func \(s \*StorageECR721\) Price\(\) \(\*big.Int, error\)](<#StorageECR721.Price>) + - [func \(s \*StorageECR721\) Receiver\(\) \(string, error\)](<#StorageECR721.Receiver>) + - [func \(s \*StorageECR721\) Royalty\(\) \(\*big.Int, error\)](<#StorageECR721.Royalty>) + - [func \(s \*StorageECR721\) RoyaltyInfo\(tokenId, salePrice \*big.Int\) \(string, \*big.Int, error\)](<#StorageECR721.RoyaltyInfo>) + - [func \(s \*StorageECR721\) SetAllocation\(allocation string\) error](<#StorageECR721.SetAllocation>) + - [func \(s \*StorageECR721\) SetMintable\(status bool\) error](<#StorageECR721.SetMintable>) + - [func \(s \*StorageECR721\) SetReceiver\(receiver string\) error](<#StorageECR721.SetReceiver>) + - [func \(s \*StorageECR721\) SetRoyalty\(sum \*big.Int\) error](<#StorageECR721.SetRoyalty>) + - [func \(s \*StorageECR721\) SetURI\(uri string\) error](<#StorageECR721.SetURI>) + - [func \(s \*StorageECR721\) SetURIFallback\(uri string\) error](<#StorageECR721.SetURIFallback>) + - [func \(s \*StorageECR721\) TokenURIFallback\(token \*big.Int\) \(string, error\)](<#StorageECR721.TokenURIFallback>) + - [func \(s \*StorageECR721\) Total\(\) \(\*big.Int, error\)](<#StorageECR721.Total>) + - [func \(s \*StorageECR721\) Uri\(\) \(string, error\)](<#StorageECR721.Uri>) + - [func \(s \*StorageECR721\) UriFallback\(\) \(string, error\)](<#StorageECR721.UriFallback>) + - [func \(s \*StorageECR721\) Withdraw\(\) error](<#StorageECR721.Withdraw>) +- [type StorageECR721Fixed](<#StorageECR721Fixed>) + - [func \(s \*StorageECR721Fixed\) Allocation\(\) \(string, error\)](<#StorageECR721Fixed.Allocation>) + - [func \(s \*StorageECR721Fixed\) Batch\(\) \(\*big.Int, error\)](<#StorageECR721Fixed.Batch>) + - [func \(s \*StorageECR721Fixed\) Max\(\) \(\*big.Int, error\)](<#StorageECR721Fixed.Max>) + - [func \(s \*StorageECR721Fixed\) Mint\(amount \*big.Int\) error](<#StorageECR721Fixed.Mint>) + - [func \(s \*StorageECR721Fixed\) MintOwner\(amount \*big.Int\) error](<#StorageECR721Fixed.MintOwner>) + - [func \(s \*StorageECR721Fixed\) Mintable\(\) \(bool, error\)](<#StorageECR721Fixed.Mintable>) + - [func \(s \*StorageECR721Fixed\) Price\(\) \(\*big.Int, error\)](<#StorageECR721Fixed.Price>) + - [func \(s \*StorageECR721Fixed\) Receiver\(\) \(string, error\)](<#StorageECR721Fixed.Receiver>) + - [func \(s \*StorageECR721Fixed\) Royalty\(\) \(\*big.Int, error\)](<#StorageECR721Fixed.Royalty>) + - [func \(s \*StorageECR721Fixed\) RoyaltyInfo\(tokenId, salePrice \*big.Int\) \(string, \*big.Int, error\)](<#StorageECR721Fixed.RoyaltyInfo>) + - [func \(s \*StorageECR721Fixed\) SetAllocation\(allocation string\) error](<#StorageECR721Fixed.SetAllocation>) + - [func \(s \*StorageECR721Fixed\) SetMintable\(status bool\) error](<#StorageECR721Fixed.SetMintable>) + - [func \(s \*StorageECR721Fixed\) SetReceiver\(receiver string\) error](<#StorageECR721Fixed.SetReceiver>) + - [func \(s \*StorageECR721Fixed\) SetRoyalty\(sum \*big.Int\) error](<#StorageECR721Fixed.SetRoyalty>) + - [func \(s \*StorageECR721Fixed\) SetURI\(uri string\) error](<#StorageECR721Fixed.SetURI>) + - [func \(s \*StorageECR721Fixed\) SetURIFallback\(uri string\) error](<#StorageECR721Fixed.SetURIFallback>) + - [func \(s \*StorageECR721Fixed\) TokenURI\(token \*big.Int\) \(string, error\)](<#StorageECR721Fixed.TokenURI>) + - [func \(s \*StorageECR721Fixed\) TokenURIFallback\(token \*big.Int\) \(string, error\)](<#StorageECR721Fixed.TokenURIFallback>) + - [func \(s \*StorageECR721Fixed\) Total\(\) \(\*big.Int, error\)](<#StorageECR721Fixed.Total>) + - [func \(s \*StorageECR721Fixed\) Uri\(\) \(string, error\)](<#StorageECR721Fixed.Uri>) + - [func \(s \*StorageECR721Fixed\) UriFallback\(\) \(string, error\)](<#StorageECR721Fixed.UriFallback>) + - [func \(s \*StorageECR721Fixed\) Withdraw\(\) error](<#StorageECR721Fixed.Withdraw>) +- [type StorageECR721Pack](<#StorageECR721Pack>) + - [func \(s \*StorageECR721Pack\) Allocation\(\) \(string, error\)](<#StorageECR721Pack.Allocation>) + - [func \(s \*StorageECR721Pack\) Batch\(\) \(\*big.Int, error\)](<#StorageECR721Pack.Batch>) + - [func \(s \*StorageECR721Pack\) Max\(\) \(\*big.Int, error\)](<#StorageECR721Pack.Max>) + - [func \(s \*StorageECR721Pack\) Mint\(amount \*big.Int\) error](<#StorageECR721Pack.Mint>) + - [func \(s \*StorageECR721Pack\) MintOwner\(amount \*big.Int\) error](<#StorageECR721Pack.MintOwner>) + - [func \(s \*StorageECR721Pack\) Mintable\(\) \(bool, error\)](<#StorageECR721Pack.Mintable>) + - [func \(s \*StorageECR721Pack\) Price\(\) \(\*big.Int, error\)](<#StorageECR721Pack.Price>) + - [func \(s \*StorageECR721Pack\) Receiver\(\) \(string, error\)](<#StorageECR721Pack.Receiver>) + - [func \(s \*StorageECR721Pack\) Redeem\(tokenId \*big.Int\) error](<#StorageECR721Pack.Redeem>) + - [func \(s \*StorageECR721Pack\) Reveal\(tokenId \*big.Int\) error](<#StorageECR721Pack.Reveal>) + - [func \(s \*StorageECR721Pack\) Royalty\(\) \(\*big.Int, error\)](<#StorageECR721Pack.Royalty>) + - [func \(s \*StorageECR721Pack\) RoyaltyInfo\(tokenId, salePrice \*big.Int\) \(string, \*big.Int, error\)](<#StorageECR721Pack.RoyaltyInfo>) + - [func \(s \*StorageECR721Pack\) SetAllocation\(allocation string\) error](<#StorageECR721Pack.SetAllocation>) + - [func \(s \*StorageECR721Pack\) SetClosed\(closed string\) error](<#StorageECR721Pack.SetClosed>) + - [func \(s \*StorageECR721Pack\) SetMintable\(status bool\) error](<#StorageECR721Pack.SetMintable>) + - [func \(s \*StorageECR721Pack\) SetOpened\(opened string\) error](<#StorageECR721Pack.SetOpened>) + - [func \(s \*StorageECR721Pack\) SetReceiver\(receiver string\) error](<#StorageECR721Pack.SetReceiver>) + - [func \(s \*StorageECR721Pack\) SetRoyalty\(sum \*big.Int\) error](<#StorageECR721Pack.SetRoyalty>) + - [func \(s \*StorageECR721Pack\) SetURI\(uri string\) error](<#StorageECR721Pack.SetURI>) + - [func \(s \*StorageECR721Pack\) SetURIFallback\(uri string\) error](<#StorageECR721Pack.SetURIFallback>) + - [func \(s \*StorageECR721Pack\) TokenURI\(tokenId \*big.Int\) \(string, error\)](<#StorageECR721Pack.TokenURI>) + - [func \(s \*StorageECR721Pack\) TokenURIFallback\(tokenId \*big.Int\) \(string, error\)](<#StorageECR721Pack.TokenURIFallback>) + - [func \(s \*StorageECR721Pack\) Total\(\) \(\*big.Int, error\)](<#StorageECR721Pack.Total>) + - [func \(s \*StorageECR721Pack\) Uri\(\) \(string, error\)](<#StorageECR721Pack.Uri>) + - [func \(s \*StorageECR721Pack\) UriFallback\(\) \(string, error\)](<#StorageECR721Pack.UriFallback>) + - [func \(s \*StorageECR721Pack\) Withdraw\(\) error](<#StorageECR721Pack.Withdraw>) +- [type StorageECR721Random](<#StorageECR721Random>) + - [func \(s \*StorageECR721Random\) Mint\(amount \*big.Int\) error](<#StorageECR721Random.Mint>) + - [func \(s \*StorageECR721Random\) MintOwner\(amount \*big.Int\) error](<#StorageECR721Random.MintOwner>) + - [func \(s \*StorageECR721Random\) Price\(\) \(\*big.Int, error\)](<#StorageECR721Random.Price>) + - [func \(s \*StorageECR721Random\) Reveal\(tokens \[\]\*big.Int\) error](<#StorageECR721Random.Reveal>) + - [func \(s \*StorageECR721Random\) SetHidden\(hidden string\) error](<#StorageECR721Random.SetHidden>) + - [func \(s \*StorageECR721Random\) SetPack\(address common.Address\) error](<#StorageECR721Random.SetPack>) + - [func \(s \*StorageECR721Random\) SetRevealable\(status bool\) error](<#StorageECR721Random.SetRevealable>) + - [func \(s \*StorageECR721Random\) TokenURI\(token \*big.Int\) \(string, error\)](<#StorageECR721Random.TokenURI>) + - [func \(s \*StorageECR721Random\) TokenURIFallback\(token \*big.Int\) \(string, error\)](<#StorageECR721Random.TokenURIFallback>) +- [type Znft](<#Znft>) + - [func NewNFTApplication\(c \*Configuration\) \*Znft](<#NewNFTApplication>) + - [func \(app \*Znft\) CreateFactoryERC721FixedSession\(ctx context.Context, addr string\) \(IFactoryFixed, error\)](<#Znft.CreateFactoryERC721FixedSession>) + - [func \(app \*Znft\) CreateFactoryERC721PackSession\(ctx context.Context, addr string\) \(IFactoryPack, error\)](<#Znft.CreateFactoryERC721PackSession>) + - [func \(app \*Znft\) CreateFactoryERC721RandomSession\(ctx context.Context, addr string\) \(IFactoryRandom, error\)](<#Znft.CreateFactoryERC721RandomSession>) + - [func \(app \*Znft\) CreateFactoryERC721Session\(ctx context.Context, addr string\) \(IFactoryERC721, error\)](<#Znft.CreateFactoryERC721Session>) + - [func \(app \*Znft\) CreateStorageERC721FixedSession\(ctx context.Context, addr string\) \(IStorageECR721Fixed, error\)](<#Znft.CreateStorageERC721FixedSession>) + - [func \(app \*Znft\) CreateStorageERC721PackSession\(ctx context.Context, addr string\) \(IStorageECR721Pack, error\)](<#Znft.CreateStorageERC721PackSession>) + - [func \(app \*Znft\) CreateStorageERC721RandomSession\(ctx context.Context, addr string\) \(IStorageECR721Random, error\)](<#Znft.CreateStorageERC721RandomSession>) + - [func \(app \*Znft\) CreateStorageERC721Session\(ctx context.Context, addr string\) \(IStorageECR721, error\)](<#Znft.CreateStorageERC721Session>) -Factory: **0xD98602749e7f46036d496e8D3deb6eb9F90996a6** -## Create a new NFT collection +## Constants -## NFT View + -## NFT Trading +```go +const ( + ContractStorageERC721Name = "StorageERC721" + ContractStorageERC721FixedName = "StorageERC721Fixed" + ContractStorageERC721PackName = "StorageERC721Pack" + ContractStorageERC721RandomName = "StorageERC721Random" + Withdraw = "withdraw" + SetReceiver = "setReceiver" + SetRoyalty = "setRoyalty" + SetMintable = "setMintable" + SetAllocation = "setAllocation" + SetURI = "setURI" + TokenURIFallback = "tokenURIFallback" + TokenURI = "tokenURI" + Price = "price" + Mint = "mint" + MintOwner = "mintOwner" + RoyaltyInfo = "royaltyInfo" +) +``` -![nft_dstorage_activity_diagram.png](./assets/1652602057996-nft_dstorage_activity_diagram.png) + + +```go +const ( + ConfigFile = "config.yaml" + WalletDir = "wallets" +) +``` + +## Variables + + + +```go +var Logger logger.Logger +``` + + +## func [AccountExists]() + +```go +func AccountExists(homedir, address string) bool +``` + +AccountExists checks if account exists + + +## func [CreateEthClient]() + +```go +func CreateEthClient(ethereumNodeURL string) (*ethclient.Client, error) +``` + + + + +## func [CreateKeyStorage]() + +```go +func CreateKeyStorage(homedir, password string) error +``` + +CreateKeyStorage create, restore or unlock key storage + + +## func [DeleteAccount]() + +```go +func DeleteAccount(homedir, address string) bool +``` + +DeleteAccount deletes account from wallet + + +## func [GetConfigDir]() + +```go +func GetConfigDir() string +``` + + + + +## func [ImportAccount]() + +```go +func ImportAccount(homedir, mnemonic, password string) (string, error) +``` + +ImportAccount imports account using mnemonic password is used to lock and unlock keystorage before signing transaction + + +## func [ListStorageAccounts]() + +```go +func ListStorageAccounts(homedir string) []common.Address +``` + +ListStorageAccounts List available accounts + + +## func [UpdateClientEthereumAddress]() + +```go +func UpdateClientEthereumAddress(homedir, address string) (err error) +``` + +UpdateClientEthereumAddress updates Ethereum address + + +## type [Configuration]() + + + +```go +type Configuration struct { + FactoryAddress string // FactoryAddress address + FactoryModuleERC721Address string // FactoryModuleERC721Address address + FactoryModuleERC721PackedAddress string // FactoryModuleERC721PackedAddress address + FactoryModuleERC721FixedAddress string // FactoryModuleERC721FixedAddress address + FactoryModuleERC721RandomAddress string // FactoryModuleERC721RandomAddress address + EthereumNodeURL string // EthereumNodeURL URL of ethereum RPC node (infura or alchemy) + WalletAddress string // WalletAddress client address + VaultPassword string // VaultPassword used to sign transactions on behalf of the client + Homedir string // Homedir is a client config folder + Value int64 // Value to execute Ethereum smart contracts (default = 0) +} +``` + + +## type [FactoryERC721]() + + + +```go +type FactoryERC721 struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*FactoryERC721\) [CreateToken]() + +```go +func (s *FactoryERC721) CreateToken(owner, name, symbol, uri string, max *big.Int, data []byte) error +``` + + + + +## type [FactoryFixed]() + + + +```go +type FactoryFixed struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*FactoryFixed\) [CreateToken]() + +```go +func (s *FactoryFixed) CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error +``` + + + + +## type [FactoryPack]() + + + +```go +type FactoryPack struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*FactoryPack\) [CreateToken]() + +```go +func (s *FactoryPack) CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error +``` + + + + +## type [FactoryRandom]() + + + +```go +type FactoryRandom struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*FactoryRandom\) [CreateToken]() + +```go +func (s *FactoryRandom) CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error +``` + + + + +## type [IFactoryERC721]() + + + +```go +type IFactoryERC721 interface { + CreateToken(owner, name, symbol, uri string, max *big.Int, data []byte) error +} +``` + + +## type [IFactoryFixed]() + + + +```go +type IFactoryFixed interface { + CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error +} +``` + + +## type [IFactoryPack]() + + + +```go +type IFactoryPack interface { + CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error +} +``` + + +## type [IFactoryRandom]() + + + +```go +type IFactoryRandom interface { + CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error +} +``` + + +## type [IStorageECR721]() + + + +```go +type IStorageECR721 interface { + Withdraw() error + SetReceiver(receiver string) error + SetRoyalty(sum *big.Int) error + SetMintable(status bool) error + SetAllocation(allocation string) error + SetURI(uri string) error + SetURIFallback(uri string) error + TokenURIFallback(token *big.Int) (string, error) + Price() (*big.Int, error) + Mint(amount *big.Int) error + MintOwner(amount *big.Int) error + RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) + Max() (*big.Int, error) // Fields + Total() (*big.Int, error) + Batch() (*big.Int, error) + Mintable() (bool, error) + Allocation() (string, error) + Uri() (string, error) + UriFallback() (string, error) + Royalty() (*big.Int, error) + Receiver() (string, error) +} +``` + + +## type [IStorageECR721Fixed]() + + + +```go +type IStorageECR721Fixed interface { + IStorageECR721 +} +``` + + +## type [IStorageECR721Pack]() + + + +```go +type IStorageECR721Pack interface { + IStorageECR721Fixed + MintOwner(amount *big.Int) error + Mint(amount *big.Int) error + Reveal(tokenId *big.Int) error + Redeem(tokenId *big.Int) error + TokenURI(tokenId *big.Int) (string, error) + TokenURIFallback(tokenId *big.Int) (string, error) + SetClosed(closed string) error + SetOpened(opened string) error +} +``` + + +## type [IStorageECR721Random]() + + + +```go +type IStorageECR721Random interface { + MintOwner(amount *big.Int) error + Mint(amount *big.Int) error + Reveal(tokens []*big.Int) error + TokenURI(token *big.Int) (string, error) + TokenURIFallback(token *big.Int) (string, error) + SetHidden(hidden string) error + SetPack(address common.Address) error + SetRevealable(status bool) error + Price() (*big.Int, error) +} +``` + + +## type [StorageECR721]() + + + +```go +type StorageECR721 struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*StorageECR721\) [Allocation]() + +```go +func (s *StorageECR721) Allocation() (string, error) +``` + + + + +### func \(\*StorageECR721\) [Batch]() + +```go +func (s *StorageECR721) Batch() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721\) [Max]() + +```go +func (s *StorageECR721) Max() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721\) [Mint]() + +```go +func (s *StorageECR721) Mint(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721\) [MintOwner]() + +```go +func (s *StorageECR721) MintOwner(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721\) [Mintable]() + +```go +func (s *StorageECR721) Mintable() (bool, error) +``` + + + + +### func \(\*StorageECR721\) [Price]() + +```go +func (s *StorageECR721) Price() (*big.Int, error) +``` + +Price returns price + + +### func \(\*StorageECR721\) [Receiver]() + +```go +func (s *StorageECR721) Receiver() (string, error) +``` + + + + +### func \(\*StorageECR721\) [Royalty]() + +```go +func (s *StorageECR721) Royalty() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721\) [RoyaltyInfo]() + +```go +func (s *StorageECR721) RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) +``` + + + + +### func \(\*StorageECR721\) [SetAllocation]() + +```go +func (s *StorageECR721) SetAllocation(allocation string) error +``` + +SetAllocation updates allocation + + +### func \(\*StorageECR721\) [SetMintable]() + +```go +func (s *StorageECR721) SetMintable(status bool) error +``` + +SetMintable updates mintable state + + +### func \(\*StorageECR721\) [SetReceiver]() + +```go +func (s *StorageECR721) SetReceiver(receiver string) error +``` + +SetReceiver eth balance from token contract \- setReceiver\(address receiver_\) + + +### func \(\*StorageECR721\) [SetRoyalty]() + +```go +func (s *StorageECR721) SetRoyalty(sum *big.Int) error +``` + +SetRoyalty eth balance from token contract \- setReceiver\(address receiver_\) + + +### func \(\*StorageECR721\) [SetURI]() + +```go +func (s *StorageECR721) SetURI(uri string) error +``` + +SetURI updates uri + + +### func \(\*StorageECR721\) [SetURIFallback]() + +```go +func (s *StorageECR721) SetURIFallback(uri string) error +``` + + + + +### func \(\*StorageECR721\) [TokenURIFallback]() + +```go +func (s *StorageECR721) TokenURIFallback(token *big.Int) (string, error) +``` + + + + +### func \(\*StorageECR721\) [Total]() + +```go +func (s *StorageECR721) Total() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721\) [Uri]() + +```go +func (s *StorageECR721) Uri() (string, error) +``` + + + + +### func \(\*StorageECR721\) [UriFallback]() + +```go +func (s *StorageECR721) UriFallback() (string, error) +``` + + + + +### func \(\*StorageECR721\) [Withdraw]() + +```go +func (s *StorageECR721) Withdraw() error +``` + +Withdraw eth balance from token contract \- withdraw\(\) + + +## type [StorageECR721Fixed]() + + + +```go +type StorageECR721Fixed struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*StorageECR721Fixed\) [Allocation]() + +```go +func (s *StorageECR721Fixed) Allocation() (string, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Batch]() + +```go +func (s *StorageECR721Fixed) Batch() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Max]() + +```go +func (s *StorageECR721Fixed) Max() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Mint]() + +```go +func (s *StorageECR721Fixed) Mint(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721Fixed\) [MintOwner]() + +```go +func (s *StorageECR721Fixed) MintOwner(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721Fixed\) [Mintable]() + +```go +func (s *StorageECR721Fixed) Mintable() (bool, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Price]() + +```go +func (s *StorageECR721Fixed) Price() (*big.Int, error) +``` + +Price returns price + + +### func \(\*StorageECR721Fixed\) [Receiver]() + +```go +func (s *StorageECR721Fixed) Receiver() (string, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Royalty]() + +```go +func (s *StorageECR721Fixed) Royalty() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [RoyaltyInfo]() + +```go +func (s *StorageECR721Fixed) RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [SetAllocation]() + +```go +func (s *StorageECR721Fixed) SetAllocation(allocation string) error +``` + +SetAllocation updates allocation + + +### func \(\*StorageECR721Fixed\) [SetMintable]() + +```go +func (s *StorageECR721Fixed) SetMintable(status bool) error +``` + +SetMintable updates mintable state + + +### func \(\*StorageECR721Fixed\) [SetReceiver]() + +```go +func (s *StorageECR721Fixed) SetReceiver(receiver string) error +``` + +SetReceiver eth balance from token contract \- setReceiver\(address receiver_\) + + +### func \(\*StorageECR721Fixed\) [SetRoyalty]() + +```go +func (s *StorageECR721Fixed) SetRoyalty(sum *big.Int) error +``` + +SetRoyalty eth balance from token contract \- setReceiver\(address receiver_\) + + +### func \(\*StorageECR721Fixed\) [SetURI]() + +```go +func (s *StorageECR721Fixed) SetURI(uri string) error +``` + +SetURI updates uri + + +### func \(\*StorageECR721Fixed\) [SetURIFallback]() + +```go +func (s *StorageECR721Fixed) SetURIFallback(uri string) error +``` + + + + +### func \(\*StorageECR721Fixed\) [TokenURI]() + +```go +func (s *StorageECR721Fixed) TokenURI(token *big.Int) (string, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [TokenURIFallback]() + +```go +func (s *StorageECR721Fixed) TokenURIFallback(token *big.Int) (string, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Total]() + +```go +func (s *StorageECR721Fixed) Total() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Uri]() + +```go +func (s *StorageECR721Fixed) Uri() (string, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [UriFallback]() + +```go +func (s *StorageECR721Fixed) UriFallback() (string, error) +``` + + + + +### func \(\*StorageECR721Fixed\) [Withdraw]() + +```go +func (s *StorageECR721Fixed) Withdraw() error +``` + +Withdraw eth balance from token contract \- withdraw\(\) + + +## type [StorageECR721Pack]() + + + +```go +type StorageECR721Pack struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*StorageECR721Pack\) [Allocation]() + +```go +func (s *StorageECR721Pack) Allocation() (string, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Batch]() + +```go +func (s *StorageECR721Pack) Batch() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Max]() + +```go +func (s *StorageECR721Pack) Max() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Mint]() + +```go +func (s *StorageECR721Pack) Mint(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721Pack\) [MintOwner]() + +```go +func (s *StorageECR721Pack) MintOwner(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721Pack\) [Mintable]() + +```go +func (s *StorageECR721Pack) Mintable() (bool, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Price]() + +```go +func (s *StorageECR721Pack) Price() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Receiver]() + +```go +func (s *StorageECR721Pack) Receiver() (string, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Redeem]() + +```go +func (s *StorageECR721Pack) Redeem(tokenId *big.Int) error +``` + + + + +### func \(\*StorageECR721Pack\) [Reveal]() + +```go +func (s *StorageECR721Pack) Reveal(tokenId *big.Int) error +``` + + + + +### func \(\*StorageECR721Pack\) [Royalty]() + +```go +func (s *StorageECR721Pack) Royalty() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Pack\) [RoyaltyInfo]() + +```go +func (s *StorageECR721Pack) RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) +``` + + + + +### func \(\*StorageECR721Pack\) [SetAllocation]() + +```go +func (s *StorageECR721Pack) SetAllocation(allocation string) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetClosed]() + +```go +func (s *StorageECR721Pack) SetClosed(closed string) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetMintable]() + +```go +func (s *StorageECR721Pack) SetMintable(status bool) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetOpened]() + +```go +func (s *StorageECR721Pack) SetOpened(opened string) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetReceiver]() + +```go +func (s *StorageECR721Pack) SetReceiver(receiver string) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetRoyalty]() + +```go +func (s *StorageECR721Pack) SetRoyalty(sum *big.Int) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetURI]() + +```go +func (s *StorageECR721Pack) SetURI(uri string) error +``` + + + + +### func \(\*StorageECR721Pack\) [SetURIFallback]() + +```go +func (s *StorageECR721Pack) SetURIFallback(uri string) error +``` + + + + +### func \(\*StorageECR721Pack\) [TokenURI]() + +```go +func (s *StorageECR721Pack) TokenURI(tokenId *big.Int) (string, error) +``` + + + + +### func \(\*StorageECR721Pack\) [TokenURIFallback]() + +```go +func (s *StorageECR721Pack) TokenURIFallback(tokenId *big.Int) (string, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Total]() + +```go +func (s *StorageECR721Pack) Total() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Uri]() + +```go +func (s *StorageECR721Pack) Uri() (string, error) +``` + + + + +### func \(\*StorageECR721Pack\) [UriFallback]() + +```go +func (s *StorageECR721Pack) UriFallback() (string, error) +``` + + + + +### func \(\*StorageECR721Pack\) [Withdraw]() + +```go +func (s *StorageECR721Pack) Withdraw() error +``` + + + + +## type [StorageECR721Random]() + + + +```go +type StorageECR721Random struct { + // contains filtered or unexported fields +} +``` + + +### func \(\*StorageECR721Random\) [Mint]() + +```go +func (s *StorageECR721Random) Mint(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721Random\) [MintOwner]() + +```go +func (s *StorageECR721Random) MintOwner(amount *big.Int) error +``` + + + + +### func \(\*StorageECR721Random\) [Price]() + +```go +func (s *StorageECR721Random) Price() (*big.Int, error) +``` + + + + +### func \(\*StorageECR721Random\) [Reveal]() + +```go +func (s *StorageECR721Random) Reveal(tokens []*big.Int) error +``` + + + + +### func \(\*StorageECR721Random\) [SetHidden]() + +```go +func (s *StorageECR721Random) SetHidden(hidden string) error +``` + + + + +### func \(\*StorageECR721Random\) [SetPack]() + +```go +func (s *StorageECR721Random) SetPack(address common.Address) error +``` + + + + +### func \(\*StorageECR721Random\) [SetRevealable]() + +```go +func (s *StorageECR721Random) SetRevealable(status bool) error +``` + + + + +### func \(\*StorageECR721Random\) [TokenURI]() + +```go +func (s *StorageECR721Random) TokenURI(token *big.Int) (string, error) +``` + + + + +### func \(\*StorageECR721Random\) [TokenURIFallback]() + +```go +func (s *StorageECR721Random) TokenURIFallback(token *big.Int) (string, error) +``` + + + + +## type [Znft]() + + + +```go +type Znft struct { + // contains filtered or unexported fields +} +``` + + +### func [NewNFTApplication]() + +```go +func NewNFTApplication(c *Configuration) *Znft +``` + + + + +### func \(\*Znft\) [CreateFactoryERC721FixedSession]() + +```go +func (app *Znft) CreateFactoryERC721FixedSession(ctx context.Context, addr string) (IFactoryFixed, error) +``` + + + + +### func \(\*Znft\) [CreateFactoryERC721PackSession]() + +```go +func (app *Znft) CreateFactoryERC721PackSession(ctx context.Context, addr string) (IFactoryPack, error) +``` + + + + +### func \(\*Znft\) [CreateFactoryERC721RandomSession]() + +```go +func (app *Znft) CreateFactoryERC721RandomSession(ctx context.Context, addr string) (IFactoryRandom, error) +``` + + + + +### func \(\*Znft\) [CreateFactoryERC721Session]() + +```go +func (app *Znft) CreateFactoryERC721Session(ctx context.Context, addr string) (IFactoryERC721, error) +``` + + + + +### func \(\*Znft\) [CreateStorageERC721FixedSession]() + +```go +func (app *Znft) CreateStorageERC721FixedSession(ctx context.Context, addr string) (IStorageECR721Fixed, error) +``` + + + + +### func \(\*Znft\) [CreateStorageERC721PackSession]() + +```go +func (app *Znft) CreateStorageERC721PackSession(ctx context.Context, addr string) (IStorageECR721Pack, error) +``` + + + + +### func \(\*Znft\) [CreateStorageERC721RandomSession]() + +```go +func (app *Znft) CreateStorageERC721RandomSession(ctx context.Context, addr string) (IStorageECR721Random, error) +``` + + + + +### func \(\*Znft\) [CreateStorageERC721Session]() + +```go +func (app *Znft) CreateStorageERC721Session(ctx context.Context, addr string) (IStorageECR721, error) +``` + + + +Generated by [gomarkdoc]() diff --git a/znft/contracts/doc.go b/znft/contracts/doc.go new file mode 100644 index 000000000..1c2861cff --- /dev/null +++ b/znft/contracts/doc.go @@ -0,0 +1,2 @@ +// AUTOGENERATED! All sub-packages and modules are auto-generated and should not be modified. +package contracts \ No newline at end of file diff --git a/znft/doc.go b/znft/doc.go new file mode 100644 index 000000000..fd18d5ce3 --- /dev/null +++ b/znft/doc.go @@ -0,0 +1,4 @@ +// Provides methods and types to interact with the ERC-721 NFT smart contract on the Ethereum blockchain. +// Makes it possible for our clients to create and manage their NFTs using the Chalk apps. +// It defines the functionality to Mint/Burn ERC-721 NFTs. +package znft diff --git a/znft/example/main.go b/znft/example/main.go index 35b8f5d87..1b0f1d890 100644 --- a/znft/example/main.go +++ b/znft/example/main.go @@ -1,6 +1,7 @@ //go:build ignore // +build ignore +// Example usage of the znft package - do not use. package main import (