From f9eb6751cae3a29bf73cdaee396c7e1cc8d0fff9 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Mon, 22 Jul 2024 03:17:50 +0530 Subject: [PATCH 001/107] add version marker and block hasher --- zboxcore/blockchain/entity.go | 20 ++- zboxcore/marker/versionmarker.go | 50 ++++++ zboxcore/sdk/allocation.go | 10 +- zboxcore/sdk/chunked_upload_blobber.go | 3 - zboxcore/sdk/chunked_upload_form_builder.go | 56 ++---- zboxcore/sdk/chunked_upload_hasher.go | 35 +++- zboxcore/sdk/chunked_upload_model.go | 21 +-- zboxcore/sdk/chunked_upload_process.go | 9 +- zboxcore/sdk/chunked_upload_process_js.go | 11 +- zboxcore/sdk/commitworker.go | 182 +++----------------- zboxcore/sdk/multi_operation_worker.go | 8 + zboxcore/sdk/rollback.go | 114 +++++------- 12 files changed, 199 insertions(+), 320 deletions(-) create mode 100644 zboxcore/marker/versionmarker.go diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go index e5c85b5e0..8e562a8c7 100644 --- a/zboxcore/blockchain/entity.go +++ b/zboxcore/blockchain/entity.go @@ -2,11 +2,12 @@ package blockchain import ( "encoding/json" - "github.com/0chain/gosdk/core/util" "math" "sync" "sync/atomic" + "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk/core/conf" "github.com/0chain/gosdk/core/node" ) @@ -51,16 +52,16 @@ type ChainConfig struct { // StakePoolSettings information. type StakePoolSettings 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"` } // UpdateStakePoolSettings information. type UpdateStakePoolSettings 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 ValidationNode struct { @@ -76,8 +77,9 @@ type UpdateValidationNode struct { } type StorageNode struct { - ID string `json:"id"` - Baseurl string `json:"url"` + ID string `json:"id"` + Baseurl string `json:"url"` + AllocationVersion int64 `json:"-"` skip uint64 `json:"-"` // skip on error } diff --git a/zboxcore/marker/versionmarker.go b/zboxcore/marker/versionmarker.go new file mode 100644 index 000000000..b150a3446 --- /dev/null +++ b/zboxcore/marker/versionmarker.go @@ -0,0 +1,50 @@ +package marker + +import ( + "fmt" + + "github.com/0chain/errors" + "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/zboxcore/client" +) + +type VersionMarker struct { + ClientID string `json:"client_id"` + BlobberID string `json:"blobber_id"` + AllocationID string `json:"allocation_id"` + Version int64 `json:"version"` + Timestamp int64 `json:"timestamp"` + Signature string `json:"signature"` + IsRepair bool `json:"is_repair"` + RepairVersion int64 `json:"repair_version"` + RepairOffset string `json:"repair_offset"` +} + +func (vm *VersionMarker) GetHashData() string { + return fmt.Sprintf("%s:%s:%s:%d:%d", vm.AllocationID, vm.ClientID, vm.BlobberID, vm.Version, vm.Timestamp) +} + +func (vm *VersionMarker) GetHash() string { + sigData := vm.GetHashData() + return encryption.Hash(sigData) +} + +func (vm *VersionMarker) Sign() error { + var err error + vm.Signature, err = client.Sign(vm.GetHash()) + return err +} + +func (vm *VersionMarker) VerifySignature(clientPublicKey string) error { + hashData := vm.GetHashData() + signatureHash := encryption.Hash(hashData) + sigOK, err := sys.Verify(vm.Signature, signatureHash) + if err != nil { + return errors.New("write_marker_validation_failed", "Error during verifying signature. "+err.Error()) + } + if !sigOK { + return errors.New("write_marker_validation_failed", "Write marker signature is not valid") + } + return nil +} diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 0c53eacfd..2a44fe467 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -722,7 +722,7 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { } else { markerChan <- &RollbackBlobber{ blobber: blobber, - lpm: wr, + lvm: wr, commitResult: &CommitResult{}, } } @@ -737,15 +737,15 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { for rb := range markerChan { - if rb == nil || rb.lpm.LatestWM == nil { + if rb == nil || rb.lvm == nil { continue } - if _, ok := versionMap[rb.lpm.LatestWM.Timestamp]; !ok { - versionMap[rb.lpm.LatestWM.Timestamp] = make([]*RollbackBlobber, 0) + if _, ok := versionMap[rb.lvm.VersionMarker.Version]; !ok { + versionMap[rb.lvm.VersionMarker.Version] = make([]*RollbackBlobber, 0) } - versionMap[rb.lpm.LatestWM.Timestamp] = append(versionMap[rb.lpm.LatestWM.Timestamp], rb) + versionMap[rb.lvm.VersionMarker.Version] = append(versionMap[rb.lvm.VersionMarker.Version], rb) if len(versionMap) > 2 { return false, fmt.Errorf("more than 2 versions found") diff --git a/zboxcore/sdk/chunked_upload_blobber.go b/zboxcore/sdk/chunked_upload_blobber.go index 886464aff..430c1920a 100644 --- a/zboxcore/sdk/chunked_upload_blobber.go +++ b/zboxcore/sdk/chunked_upload_blobber.go @@ -154,9 +154,6 @@ func (sb *ChunkedUploadBlobber) sendUploadRequest( // fixed fileRef in last chunk on stream if isFinal { - sb.fileRef.FixedMerkleRoot = formData.FixedMerkleRoot - sb.fileRef.ValidationRoot = formData.ValidationRoot - sb.fileRef.ChunkSize = su.chunkSize sb.fileRef.Size = su.shardUploadedSize sb.fileRef.Path = su.fileMeta.RemotePath diff --git a/zboxcore/sdk/chunked_upload_form_builder.go b/zboxcore/sdk/chunked_upload_form_builder.go index 1de228fa5..3db24225b 100644 --- a/zboxcore/sdk/chunked_upload_form_builder.go +++ b/zboxcore/sdk/chunked_upload_form_builder.go @@ -6,7 +6,6 @@ import ( "encoding/json" "io" "mime/multipart" - "sync" "github.com/0chain/gosdk/zboxcore/client" @@ -29,9 +28,8 @@ type ChunkedUploadFormMetadata struct { FileBytesLen int ThumbnailBytesLen int ContentType string - FixedMerkleRoot string - ValidationRoot string ThumbnailContentHash string + DataHash string } // CreateChunkedUploadFormBuilder create ChunkedUploadFormBuilder instance @@ -116,12 +114,7 @@ func (b *chunkedUploadFormBuilder) Build( return res, err } - err = hasher.WriteToFixedMT(chunkBytes) - if err != nil { - return res, err - } - - err = hasher.WriteToValidationMT(chunkBytes) + err = hasher.WriteToBlockHasher(chunkBytes) if err != nil { return res, err } @@ -130,50 +123,24 @@ func (b *chunkedUploadFormBuilder) Build( } if isFinal && i == numBodies-1 { - err = hasher.Finalize() + + actualHashSignature, err := client.Sign(fileMeta.ActualHash) if err != nil { return res, err } - var ( - wg sync.WaitGroup - errChan = make(chan error, 2) - ) - wg.Add(2) - go func() { - formData.FixedMerkleRoot, err = hasher.GetFixedMerkleRoot() - if err != nil { - errChan <- err - } - wg.Done() - }() - go func() { - formData.ValidationRoot, err = hasher.GetValidationRoot() - if err != nil { - errChan <- err - } - wg.Done() - }() - wg.Wait() - close(errChan) - for err := range errChan { - return res, err - } - actualHashSignature, err := client.Sign(fileMeta.ActualHash) + formData.ActualHash = fileMeta.ActualHash + formData.ActualFileHashSignature = actualHashSignature + formData.ActualSize = fileMeta.ActualSize + dataHash, err := hasher.GetBlockHash() if err != nil { return res, err } - - validationRootSignature, err := client.Sign(actualHashSignature + formData.ValidationRoot) + formData.DataHash = dataHash + formData.DataHashSignature, err = client.Sign(dataHash) if err != nil { return res, err } - - formData.ActualHash = fileMeta.ActualHash - formData.ActualFileHashSignature = actualHashSignature - formData.ValidationRootSignature = validationRootSignature - formData.ActualSize = fileMeta.ActualSize - } thumbnailSize := len(thumbnailChunkData) @@ -225,9 +192,8 @@ func (b *chunkedUploadFormBuilder) Build( contentSlice = append(contentSlice, formWriter.FormDataContentType()) dataBuffers = append(dataBuffers, body) } - metadata.FixedMerkleRoot = formData.FixedMerkleRoot - metadata.ValidationRoot = formData.ValidationRoot metadata.ThumbnailContentHash = formData.ThumbnailContentHash + metadata.DataHash = formData.DataHash res.dataBuffers = dataBuffers res.contentSlice = contentSlice res.formData = metadata diff --git a/zboxcore/sdk/chunked_upload_hasher.go b/zboxcore/sdk/chunked_upload_hasher.go index bd1935d3b..e58da0220 100644 --- a/zboxcore/sdk/chunked_upload_hasher.go +++ b/zboxcore/sdk/chunked_upload_hasher.go @@ -26,6 +26,10 @@ type Hasher interface { WriteToValidationMT(buf []byte) error // Finalize will let merkle tree know that tree is finalized with the content it has received Finalize() error + // WriteToBlockHasher write bytes to block hasher + WriteToBlockHasher(buf []byte) error + // GetBlockHash get block hash + GetBlockHash() (string, error) } // see more detail about hash on https://github.com/0chain/blobber/wiki/Protocols#file-hash @@ -33,14 +37,14 @@ type hasher struct { File hash.Hash `json:"-"` FixedMT *util.FixedMerkleTree `json:"fixed_merkle_tree"` ValidationMT *util.ValidationTree `json:"validation_merkle_tree"` + BlockHasher hash.Hash `json:"-"` } // CreateHasher creat Hasher instance func CreateHasher(dataSize int64) Hasher { return &hasher{ - File: md5.New(), - FixedMT: util.NewFixedMerkleTree(), - ValidationMT: util.NewValidationTree(dataSize), + File: md5.New(), + BlockHasher: md5.New(), } } @@ -123,6 +127,31 @@ func (h *hasher) WriteToValidationMT(buf []byte) error { return err } +func (h *hasher) WriteToBlockHasher(buf []byte) error { + if h == nil { + return errors.Throw(constants.ErrInvalidParameter, "h") + } + + if h.BlockHasher == nil { + return errors.Throw(constants.ErrInvalidParameter, "h.BlockHasher") + } + + _, err := h.BlockHasher.Write(buf) + return err +} + +func (h *hasher) GetBlockHash() (string, error) { + if h == nil { + return "", errors.Throw(constants.ErrInvalidParameter, "h") + } + + if h.BlockHasher == nil { + return "", errors.Throw(constants.ErrInvalidParameter, "h.BlockHasher") + } + + return hex.EncodeToString(h.BlockHasher.Sum(nil)), nil +} + func (h *hasher) Finalize() error { var ( wg sync.WaitGroup diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index 326fb7e73..ec6788353 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -140,15 +140,9 @@ type UploadFormData struct { // Path remote path Path string `json:"filepath,omitempty"` - // ValidationRoot is merkle root of sha256 of 64KB as leaf - ValidationRoot string `json:"validation_root,omitempty"` - ValidationRootSignature string `json:"validation_root_signature,omitempty"` // Hash hash of shard thumbnail (encoded,encrypted) ThumbnailContentHash string `json:"thumbnail_content_hash,omitempty"` - // ChallengeHash challenge hash of shard data (encoded, encrypted) - FixedMerkleRoot string `json:"fixed_merkle_root,omitempty"` - // ActualHash hash of original file (un-encoded, un-encrypted) ActualHash string `json:"actual_hash,omitempty"` ActualFileHashSignature string `json:"actual_file_hash_signature,omitempty"` @@ -164,13 +158,14 @@ type UploadFormData struct { EncryptedKey string `json:"encrypted_key,omitempty"` EncryptedKeyPoint string `json:"encrypted_key_point,omitempty"` - IsFinal bool `json:"is_final,omitempty"` // all of chunks are uploaded - ChunkStartIndex int `json:"chunk_start_index,omitempty"` // start index of chunks. - ChunkEndIndex int `json:"chunk_end_index,omitempty"` // end index of chunks. all chunks MUST be uploaded one by one because of streaming merkle hash - ChunkSize int64 `json:"chunk_size,omitempty"` // the size of a chunk. 64*1024 is default - UploadOffset int64 `json:"upload_offset,omitempty"` // It is next position that new incoming chunk should be append to - Size int64 `json:"size"` // total size of shard - + IsFinal bool `json:"is_final,omitempty"` // all of chunks are uploaded + ChunkStartIndex int `json:"chunk_start_index,omitempty"` // start index of chunks. + ChunkEndIndex int `json:"chunk_end_index,omitempty"` // end index of chunks. all chunks MUST be uploaded one by one because of streaming merkle hash + ChunkSize int64 `json:"chunk_size,omitempty"` // the size of a chunk. 64*1024 is default + UploadOffset int64 `json:"upload_offset,omitempty"` // It is next position that new incoming chunk should be append to + Size int64 `json:"size"` // total size of shard + DataHash string `json:"data_hash,omitempty"` // hash of shard data (encoded,encrypted) + DataHashSignature string `json:"data_hash_signature,omitempty"` } // UploadProgress progress of upload diff --git a/zboxcore/sdk/chunked_upload_process.go b/zboxcore/sdk/chunked_upload_process.go index da58f19de..597217612 100644 --- a/zboxcore/sdk/chunked_upload_process.go +++ b/zboxcore/sdk/chunked_upload_process.go @@ -49,14 +49,7 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, for i, blobberShard := range fileShards { hasher := su.blobbers[i].progress.Hasher for _, chunkBytes := range blobberShard { - err := hasher.WriteToFixedMT(chunkBytes) - if err != nil { - if su.statusCallback != nil { - su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) - } - return err - } - err = hasher.WriteToValidationMT(chunkBytes) + err := hasher.WriteToBlockHasher(chunkBytes) if err != nil { if su.statusCallback != nil { su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index b6a0c8d3b..303a3739c 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -212,8 +212,7 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, } type FinalWorkerResult struct { - FixedMerkleRoot string - ValidationRoot string + DataHash string ThumbnailContentHash string } @@ -335,8 +334,6 @@ func (su *ChunkedUpload) listen(allEventChan []chan worker.MessageEvent, respCha } return } - blobber.fileRef.FixedMerkleRoot = finalResultObj.FixedMerkleRoot - blobber.fileRef.ValidationRoot = finalResultObj.ValidationRoot blobber.fileRef.ThumbnailHash = finalResultObj.ThumbnailContentHash isFinal = true } @@ -408,8 +405,7 @@ func ProcessEventData(data safejs.Value) { if formInfo.OnlyHash { if formInfo.IsFinal { finalResult := &FinalWorkerResult{ - FixedMerkleRoot: uploadData.formData.FixedMerkleRoot, - ValidationRoot: uploadData.formData.ValidationRoot, + DataHash: uploadData.formData.DataHash, ThumbnailContentHash: uploadData.formData.ThumbnailContentHash, } selfPostMessage(true, true, "", remotePath, formInfo.ChunkEndIndex, finalResult) @@ -449,8 +445,7 @@ func ProcessEventData(data safejs.Value) { } if formInfo.IsFinal { finalResult := &FinalWorkerResult{ - FixedMerkleRoot: blobberData.formData.FixedMerkleRoot, - ValidationRoot: blobberData.formData.ValidationRoot, + DataHash: blobberData.formData.DataHash, ThumbnailContentHash: blobberData.formData.ThumbnailContentHash, } selfPostMessage(true, true, "", remotePath, formInfo.ChunkEndIndex, finalResult) diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index 39494064f..c353a1252 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -3,7 +3,6 @@ package sdk import ( "bytes" "context" - "encoding/hex" "encoding/json" "fmt" "io" @@ -25,7 +24,6 @@ import ( l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/minio/sha256-simd" ) type ReferencePathResult struct { @@ -52,15 +50,19 @@ func SuccessCommitResult() *CommitResult { const MARKER_VERSION = "v2" type CommitRequest struct { - changes []allocationchange.AllocationChange - blobber *blockchain.StorageNode - allocationID string - allocationTx string - connectionID string - wg *sync.WaitGroup - result *CommitResult - timestamp int64 - blobberInd uint64 + changes []allocationchange.AllocationChange + blobber *blockchain.StorageNode + allocationID string + allocationTx string + connectionID string + wg *sync.WaitGroup + result *CommitResult + timestamp int64 + blobberInd uint64 + version int64 + isRepair bool + repairVersion int64 + repairOffset string } var commitChan map[string]chan *CommitRequest @@ -100,115 +102,12 @@ func (commitreq *CommitRequest) processCommit() { defer commitreq.wg.Done() start := time.Now() l.Logger.Debug("received a commit request") - paths := make([]string, 0) - for _, change := range commitreq.changes { - paths = append(paths, change.GetAffectedPath()...) - } - if len(paths) == 0 { + if len(commitreq.changes) == 0 { l.Logger.Debug("Nothing to commit") commitreq.result = SuccessCommitResult() return } - var req *http.Request - var lR ReferencePathResult - req, err := zboxutil.NewReferencePathRequest(commitreq.blobber.Baseurl, commitreq.allocationID, commitreq.allocationTx, paths) - if err != nil { - l.Logger.Error("Creating ref path req", err) - return - } - ctx, cncl := context.WithTimeout(context.Background(), (time.Second * 30)) - err = zboxutil.HttpDo(ctx, cncl, req, func(resp *http.Response, err error) error { - if err != nil { - l.Logger.Error("Ref path error:", err) - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - l.Logger.Error("Ref path response : ", resp.StatusCode) - } - resp_body, err := ioutil.ReadAll(resp.Body) - if err != nil { - l.Logger.Error("Ref path: Resp", err) - return err - } - if resp.StatusCode != http.StatusOK { - return errors.New( - strconv.Itoa(resp.StatusCode), - fmt.Sprintf("Reference path error response: Status: %d - %s ", - resp.StatusCode, string(resp_body))) - } - err = json.Unmarshal(resp_body, &lR) - if err != nil { - l.Logger.Error("Reference path json decode error: ", err) - return err - } - return nil - }) - - if err != nil { - commitreq.result = ErrorCommitResult(err.Error()) - return - } - rootRef, err := lR.GetDirTree(commitreq.allocationID) - - if err != nil { - commitreq.result = ErrorCommitResult(err.Error()) - return - } - hasher := sha256.New() - if lR.LatestWM != nil { - err = lR.LatestWM.VerifySignature(client.GetClientPublicKey()) - if err != nil { - e := errors.New("signature_verification_failed", err.Error()) - commitreq.result = ErrorCommitResult(e.Error()) - return - } - if commitreq.timestamp <= lR.LatestWM.Timestamp { - commitreq.timestamp = lR.LatestWM.Timestamp + 1 - } - - rootRef.CalculateHash() - prevAllocationRoot := rootRef.Hash - if prevAllocationRoot != lR.LatestWM.AllocationRoot { - l.Logger.Error("Allocation root from latest writemarker mismatch. Expected: " + prevAllocationRoot + " got: " + lR.LatestWM.AllocationRoot) - errMsg := fmt.Sprintf( - "calculated allocation root mismatch from blobber %s. Expected: %s, Got: %s", - commitreq.blobber.Baseurl, prevAllocationRoot, lR.LatestWM.AllocationRoot) - commitreq.result = ErrorCommitResult(errMsg) - return - } - if lR.LatestWM.ChainHash != "" { - prevChainHash, err := hex.DecodeString(lR.LatestWM.ChainHash) - if err != nil { - commitreq.result = ErrorCommitResult(err.Error()) - return - } - hasher.Write(prevChainHash) //nolint:errcheck - } - } - - var size int64 - fileIDMeta := make(map[string]string) - - for _, change := range commitreq.changes { - err = change.ProcessChange(rootRef, fileIDMeta) - if err != nil { - if !errors.Is(err, allocationchange.ErrRefNotFound) { - commitreq.result = ErrorCommitResult(err.Error()) - return - } - } else { - size += change.GetSize() - } - } - rootRef.CalculateHash() - var chainHash string - if lR.Version == MARKER_VERSION { - decodedHash, _ := hex.DecodeString(rootRef.Hash) - hasher.Write(decodedHash) //nolint:errcheck - chainHash = hex.EncodeToString(hasher.Sum(nil)) - } - err = commitreq.commitBlobber(rootRef, chainHash, lR.LatestWM, size, fileIDMeta) + err := commitreq.commitBlobber() if err != nil { commitreq.result = ErrorCommitResult(err.Error()) return @@ -217,42 +116,20 @@ func (commitreq *CommitRequest) processCommit() { commitreq.result = SuccessCommitResult() } -func (req *CommitRequest) commitBlobber( - rootRef *fileref.Ref, chainHash string, latestWM *marker.WriteMarker, size int64, - fileIDMeta map[string]string) (err error) { - - fileIDMetaData, err := json.Marshal(fileIDMeta) - if err != nil { - l.Logger.Error("Marshalling inode metadata failed: ", err) - return err - } - - wm := &marker.WriteMarker{} - wm.AllocationRoot = rootRef.Hash - wm.ChainSize = size - if latestWM != nil { - wm.PreviousAllocationRoot = latestWM.AllocationRoot - wm.ChainSize += latestWM.ChainSize - } else { - wm.PreviousAllocationRoot = "" - } - if wm.AllocationRoot == wm.PreviousAllocationRoot { - l.Logger.Debug("Allocation root and previous allocation root are same") - return nil +func (req *CommitRequest) commitBlobber() (err error) { + vm := &marker.VersionMarker{ + Version: req.version, + Timestamp: req.timestamp, + ClientID: client.GetClientID(), + AllocationID: req.allocationID, + BlobberID: req.blobber.ID, } - wm.ChainHash = chainHash - wm.FileMetaRoot = rootRef.FileMetaHash - wm.AllocationID = req.allocationID - wm.Size = size - wm.BlobberID = req.blobber.ID - wm.Timestamp = req.timestamp - wm.ClientID = client.GetClientID() - err = wm.Sign() + err = vm.Sign() if err != nil { l.Logger.Error("Signing writemarker failed: ", err) return err } - wmData, err := json.Marshal(wm) + vmData, err := json.Marshal(vm) if err != nil { l.Logger.Error("Creating writemarker failed: ", err) return err @@ -266,7 +143,7 @@ func (req *CommitRequest) commitBlobber( for retries := 0; retries < 6; retries++ { err, shouldContinue = func() (err error, shouldContinue bool) { body := new(bytes.Buffer) - formWriter, err := getFormWritter(req.connectionID, wmData, fileIDMetaData, body) + formWriter, err := getFormWritter(req.connectionID, vmData, body) if err != nil { l.Logger.Error("Creating form writer failed: ", err) return @@ -379,19 +256,14 @@ func (commitreq *CommitRequest) calculateHashRequest(ctx context.Context, paths return err } -func getFormWritter(connectionID string, wmData, fileIDMetaData []byte, body *bytes.Buffer) (*multipart.Writer, error) { +func getFormWritter(connectionID string, vmData []byte, body *bytes.Buffer) (*multipart.Writer, error) { formWriter := multipart.NewWriter(body) err := formWriter.WriteField("connection_id", connectionID) if err != nil { return nil, err } - err = formWriter.WriteField("write_marker", string(wmData)) - if err != nil { - return nil, err - } - - err = formWriter.WriteField("file_id_meta", string(fileIDMetaData)) + err = formWriter.WriteField("version_marker", string(vmData)) if err != nil { return nil, err } diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 0ab370207..2a5f5a316 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -292,6 +292,7 @@ func (mo *MultiOperation) Process() error { wg: wg, timestamp: timestamp, blobberInd: pos, + version: mo.allocationObj.Blobbers[pos].AllocationVersion + 1, } commitReq.changes = append(commitReq.changes, mo.changes[pos]...) @@ -335,6 +336,13 @@ func (mo *MultiOperation) Process() error { for _, op := range mo.operations { op.Completed(mo.allocationObj) } + if singleClientMode && !mo.isRepair { + for _, commitReq := range commitReqs { + if commitReq.result.Success { + mo.allocationObj.Blobbers[commitReq.blobberInd].AllocationVersion++ + } + } + } } return nil diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index e0e10dc2c..32788cae0 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -3,7 +3,6 @@ package sdk import ( "bytes" "context" - "encoding/hex" "encoding/json" "fmt" "io" @@ -24,7 +23,6 @@ import ( l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/minio/sha256-simd" "go.uber.org/zap" ) @@ -34,6 +32,10 @@ type LatestPrevWriteMarker struct { Version string `json:"version"` } +type LatestVersionMarker struct { + VersionMarker *marker.VersionMarker `json:"version_marker"` +} + type AllocStatus byte const ( @@ -51,7 +53,7 @@ var ( type RollbackBlobber struct { blobber *blockchain.StorageNode commitResult *CommitResult - lpm *LatestPrevWriteMarker + lvm *LatestVersionMarker blobIndex int } @@ -60,9 +62,9 @@ type BlobberStatus struct { Status string } -func GetWritemarker(allocID, allocTx, id, baseUrl string) (*LatestPrevWriteMarker, error) { +func GetWritemarker(allocID, allocTx, id, baseUrl string) (*LatestVersionMarker, error) { - var lpm LatestPrevWriteMarker + var lvm LatestVersionMarker req, err := zboxutil.NewWritemarkerRequest(baseUrl, allocID, allocTx) if err != nil { @@ -96,75 +98,49 @@ func GetWritemarker(allocID, allocTx, id, baseUrl string) (*LatestPrevWriteMarke if err != nil { return nil, err } - err = json.Unmarshal(body, &lpm) + err = json.Unmarshal(body, &lvm) if err != nil { return nil, err } - if lpm.LatestWM != nil { - err = lpm.LatestWM.VerifySignature(client.GetClientPublicKey()) + if lvm.VersionMarker != nil && lvm.VersionMarker.Version != 0 { + err = lvm.VersionMarker.VerifySignature(client.GetClientPublicKey()) if err != nil { return nil, fmt.Errorf("signature verification failed for latest writemarker: %s", err.Error()) } - if lpm.PrevWM != nil { - err = lpm.PrevWM.VerifySignature(client.GetClientPublicKey()) - if err != nil { - return nil, fmt.Errorf("signature verification failed for latest writemarker: %s", err.Error()) - } - } } - return &lpm, nil + return &lvm, nil } return nil, fmt.Errorf("writemarker error response %d", http.StatusTooManyRequests) } func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error { - - wm := &marker.WriteMarker{} - wm.AllocationID = rb.lpm.LatestWM.AllocationID - wm.Timestamp = rb.lpm.LatestWM.Timestamp - wm.BlobberID = rb.lpm.LatestWM.BlobberID - wm.ClientID = client.GetClientID() - wm.Size = -rb.lpm.LatestWM.Size - wm.ChainSize = wm.Size + rb.lpm.LatestWM.ChainSize - - if rb.lpm.PrevWM != nil { - wm.AllocationRoot = rb.lpm.PrevWM.AllocationRoot - wm.PreviousAllocationRoot = rb.lpm.PrevWM.AllocationRoot - wm.FileMetaRoot = rb.lpm.PrevWM.FileMetaRoot - if wm.AllocationRoot == rb.lpm.LatestWM.AllocationRoot { - return nil - } - } - if rb.lpm.Version == MARKER_VERSION { - decodedHash, _ := hex.DecodeString(wm.AllocationRoot) - prevChainHash, _ := hex.DecodeString(rb.lpm.LatestWM.ChainHash) - hasher := sha256.New() - hasher.Write(prevChainHash) //nolint:errcheck - hasher.Write(decodedHash) //nolint:errcheck - wm.ChainHash = hex.EncodeToString(hasher.Sum(nil)) - } else if rb.lpm.Version == "" { - wm.Size = 0 + vm := &marker.VersionMarker{ + ClientID: client.GetClientID(), + BlobberID: rb.lvm.VersionMarker.BlobberID, + AllocationID: rb.lvm.VersionMarker.AllocationID, + Version: rb.lvm.VersionMarker.Version - 1, + Timestamp: rb.lvm.VersionMarker.Timestamp, } - err := wm.Sign() + err := vm.Sign() if err != nil { l.Logger.Error("Signing writemarker failed: ", err) return err } body := new(bytes.Buffer) formWriter := multipart.NewWriter(body) - wmData, err := json.Marshal(wm) + vmData, err := json.Marshal(vm) if err != nil { l.Logger.Error("Creating writemarker failed: ", err) return err } connID := zboxutil.NewConnectionId() - formWriter.WriteField("write_marker", string(wmData)) + formWriter.WriteField("version_marker", string(vmData)) formWriter.WriteField("connection_id", connID) formWriter.Close() - req, err := zboxutil.NewRollbackRequest(rb.blobber.Baseurl, wm.AllocationID, tx, body) + req, err := zboxutil.NewRollbackRequest(rb.blobber.Baseurl, vm.AllocationID, tx, body) if err != nil { l.Logger.Error("Creating rollback request failed: ", err) return err @@ -268,22 +244,23 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { ID: blobber.ID, Status: "available", } - wr, err := GetWritemarker(a.ID, a.Tx, blobber.ID, blobber.Baseurl) + lvm, err := GetWritemarker(a.ID, a.Tx, blobber.ID, blobber.Baseurl) if err != nil { atomic.AddInt32(&errCnt, 1) markerError = err l.Logger.Error("error during getWritemarker", zap.Error(err)) blobStatus.Status = "unavailable" } - if wr == nil { + if lvm == nil { markerChan <- nil } else { markerChan <- &RollbackBlobber{ blobber: blobber, - lpm: wr, + lvm: lvm, commitResult: &CommitResult{}, blobIndex: ind, } + blobber.AllocationVersion = lvm.VersionMarker.Version } blobberRes[ind] = blobStatus }(blobber, ind) @@ -295,30 +272,24 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { return Broken, blobberRes, common.NewError("check_alloc_status_failed", markerError.Error()) } - versionMap := make(map[string][]*RollbackBlobber) + versionMap := make(map[int64][]*RollbackBlobber) var ( - prevVersion string - latestVersion string - highestTS int64 + consensusReached bool + latestVersion int64 + prevVersion int64 ) for rb := range markerChan { - if rb == nil || rb.lpm.LatestWM == nil { + if rb == nil || rb.lvm == nil { continue } - version := rb.lpm.LatestWM.FileMetaRoot - - if highestTS < rb.lpm.LatestWM.Timestamp { - prevVersion = latestVersion - highestTS = rb.lpm.LatestWM.Timestamp + version := rb.lvm.VersionMarker.Version + if version > latestVersion { latestVersion = version - } - - if prevVersion == "" && version != latestVersion { - prevVersion = version + prevVersion = latestVersion } if _, ok := versionMap[version]; !ok { @@ -326,6 +297,9 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { } versionMap[version] = append(versionMap[version], rb) + if len(versionMap[version]) >= a.DataShards && version == latestVersion { + consensusReached = true + } } req := a.DataShards @@ -334,17 +308,15 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { return Commit, blobberRes, nil } - if len(versionMap[latestVersion]) > req || len(versionMap[prevVersion]) > req { + if consensusReached { return Commit, blobberRes, nil } - if len(versionMap[latestVersion]) >= req || len(versionMap[prevVersion]) >= req || len(versionMap) > 2 { - for _, rb := range versionMap[prevVersion] { - blobberRes[rb.blobIndex].Status = "repair" - } + if len(versionMap[latestVersion]) >= req { + // for _, rb := range versionMap[prevVersion] { + // blobberRes[rb.blobIndex].Status = "repair" + // } return Repair, blobberRes, nil - } else { - l.Logger.Info("versionMapLen", zap.Int("versionMapLen", len(versionMap)), zap.Int("latestLen", len(versionMap[latestVersion])), zap.Int("prevLen", len(versionMap[prevVersion]))) } // rollback to previous version @@ -401,7 +373,7 @@ func (a *Allocation) RollbackWithMask(mask zboxutil.Uint128) { } else { markerChan <- &RollbackBlobber{ blobber: blobber, - lpm: wr, + lvm: wr, commitResult: &CommitResult{}, } } @@ -412,7 +384,7 @@ func (a *Allocation) RollbackWithMask(mask zboxutil.Uint128) { close(markerChan) for rb := range markerChan { - if rb == nil || rb.lpm.LatestWM == nil { + if rb == nil || rb.lvm == nil { continue } wg.Add(1) From 02e203d91330793495685777093910c4b495636d Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Mon, 22 Jul 2024 03:25:19 +0530 Subject: [PATCH 002/107] add repair info in commit worker --- zboxcore/sdk/commitworker.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index c353a1252..61830cbf3 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -118,11 +118,14 @@ func (commitreq *CommitRequest) processCommit() { func (req *CommitRequest) commitBlobber() (err error) { vm := &marker.VersionMarker{ - Version: req.version, - Timestamp: req.timestamp, - ClientID: client.GetClientID(), - AllocationID: req.allocationID, - BlobberID: req.blobber.ID, + Version: req.version, + Timestamp: req.timestamp, + ClientID: client.GetClientID(), + AllocationID: req.allocationID, + BlobberID: req.blobber.ID, + IsRepair: req.isRepair, + RepairVersion: req.repairVersion, + RepairOffset: req.repairOffset, } err = vm.Sign() if err != nil { From c981f068ef753702ebf4475de4d742eba3648565 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Tue, 23 Jul 2024 23:26:34 +0530 Subject: [PATCH 003/107] add check for repair marker --- zboxcore/sdk/rollback.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 32788cae0..02018e29f 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -115,6 +115,10 @@ func GetWritemarker(allocID, allocTx, id, baseUrl string) (*LatestVersionMarker, } func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error { + // don't rollback if the blobber is already in repair mode otherwise it will lead to inconsistent state + if rb.lvm == nil || rb.lvm.VersionMarker.IsRepair { + return nil + } vm := &marker.VersionMarker{ ClientID: client.GetClientID(), BlobberID: rb.lvm.VersionMarker.BlobberID, From b5cbb792ef034f3c71200460d3b646da41670b90 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 25 Jul 2024 02:10:45 +0530 Subject: [PATCH 004/107] add allocation version and check for directory --- zboxcore/fileref/fileref.go | 1 + zboxcore/sdk/allocation.go | 2 ++ zboxcore/sdk/deleteworker.go | 3 +++ zboxcore/sdk/multi_operation_worker.go | 13 ++++++++++++- zboxcore/sdk/rollback.go | 7 ++++--- 5 files changed, 22 insertions(+), 4 deletions(-) diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index bb46a0e11..4cc2f1147 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -90,6 +90,7 @@ type Ref struct { ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` ActualThumbnailHash string `json:"actual_thumbnail_hash" mapstructure:"actual_thumbnail_hash"` ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` + IsEmpty bool `json:"is_empty" mapstructure:"is_empty"` HashToBeComputed bool ChildrenLoaded bool Children []RefEntity `json:"-" mapstructure:"-"` diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 2a44fe467..00e68aed1 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -201,6 +201,7 @@ type Allocation struct { MovedToValidators common.Balance `json:"moved_to_validators,omitempty"` FileOptions uint16 `json:"file_options"` ThirdPartyExtendable bool `json:"third_party_extendable"` + AllocationVersion int64 `json:"-"` numBlockDownloads int downloadChan chan *DownloadRequest @@ -338,6 +339,7 @@ func (a *Allocation) InitAllocation() { a.startWorker(a.ctx) InitCommitWorker(a.Blobbers) InitBlockDownloader(a.Blobbers, downloadWorkerCount) + a.CheckAllocStatus() //nolint:errcheck a.initialized = true } diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 3ac0b6eb1..e173ea759 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -369,6 +369,9 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( l.Logger.Error(err.Error()) return } + if refEntity.Type == fileref.DIRECTORY && !refEntity.IsEmpty { + //TODO: Handle directory delete + } err = deleteReq.deleteBlobberFile(deleteReq.blobbers[blobberIdx], blobberIdx) if err != nil { blobberErrors[blobberIdx] = err diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 2a5f5a316..cb2807d1f 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -275,11 +275,21 @@ func (mo *MultiOperation) Process() error { } logger.Logger.Debug("[checkAllocStatus]", time.Since(start).Milliseconds()) mo.Consensus.Reset() + var pos uint64 + for i := mo.operationMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + if mo.allocationObj.Blobbers[pos].AllocationVersion != mo.allocationObj.AllocationVersion { + mo.operationMask = mo.operationMask.And(zboxutil.NewUint128(1).Lsh(pos).Not()) + } + } activeBlobbers := mo.operationMask.CountOnes() + if activeBlobbers < mo.consensusThresh { + return errors.New("consensus_not_met", "Active blobbers less than consensus threshold") + } commitReqs := make([]*CommitRequest, activeBlobbers) start = time.Now() wg.Add(activeBlobbers) - var pos uint64 + var counter = 0 timestamp := int64(common.Now()) for i := mo.operationMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { @@ -342,6 +352,7 @@ func (mo *MultiOperation) Process() error { mo.allocationObj.Blobbers[commitReq.blobberInd].AllocationVersion++ } } + mo.allocationObj.AllocationVersion += 1 } } diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 02018e29f..a288c5de2 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -313,13 +313,14 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { } if consensusReached { + a.AllocationVersion = latestVersion return Commit, blobberRes, nil } if len(versionMap[latestVersion]) >= req { - // for _, rb := range versionMap[prevVersion] { - // blobberRes[rb.blobIndex].Status = "repair" - // } + for _, rb := range versionMap[prevVersion] { + blobberRes[rb.blobIndex].Status = "repair" + } return Repair, blobberRes, nil } From 526a11784672a66f914b278f01e840f0bca10a1d Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 25 Jul 2024 18:53:19 +0530 Subject: [PATCH 005/107] prefix delete --- wasmsdk/common.go | 8 ++ zboxcore/fileref/fileref.go | 7 ++ zboxcore/sdk/allocation.go | 12 ++- zboxcore/sdk/deleteworker.go | 132 ++++++++++++++++++++++++++++++++- zboxcore/sdk/filerefsworker.go | 61 ++++++++++++++- 5 files changed, 212 insertions(+), 8 deletions(-) diff --git a/wasmsdk/common.go b/wasmsdk/common.go index ba2bfe408..7c9f4f8ac 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -89,3 +89,11 @@ func (h *hasher) WriteToValidationMT(_ []byte) error { func (h *hasher) Finalize() error { return nil } + +func (h *hasher) GetBlockHash() (string, error) { + return "", nil +} + +func (h *hasher) WriteToBlockHasher(buf []byte) error { + return nil +} diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index 4cc2f1147..c79f343ce 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -17,6 +17,7 @@ const CHUNK_SIZE = 64 * 1024 const ( FILE = "f" DIRECTORY = "d" + REGULAR = "regular" ) var fileCache, _ = lru.New[string, FileRef](100) @@ -70,6 +71,7 @@ type RefEntity interface { GetFileID() string GetCreatedAt() common.Timestamp GetUpdatedAt() common.Timestamp + GetAllocationVersion() int64 } type Ref struct { @@ -91,6 +93,7 @@ type Ref struct { ActualThumbnailHash string `json:"actual_thumbnail_hash" mapstructure:"actual_thumbnail_hash"` ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` IsEmpty bool `json:"is_empty" mapstructure:"is_empty"` + AllocationVersion int64 `json:"allocation_version" mapstructure:"allocation_version"` HashToBeComputed bool ChildrenLoaded bool Children []RefEntity `json:"-" mapstructure:"-"` @@ -233,6 +236,10 @@ func (r *Ref) RemoveChild(idx int) { r.Children = append(r.Children[:idx], r.Children[idx+1:]...) } +func (r *Ref) GetAllocationVersion() int64 { + return r.AllocationVersion +} + func (fr *FileRef) GetFileMetaHash() string { return fr.FileMetaHash } diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 00e68aed1..6154cb69d 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -64,6 +64,7 @@ const ( const ( emptyFileDataHash = "d41d8cd98f00b204e9800998ecf8427e" + getRefPageLimit = 1000 ) // Expected success rate is calculated (NumDataShards)*100/(NumDataShards+NumParityShards) @@ -1401,7 +1402,7 @@ func (a *Allocation) ListDir(path string, opts ...ListRequestOptions) (*ListResu return nil, errors.New("list_request_failed", "Failed to get list response from the blobbers") } -func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int) (*ObjectTreeResult, error) { +func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int, opts ...ObjectTreeRequestOption) (*ObjectTreeResult, error) { if !a.isInitialized() { return nil, notInitialized } @@ -1421,9 +1422,16 @@ func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, fileType: fileType, refType: refType, ctx: a.ctx, + reqMask: zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1), } oTreeReq.fullconsensus = a.fullconsensus oTreeReq.consensusThresh = a.DataShards + for _, opt := range opts { + opt(oTreeReq) + } + if singleClientMode { + oTreeReq.singleBlobber = true + } return oTreeReq.GetRefs() } @@ -1516,7 +1524,7 @@ func (a *Allocation) GetRefsWithAuthTicket(authToken, offsetPath, updatedDate, o } // This function will retrieve paginated objectTree and will handle concensus; Required tree should be made in application side. -func (a *Allocation) GetRefs(path, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int) (*ObjectTreeResult, error) { +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)) } diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index e173ea759..83be0414e 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "net/http" "net/url" + "strings" "sync" "sync/atomic" "time" @@ -352,8 +353,11 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( numList := len(deleteReq.blobbers) objectTreeRefs := make([]fileref.RefEntity, numList) blobberErrors := make([]error, numList) - - var pos uint64 + versionMap := make(map[int64]int) + var ( + pos uint64 + consensusRef *fileref.FileRef + ) for i := deleteReq.deleteMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) @@ -372,7 +376,57 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( if refEntity.Type == fileref.DIRECTORY && !refEntity.IsEmpty { //TODO: Handle directory delete } - err = deleteReq.deleteBlobberFile(deleteReq.blobbers[blobberIdx], blobberIdx) + // err = deleteReq.deleteBlobberFile(deleteReq.blobbers[blobberIdx], blobberIdx) + // if err != nil { + // blobberErrors[blobberIdx] = err + // } + // if singleClientMode { + // lookuphash := fileref.GetReferenceLookup(deleteReq.allocationID, deleteReq.remotefilepath) + // cacheKey := fileref.GetCacheKey(lookuphash, deleteReq.blobbers[blobberIdx].ID) + // fileref.DeleteFileRef(cacheKey) + // } + objectTreeRefs[blobberIdx] = refEntity + deleteReq.maskMu.Lock() + versionMap[refEntity.AllocationVersion]++ + if versionMap[refEntity.AllocationVersion] > deleteReq.consensus.consensusThresh { + consensusRef = refEntity + } + deleteReq.maskMu.Unlock() + }(int(pos)) + } + deleteReq.wg.Wait() + + if !deleteReq.consensus.isConsensusOk() { + err := zboxutil.MajorError(blobberErrors) + if err != nil { + return nil, deleteReq.deleteMask, thrown.New("delete_failed", fmt.Sprintf("Delete failed. %s", err.Error())) + } + + return nil, deleteReq.deleteMask, thrown.New("consensus_not_met", + fmt.Sprintf("Delete failed. Required consensus %d, got %d", + deleteReq.consensus.consensusThresh, deleteReq.consensus.consensus)) + } + if consensusRef == nil { + return nil, deleteReq.deleteMask, thrown.New("delete_failed", "Delete failed. No consensus found") + } + if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { + for ind, refEntity := range objectTreeRefs { + if refEntity.GetAllocationVersion() != consensusRef.AllocationVersion { + deleteReq.deleteMask = deleteReq.deleteMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) + } + } + err := deleteReq.deleteSubDirectories() + if err != nil { + return nil, deleteReq.deleteMask, err + } + } + pos = 0 + for i := deleteReq.deleteMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + deleteReq.wg.Add(1) + go func(blobberIdx int) { + defer deleteReq.wg.Done() + err := deleteReq.deleteBlobberFile(deleteReq.blobbers[blobberIdx], blobberIdx) if err != nil { blobberErrors[blobberIdx] = err } @@ -381,7 +435,6 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( cacheKey := fileref.GetCacheKey(lookuphash, deleteReq.blobbers[blobberIdx].ID) fileref.DeleteFileRef(cacheKey) } - objectTreeRefs[blobberIdx] = refEntity }(int(pos)) } deleteReq.wg.Wait() @@ -396,6 +449,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( fmt.Sprintf("Delete failed. Required consensus %d, got %d", deleteReq.consensus.consensusThresh, deleteReq.consensus.consensus)) } + l.Logger.Debug("Delete Process Ended ") return objectTreeRefs, deleteReq.deleteMask, nil } @@ -453,3 +507,73 @@ func NewDeleteOperation(remotePath string, deleteMask zboxutil.Uint128, maskMu * dop.ctx, dop.ctxCncl = context.WithCancel(ctx) return dop } + +func (req *DeleteRequest) deleteSubDirectories() error { + // list all files + var ( + offsetPath string + pathLevel int + ) + for { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WitObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + break + } + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.deleteMask + op := OperationRequest{ + OperationType: constants.FileOperationDelete, + RemotePath: ref.Path, + Mask: &opMask, + } + ops = append(ops, op) + } + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err + } + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + pathLevel = oResult.Refs[len(oResult.Refs)-1].PathLevel + if len(oResult.Refs) < getRefPageLimit { + break + } + } + // reset offsetPath + offsetPath = "" + level := len(strings.Split(strings.TrimSuffix(req.remotefilepath, "/"), "/")) + // list all directories by descending order of path level + for pathLevel > level { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.DIRECTORY, fileref.REGULAR, pathLevel, getRefPageLimit, WithObjectContext(req.ctx), WitObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + pathLevel-- + } else { + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.deleteMask + op := OperationRequest{ + OperationType: constants.FileOperationDelete, + RemotePath: ref.Path, + Mask: &opMask, + } + ops = append(ops, op) + } + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err + } + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + if len(oResult.Refs) < getRefPageLimit { + pathLevel-- + } + } + } + + return nil +} diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 93af36190..dccea9af2 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -7,6 +7,7 @@ import ( "fmt" "io/ioutil" "math" + "math/rand" "net/http" "sync" "time" @@ -43,7 +44,9 @@ type ObjectTreeRequest struct { offsetPath string updatedDate string // must have "2006-01-02T15:04:05.99999Z07:00" format offsetDate string // must have "2006-01-02T15:04:05.99999Z07:00" format + reqMask zboxutil.Uint128 ctx context.Context + singleBlobber bool Consensus } @@ -54,18 +57,72 @@ type oTreeResponse struct { idx int } +type ObjectTreeRequestOption func(*ObjectTreeRequest) + +func WithObjectContext(ctx context.Context) ObjectTreeRequestOption { + return func(o *ObjectTreeRequest) { + o.ctx = ctx + } +} + +func WitObjectMask(mask zboxutil.Uint128) ObjectTreeRequestOption { + return func(o *ObjectTreeRequest) { + o.reqMask = mask + } +} + +func WithObjectConsensusThresh(thresh int) ObjectTreeRequestOption { + return func(o *ObjectTreeRequest) { + o.consensusThresh = thresh + } +} + +func WithSingleBlobber(singleBlobber bool) ObjectTreeRequestOption { + return func(o *ObjectTreeRequest) { + o.singleBlobber = singleBlobber + } +} + // Paginated tree should not be collected as this will stall the client // It should rather be handled by application that uses gosdk func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { totalBlobbersCount := len(o.blobbers) oTreeResponses := make([]oTreeResponse, totalBlobbersCount) respChan := make(chan *oTreeResponse, totalBlobbersCount) - for i, blob := range o.blobbers { + activeCount := o.reqMask.CountOnes() + if o.singleBlobber { + var respErr error + for i := 0; i < activeCount; i++ { + var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) + num := rnd.Intn(activeCount) + blob := o.blobbers[num] + l.Logger.Debug(fmt.Sprintf("Getting file refs for path %v from blobber %v", o.remotefilepath, blob.Baseurl)) + idx := num + baseURL := blob.Baseurl + go o.getFileRefs(baseURL, respChan, idx) + select { + case <-o.ctx.Done(): + return nil, o.ctx.Err() + case oTreeResponse := <-respChan: + if oTreeResponse.err != nil { + respErr = oTreeResponse.err + } else { + return oTreeResponse.oTResult, nil + } + } + } + return nil, respErr + } + var pos uint64 + for i := o.reqMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + blob := o.blobbers[pos] l.Logger.Debug(fmt.Sprintf("Getting file refs for path %v from blobber %v", o.remotefilepath, blob.Baseurl)) - idx := i + idx := int(pos) baseURL := blob.Baseurl go o.getFileRefs(baseURL, respChan, idx) } + hashCount := make(map[string]int) hashRefsMap := make(map[string]*ObjectTreeResult) oTreeResponseErrors := make([]error, totalBlobbersCount) From 6486442dcc77436f3917ae36d88b024aa6ae883c Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 25 Jul 2024 23:40:28 +0530 Subject: [PATCH 006/107] fix consensus in delete --- zboxcore/sdk/deleteworker.go | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 83be0414e..dfb116a53 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -373,18 +373,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( l.Logger.Error(err.Error()) return } - if refEntity.Type == fileref.DIRECTORY && !refEntity.IsEmpty { - //TODO: Handle directory delete - } - // err = deleteReq.deleteBlobberFile(deleteReq.blobbers[blobberIdx], blobberIdx) - // if err != nil { - // blobberErrors[blobberIdx] = err - // } - // if singleClientMode { - // lookuphash := fileref.GetReferenceLookup(deleteReq.allocationID, deleteReq.remotefilepath) - // cacheKey := fileref.GetCacheKey(lookuphash, deleteReq.blobbers[blobberIdx].ID) - // fileref.DeleteFileRef(cacheKey) - // } + deleteReq.consensus.Done() objectTreeRefs[blobberIdx] = refEntity deleteReq.maskMu.Lock() versionMap[refEntity.AllocationVersion]++ From f9f82373ef8084338b08eb4b0f11925dfe29c4c1 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Fri, 26 Jul 2024 14:48:49 +0530 Subject: [PATCH 007/107] fix consensus thresh check --- zboxcore/sdk/deleteworker.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index dfb116a53..927abcd07 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -376,8 +376,8 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( deleteReq.consensus.Done() objectTreeRefs[blobberIdx] = refEntity deleteReq.maskMu.Lock() - versionMap[refEntity.AllocationVersion]++ - if versionMap[refEntity.AllocationVersion] > deleteReq.consensus.consensusThresh { + versionMap[refEntity.AllocationVersion] += 1 + if versionMap[refEntity.AllocationVersion] >= deleteReq.consensus.consensusThresh { consensusRef = refEntity } deleteReq.maskMu.Unlock() From e015027ef52aca37ba042399a963cf1819b323e1 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Fri, 26 Jul 2024 19:43:56 +0530 Subject: [PATCH 008/107] fix path level in delete --- zboxcore/sdk/chunked_upload.go | 3 +-- zboxcore/sdk/deleteworker.go | 11 +++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index f30f318ef..00f514340 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -181,9 +181,9 @@ func CreateChunkedUpload( // su.ctx, su.ctxCncl = context.WithCancel(allocationObj.ctx) su.ctx, su.ctxCncl = context.WithCancelCause(ctx) + su.httpMethod = http.MethodPost if isUpdate { - su.httpMethod = http.MethodPut su.buildChange = func(ref *fileref.FileRef, _ uuid.UUID, ts common.Timestamp) allocationchange.AllocationChange { change := &allocationchange.UpdateFileChange{} change.NewFile = ref @@ -193,7 +193,6 @@ func CreateChunkedUpload( return change } } else { - su.httpMethod = http.MethodPost su.buildChange = func(ref *fileref.FileRef, uid uuid.UUID, ts common.Timestamp) allocationchange.AllocationChange { change := &allocationchange.NewFileChange{} change.File = ref diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 927abcd07..1db2e9a2c 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -384,7 +384,6 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( }(int(pos)) } deleteReq.wg.Wait() - if !deleteReq.consensus.isConsensusOk() { err := zboxutil.MajorError(blobberErrors) if err != nil { @@ -514,6 +513,12 @@ func (req *DeleteRequest) deleteSubDirectories() error { ops := make([]OperationRequest, 0, len(oResult.Refs)) for _, ref := range oResult.Refs { opMask := req.deleteMask + if ref.Type == fileref.DIRECTORY { + continue + } + if ref.PathLevel > pathLevel { + pathLevel = ref.PathLevel + } op := OperationRequest{ OperationType: constants.FileOperationDelete, RemotePath: ref.Path, @@ -526,7 +531,6 @@ func (req *DeleteRequest) deleteSubDirectories() error { return err } offsetPath = oResult.Refs[len(oResult.Refs)-1].Path - pathLevel = oResult.Refs[len(oResult.Refs)-1].PathLevel if len(oResult.Refs) < getRefPageLimit { break } @@ -534,6 +538,9 @@ func (req *DeleteRequest) deleteSubDirectories() error { // reset offsetPath offsetPath = "" level := len(strings.Split(strings.TrimSuffix(req.remotefilepath, "/"), "/")) + if pathLevel == 0 { + pathLevel = level + 1 + } // list all directories by descending order of path level for pathLevel > level { oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.DIRECTORY, fileref.REGULAR, pathLevel, getRefPageLimit, WithObjectContext(req.ctx), WitObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) From a8bf8bb9edeaac95691d7209d2a21c7f0481567a Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Fri, 26 Jul 2024 22:58:49 +0530 Subject: [PATCH 009/107] remove vt from downloadworker --- zboxcore/sdk/blockdownloadworker.go | 13 ------------- zboxcore/sdk/downloadworker.go | 11 ----------- 2 files changed, 24 deletions(-) diff --git a/zboxcore/sdk/blockdownloadworker.go b/zboxcore/sdk/blockdownloadworker.go index 603003903..7dc4d5375 100644 --- a/zboxcore/sdk/blockdownloadworker.go +++ b/zboxcore/sdk/blockdownloadworker.go @@ -11,7 +11,6 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/client" "github.com/0chain/gosdk/zboxcore/fileref" @@ -29,7 +28,6 @@ const ( type BlockDownloadRequest struct { blobber *blockchain.StorageNode - blobberFile *blobberFile allocationID string allocationTx string allocOwnerID string @@ -199,18 +197,7 @@ func (req *BlockDownloadRequest) downloadBlobberBlock(fastClient *fasthttp.Clien dR.Data = respBuf } if req.contentMode == DOWNLOAD_CONTENT_FULL && req.shouldVerify { - - vmp := util.MerklePathForMultiLeafVerification{ - Nodes: dR.Nodes, - Index: dR.Indexes, - RootHash: req.blobberFile.validationRoot, - DataSize: req.blobberFile.size, - } zlogger.Logger.Info("verifying multiple blocks") - err = vmp.VerifyMultipleBlocks(dR.Data) - if err != nil { - return errors.New("merkle_path_verification_error", err.Error()) - } } rspData.idx = req.blobberIdx diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 3bcd518ed..e9c56c131 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -80,7 +80,6 @@ type DownloadRequest struct { endBlock int64 chunkSize int numBlocks int64 - validationRootMap map[string]*blobberFile statusCallback StatusCallback ctx context.Context ctxCncl context.CancelFunc @@ -255,7 +254,6 @@ func (req *DownloadRequest) downloadBlock( remotefilepathhash: req.remotefilepathhash, numBlocks: totalBlock, encryptedKey: req.encryptedKey, - shouldVerify: req.shouldVerify, connectionID: req.connectionID, } @@ -268,8 +266,6 @@ func (req *DownloadRequest) downloadBlock( } if !skipDownload { - bf := req.validationRootMap[blockDownloadReq.blobber.ID] - blockDownloadReq.blobberFile = bf if req.shouldVerify { go AddBlockDownloadReq(req.ctx, blockDownloadReq, nil, req.effectiveBlockSize) } else { @@ -1181,7 +1177,6 @@ func (req *DownloadRequest) getFileMetaConsensus(fMetaResp []*fileMetaResponse) return nil, errors.New("consensus_not_met", "") } - req.validationRootMap = make(map[string]*blobberFile) blobberCount := 0 countThreshold := req.consensusThresh + 1 if countThreshold > req.fullconsensus { @@ -1215,12 +1210,6 @@ func (req *DownloadRequest) getFileMetaConsensus(fMetaResp []*fileMetaResponse) continue } - blobber := req.blobbers[fmr.blobberIdx] - vr, _ := hex.DecodeString(fmr.fileref.ValidationRoot) - req.validationRootMap[blobber.ID] = &blobberFile{ - size: fmr.fileref.Size, - validationRoot: vr, - } shift := zboxutil.NewUint128(1).Lsh(uint64(fmr.blobberIdx)) foundMask = foundMask.Or(shift) req.downloadQueue[fmr.blobberIdx] = downloadPriority{ From b91b592f21d0f9aa3f0d2cc50827f2feb71d4198 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 27 Jul 2024 13:37:24 +0530 Subject: [PATCH 010/107] rm vt in reader --- zboxcore/sdk/downloadworker.go | 10 ---------- zboxcore/sdk/reader.go | 19 +++++++++---------- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 3bcd518ed..f4ba045b9 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -80,7 +80,6 @@ type DownloadRequest struct { endBlock int64 chunkSize int numBlocks int64 - validationRootMap map[string]*blobberFile statusCallback StatusCallback ctx context.Context ctxCncl context.CancelFunc @@ -268,8 +267,6 @@ func (req *DownloadRequest) downloadBlock( } if !skipDownload { - bf := req.validationRootMap[blockDownloadReq.blobber.ID] - blockDownloadReq.blobberFile = bf if req.shouldVerify { go AddBlockDownloadReq(req.ctx, blockDownloadReq, nil, req.effectiveBlockSize) } else { @@ -1181,7 +1178,6 @@ func (req *DownloadRequest) getFileMetaConsensus(fMetaResp []*fileMetaResponse) return nil, errors.New("consensus_not_met", "") } - req.validationRootMap = make(map[string]*blobberFile) blobberCount := 0 countThreshold := req.consensusThresh + 1 if countThreshold > req.fullconsensus { @@ -1215,12 +1211,6 @@ func (req *DownloadRequest) getFileMetaConsensus(fMetaResp []*fileMetaResponse) continue } - blobber := req.blobbers[fmr.blobberIdx] - vr, _ := hex.DecodeString(fmr.fileref.ValidationRoot) - req.validationRootMap[blobber.ID] = &blobberFile{ - size: fmr.fileref.Size, - validationRoot: vr, - } shift := zboxutil.NewUint128(1).Lsh(uint64(fmr.blobberIdx)) foundMask = foundMask.Or(shift) req.downloadQueue[fmr.blobberIdx] = downloadPriority{ diff --git a/zboxcore/sdk/reader.go b/zboxcore/sdk/reader.go index ca380c00f..711bc9c15 100644 --- a/zboxcore/sdk/reader.go +++ b/zboxcore/sdk/reader.go @@ -168,16 +168,15 @@ func GetDStorageFileReader(alloc *Allocation, ref *ORef, sdo *StreamDownloadOpti sd := &StreamDownload{ DownloadRequest: &DownloadRequest{ - allocationID: alloc.ID, - allocationTx: alloc.Tx, - allocOwnerID: alloc.Owner, - allocOwnerPubKey: alloc.OwnerPublicKey, - datashards: alloc.DataShards, - parityshards: alloc.ParityShards, - remotefilepath: ref.Path, - numBlocks: int64(sdo.BlocksPerMarker), - validationRootMap: make(map[string]*blobberFile), - shouldVerify: sdo.VerifyDownload, + allocationID: alloc.ID, + allocationTx: alloc.Tx, + allocOwnerID: alloc.Owner, + allocOwnerPubKey: alloc.OwnerPublicKey, + datashards: alloc.DataShards, + parityshards: alloc.ParityShards, + remotefilepath: ref.Path, + numBlocks: int64(sdo.BlocksPerMarker), + shouldVerify: sdo.VerifyDownload, Consensus: Consensus{ RWMutex: &sync.RWMutex{}, fullconsensus: alloc.fullconsensus, From f5b51c041d86592ff8c7ac37e0075ac0acb2f786 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 27 Jul 2024 14:28:48 +0530 Subject: [PATCH 011/107] remove single blobber for single client mode --- zboxcore/sdk/allocation.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 6154cb69d..117fb8941 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -1429,9 +1429,10 @@ func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, for _, opt := range opts { opt(oTreeReq) } - if singleClientMode { - oTreeReq.singleBlobber = true - } + //TODO: Have a mask on allocation object to track blobbers which are on latest version + // if singleClientMode { + // oTreeReq.singleBlobber = true + // } return oTreeReq.GetRefs() } From 4d33f272e936abd3365b2a905a0dbcf56f3cf84c Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 27 Jul 2024 16:54:01 +0530 Subject: [PATCH 012/107] add check for nil ref --- zboxcore/sdk/deleteworker.go | 6 +++++- zboxcore/sdk/multi_operation_worker.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 1db2e9a2c..00c203ef3 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -395,7 +395,8 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( deleteReq.consensus.consensusThresh, deleteReq.consensus.consensus)) } if consensusRef == nil { - return nil, deleteReq.deleteMask, thrown.New("delete_failed", "Delete failed. No consensus found") + //Already deleted + return objectTreeRefs, dop.deleteMask, nil } if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { for ind, refEntity := range objectTreeRefs { @@ -409,6 +410,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( } } pos = 0 + deleteReq.consensus.Reset() for i := deleteReq.deleteMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) deleteReq.wg.Add(1) @@ -416,8 +418,10 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( defer deleteReq.wg.Done() err := deleteReq.deleteBlobberFile(deleteReq.blobbers[blobberIdx], blobberIdx) if err != nil { + logger.Logger.Error("error during deleteBlobberFile", err) blobberErrors[blobberIdx] = err } + deleteReq.consensus.Done() if singleClientMode { lookuphash := fileref.GetReferenceLookup(deleteReq.allocationID, deleteReq.remotefilepath) cacheKey := fileref.GetCacheKey(lookuphash, deleteReq.blobbers[blobberIdx].ID) diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index cb2807d1f..fcea1047d 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -189,7 +189,7 @@ func (mo *MultiOperation) Process() error { return } mo.maskMU.Lock() - mo.operationMask = mo.operationMask.Or(mask) + mo.operationMask = mo.operationMask.And(mask) mo.maskMU.Unlock() changes := op.buildChange(refs, uid) mo.changes[idx] = changes From 796de38ecaaf700a7525d52d639780f590310dd8 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 27 Jul 2024 17:14:41 +0530 Subject: [PATCH 013/107] remove mask reset --- zboxcore/sdk/allocation.go | 1 + zboxcore/sdk/multi_operation_worker.go | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 117fb8941..c81a5de9c 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -977,6 +977,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest, opts ...Mul if len(mo.operations) > 0 { err := mo.Process() if err != nil { + logger.Logger.Error("Error in multi operation", zap.Error(err)) return err } diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index fcea1047d..7a200b403 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -167,7 +167,6 @@ func (mo *MultiOperation) Process() error { defer ctxCncl(nil) swg := sizedwaitgroup.New(BatchSize) errsSlice := make([]error, len(mo.operations)) - mo.operationMask = zboxutil.NewUint128(0) for idx, op := range mo.operations { uid := util.GetNewUUID() swg.Add() @@ -312,7 +311,7 @@ func (mo *MultiOperation) Process() error { counter++ } wg.Wait() - logger.Logger.Debug("[commitRequests]", time.Since(start).Milliseconds()) + logger.Logger.Info("[commitRequests]", time.Since(start).Milliseconds()) rollbackMask := zboxutil.NewUint128(0) errSlice := make([]error, len(commitReqs)) for idx, commitReq := range commitReqs { @@ -353,6 +352,7 @@ func (mo *MultiOperation) Process() error { } } mo.allocationObj.AllocationVersion += 1 + logger.Logger.Info("Allocation version updated to ", mo.allocationObj.AllocationVersion) } } From da1aa5526abad6f130ae4fdb4e89f8fc00ab1995 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 27 Jul 2024 17:28:16 +0530 Subject: [PATCH 014/107] check change count --- zboxcore/sdk/commitworker.go | 5 ----- zboxcore/sdk/deleteworker.go | 2 +- zboxcore/sdk/multi_operation_worker.go | 15 ++++++++------- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index 61830cbf3..ea847b456 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -102,11 +102,6 @@ func (commitreq *CommitRequest) processCommit() { defer commitreq.wg.Done() start := time.Now() l.Logger.Debug("received a commit request") - if len(commitreq.changes) == 0 { - l.Logger.Debug("Nothing to commit") - commitreq.result = SuccessCommitResult() - return - } err := commitreq.commitBlobber() if err != nil { commitreq.result = ErrorCommitResult(err.Error()) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 00c203ef3..9d5750b6d 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -396,7 +396,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( } if consensusRef == nil { //Already deleted - return objectTreeRefs, dop.deleteMask, nil + return nil, dop.deleteMask, nil } if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { for ind, refEntity := range objectTreeRefs { diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 7a200b403..d6d9694c8 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -14,7 +14,6 @@ import ( "github.com/remeh/sizedwaitgroup" "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk/zboxcore/client" "github.com/0chain/gosdk/zboxcore/fileref" @@ -167,8 +166,8 @@ func (mo *MultiOperation) Process() error { defer ctxCncl(nil) swg := sizedwaitgroup.New(BatchSize) errsSlice := make([]error, len(mo.operations)) + var changeCount int for idx, op := range mo.operations { - uid := util.GetNewUUID() swg.Add() go func(op Operationer, idx int) { defer swg.Done() @@ -189,9 +188,10 @@ func (mo *MultiOperation) Process() error { } mo.maskMU.Lock() mo.operationMask = mo.operationMask.And(mask) + if refs != nil { + changeCount += 1 + } mo.maskMU.Unlock() - changes := op.buildChange(refs, uid) - mo.changes[idx] = changes }(op, idx) } swg.Wait() @@ -212,12 +212,15 @@ func (mo *MultiOperation) Process() error { return nil } + if changeCount == 0 { + return nil + } + // Take transpose of mo.change because it will be easier to iterate mo if it contains blobber changes // in row instead of column. Currently mo.change[0] contains allocationChange for operation 1 and so on. // But we want mo.changes[0] to have allocationChange for blobber 1 and mo.changes[1] to have allocationChange for // blobber 2 and so on. start := time.Now() - mo.changes = zboxutil.Transpose(mo.changes) writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), mo.allocationObj) if err != nil { @@ -303,8 +306,6 @@ func (mo *MultiOperation) Process() error { blobberInd: pos, version: mo.allocationObj.Blobbers[pos].AllocationVersion + 1, } - - commitReq.changes = append(commitReq.changes, mo.changes[pos]...) commitReqs[counter] = commitReq l.Logger.Debug("Commit request sending to blobber ", commitReq.blobber.Baseurl) go AddCommitRequest(commitReq) From a9814dfb788b56077fcf7cf019749d810ec42de9 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 27 Jul 2024 17:59:07 +0530 Subject: [PATCH 015/107] chane ref check --- zboxcore/sdk/deleteworker.go | 4 +++- zboxcore/sdk/multi_operation_worker.go | 14 +++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 9d5750b6d..b1a07026e 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -43,6 +43,8 @@ type DeleteRequest struct { timestamp int64 } +var ErrFileDeleted = errors.New("file_deleted", "file is already deleted") + func (req *DeleteRequest) deleteBlobberFile( blobber *blockchain.StorageNode, blobberIdx int) error { @@ -396,7 +398,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( } if consensusRef == nil { //Already deleted - return nil, dop.deleteMask, nil + return nil, dop.deleteMask, ErrFileDeleted } if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { for ind, refEntity := range objectTreeRefs { diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index d6d9694c8..fbb71aab6 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -179,18 +179,18 @@ func (mo *MultiOperation) Process() error { default: } - refs, mask, err := op.Process(mo.allocationObj, mo.connectionID) // Process with each blobber + _, mask, err := op.Process(mo.allocationObj, mo.connectionID) // Process with each blobber if err != nil { - l.Logger.Error(err) - errsSlice[idx] = errors.New("", err.Error()) - ctxCncl(err) + if err != ErrFileDeleted { + l.Logger.Error(err) + errsSlice[idx] = errors.New("", err.Error()) + ctxCncl(err) + } return } mo.maskMU.Lock() mo.operationMask = mo.operationMask.And(mask) - if refs != nil { - changeCount += 1 - } + changeCount += 1 mo.maskMU.Unlock() }(op, idx) } From 08de511abcd90db3697c2afb065c71c6242b260b Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Mon, 29 Jul 2024 11:22:44 +0530 Subject: [PATCH 016/107] remove validation root from Ref --- zboxcore/allocationchange/newfile.go | 11 ----------- zboxcore/allocationchange/updatefile.go | 11 ----------- zboxcore/fileref/fileref.go | 19 +++++++------------ zboxcore/sdk/allocation_test.go | 9 +-------- zboxcore/sdk/downloadworker.go | 14 -------------- 5 files changed, 8 insertions(+), 56 deletions(-) diff --git a/zboxcore/allocationchange/newfile.go b/zboxcore/allocationchange/newfile.go index 8e3fd91ea..cdc501e4f 100644 --- a/zboxcore/allocationchange/newfile.go +++ b/zboxcore/allocationchange/newfile.go @@ -35,23 +35,12 @@ func (ch *NewFileChange) ProcessChange(rootRef *fileref.Ref, fileIDMeta map[stri return } - if ch.File.ValidationRoot == "" { - err = errors.New("empty validation root field") - return - } - fileHashSign, err := client.Sign(ch.File.ActualFileHash) if err != nil { return } - validationRootSign, err := client.Sign(fileHashSign + ch.File.ValidationRoot) - if err != nil { - return - } - ch.File.ActualFileHashSignature = fileHashSign - ch.File.ValidationRootSignature = validationRootSign rootRef.HashToBeComputed = true dirRef := rootRef diff --git a/zboxcore/allocationchange/updatefile.go b/zboxcore/allocationchange/updatefile.go index f3b89ae8d..b95b9669f 100644 --- a/zboxcore/allocationchange/updatefile.go +++ b/zboxcore/allocationchange/updatefile.go @@ -23,23 +23,12 @@ func (ch *UpdateFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]str return } - if ch.NewFile.ValidationRoot == "" { - err = fmt.Errorf("empty validation root field") - return - } - fileHashSign, err := client.Sign(ch.NewFile.ActualFileHash) if err != nil { return } - validationRootSign, err := client.Sign(fileHashSign + ch.NewFile.ValidationRoot) - if err != nil { - return - } - ch.NewFile.ActualFileHashSignature = fileHashSign - ch.NewFile.ValidationRootSignature = validationRootSign fields, err := common.GetPathFields(pathutil.Dir(ch.NewFile.Path)) diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index c79f343ce..7dc024093 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -29,16 +29,13 @@ type Collaborator struct { } type FileRef struct { - Ref `mapstructure:",squash"` - CustomMeta string `json:"custom_meta" mapstructure:"custom_meta"` - ValidationRoot string `json:"validation_root" mapstructure:"validation_root"` + Ref `mapstructure:",squash"` + CustomMeta string `json:"custom_meta" mapstructure:"custom_meta"` // ValidationRootSignature is signature signed by client for hash_of(ActualFileHashSignature + ValidationRoot) - ValidationRootSignature string `json:"validation_root_signature" mapstructure:"validation_root_signature"` - FixedMerkleRoot string `json:"fixed_merkle_root" mapstructure:"fixed_merkle_root"` - ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` - ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` - ActualFileSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` - ActualFileHash string `json:"actual_file_hash" mapstructure:"actual_file_hash"` + ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` + ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` + ActualFileSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` + ActualFileHash string `json:"actual_file_hash" mapstructure:"actual_file_hash"` // ActualFileHashSignature is signature signed by client for ActualFileHash ActualFileHashSignature string `json:"actual_file_hash_signature" mapstructure:"actual_file_hash_signature"` ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` @@ -252,14 +249,12 @@ func (fr *FileRef) GetFileMetaHashData() string { func (fr *FileRef) GetHashData() string { return fmt.Sprintf( - "%s:%s:%s:%s:%d:%s:%s:%d:%s:%d:%s", + "%s:%s:%s:%s:%d:%d:%s:%d:%s", fr.AllocationID, fr.Type, // don't need to add it as well fr.Name, // don't see any utility as fr.Path below has name in it fr.Path, fr.Size, - fr.ValidationRoot, - fr.FixedMerkleRoot, fr.ActualFileSize, fr.ActualFileHash, fr.ChunkSize, diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index cf283343c..e98d2c23c 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -1171,7 +1171,6 @@ func TestAllocation_GetAuthTicketForShare(t *testing.T) { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: mockValidationRoot, }) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) @@ -1226,7 +1225,6 @@ func TestAllocation_GetAuthTicket(t *testing.T) { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: "mock validation root", }) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) @@ -1258,7 +1256,6 @@ func TestAllocation_GetAuthTicket(t *testing.T) { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: "mock validation root", }) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) @@ -1310,7 +1307,6 @@ func TestAllocation_GetAuthTicket(t *testing.T) { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: "mock validation root", }) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) @@ -1351,7 +1347,6 @@ func TestAllocation_GetAuthTicket(t *testing.T) { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: "mock validation root", }) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) @@ -2384,7 +2379,6 @@ func setupMockGetFileInfoResponse(t *testing.T, mockClient *mocks.HttpClient) { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: "mock validation root", }) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) @@ -2425,8 +2419,7 @@ func getMockAuthTicket(t *testing.T) string { Ref: fileref.Ref{ Name: mockFileRefName, }, - ValidationRoot: "mock validation root", - EncryptedKey: "encrypted key", + EncryptedKey: "encrypted key", }) require.NoError(t, err) diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index e9c56c131..93d174b91 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -1196,20 +1196,6 @@ func (req *DownloadRequest) getFileMetaConsensus(fMetaResp []*fileMetaResponse) continue } - isValid, err := sys.VerifyWith( - req.allocOwnerPubKey, - fRef.ValidationRootSignature, - fRef.ActualFileHashSignature+fRef.ValidationRoot, - ) - if err != nil { - l.Logger.Error(err, "allocOwnerPubKey: ", req.allocOwnerPubKey, " validationRootSignature: ", fRef.ValidationRootSignature, " actualFileHashSignature: ", fRef.ActualFileHashSignature, " validationRoot: ", fRef.ValidationRoot) - continue - } - if !isValid { - l.Logger.Error("invalid validation root signature") - continue - } - shift := zboxutil.NewUint128(1).Lsh(uint64(fmr.blobberIdx)) foundMask = foundMask.Or(shift) req.downloadQueue[fmr.blobberIdx] = downloadPriority{ From e7df719aa344bcb1094551be1c9b404a5732e3ab Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 31 Jul 2024 13:43:34 +0530 Subject: [PATCH 017/107] add list logs --- zboxcore/sdk/allocation.go | 2 +- zboxcore/sdk/filerefsworker.go | 12 +++++++----- zboxcore/sdk/multi_operation_worker.go | 6 +++--- zboxcore/sdk/repairworker.go | 3 +++ zboxcore/sdk/rollback.go | 2 +- 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index c81a5de9c..13c1ee086 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -202,7 +202,6 @@ type Allocation struct { MovedToValidators common.Balance `json:"moved_to_validators,omitempty"` FileOptions uint16 `json:"file_options"` ThirdPartyExtendable bool `json:"third_party_extendable"` - AllocationVersion int64 `json:"-"` numBlockDownloads int downloadChan chan *DownloadRequest @@ -220,6 +219,7 @@ type Allocation struct { // conseususes consensusThreshold int fullconsensus int + allocationVersion int64 } type OperationRequest struct { diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index dccea9af2..6b7a477ed 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -86,10 +86,9 @@ func WithSingleBlobber(singleBlobber bool) ObjectTreeRequestOption { // Paginated tree should not be collected as this will stall the client // It should rather be handled by application that uses gosdk func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { - totalBlobbersCount := len(o.blobbers) - oTreeResponses := make([]oTreeResponse, totalBlobbersCount) - respChan := make(chan *oTreeResponse, totalBlobbersCount) activeCount := o.reqMask.CountOnes() + oTreeResponses := make([]oTreeResponse, activeCount) + respChan := make(chan *oTreeResponse, activeCount) if o.singleBlobber { var respErr error for i := 0; i < activeCount; i++ { @@ -125,15 +124,16 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { hashCount := make(map[string]int) hashRefsMap := make(map[string]*ObjectTreeResult) - oTreeResponseErrors := make([]error, totalBlobbersCount) + oTreeResponseErrors := make([]error, activeCount) var successCount int - for i := 0; i < totalBlobbersCount; i++ { + for i := 0; i < activeCount; i++ { select { case <-o.ctx.Done(): return nil, o.ctx.Err() case oTreeResponse := <-respChan: oTreeResponseErrors[oTreeResponse.idx] = oTreeResponse.err if oTreeResponse.err != nil { + l.Logger.Error(oTreeResponse.err) if code, _ := zboxutil.GetErrorMessageCode(oTreeResponse.err.Error()); code != INVALID_PATH { l.Logger.Error("Error while getting file refs from blobber:", oTreeResponse.err) } @@ -141,6 +141,7 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { } successCount++ hash := oTreeResponse.hash + l.Logger.Info("getRefsHash", hash) if _, ok := hashCount[hash]; ok { hashCount[hash]++ } else { @@ -255,6 +256,7 @@ func (o *ObjectTreeRequest) getFileRefs(bUrl string, respChan chan *oTreeRespons similarFieldRefs = append(similarFieldRefs, decodeBytes...) } oTR.hash = zboxutil.GetRefsHash(similarFieldRefs) + l.Logger.Info("getFileRefs: ", " blobber: ", bUrl, " path: ", o.remotefilepath, " hash: ", oTR.hash) } // Blobber response will be different from each other so we should only consider similar fields diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index fbb71aab6..0c18cefdc 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -280,7 +280,7 @@ func (mo *MultiOperation) Process() error { var pos uint64 for i := mo.operationMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) - if mo.allocationObj.Blobbers[pos].AllocationVersion != mo.allocationObj.AllocationVersion { + if mo.allocationObj.Blobbers[pos].AllocationVersion != mo.allocationObj.allocationVersion { mo.operationMask = mo.operationMask.And(zboxutil.NewUint128(1).Lsh(pos).Not()) } } @@ -352,8 +352,8 @@ func (mo *MultiOperation) Process() error { mo.allocationObj.Blobbers[commitReq.blobberInd].AllocationVersion++ } } - mo.allocationObj.AllocationVersion += 1 - logger.Logger.Info("Allocation version updated to ", mo.allocationObj.AllocationVersion) + mo.allocationObj.allocationVersion += 1 + logger.Logger.Info("Allocation version updated to ", mo.allocationObj.allocationVersion, " activeBlobbers ", activeBlobbers) } } diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index 466e9ebab..84255e054 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -315,3 +315,6 @@ func (r *RepairRequest) checkForCancel(a *Allocation) bool { } return false } + +//repair for enterprise workflow +// list all files in the allocation recursively and repair them diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index a288c5de2..7295ed51c 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -313,7 +313,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { } if consensusReached { - a.AllocationVersion = latestVersion + a.allocationVersion = latestVersion return Commit, blobberRes, nil } From c2e8b89de390bee37d5c236ad5da6b90037f9411 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 31 Jul 2024 14:06:03 +0530 Subject: [PATCH 018/107] add response --- zboxcore/sdk/filerefsworker.go | 5 +++-- zboxcore/zboxutil/util.go | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 6b7a477ed..ca5276d86 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -139,9 +139,10 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { } continue } + oTreeResponses[oTreeResponse.idx] = *oTreeResponse successCount++ hash := oTreeResponse.hash - l.Logger.Info("getRefsHash", hash) + l.Logger.Info("getRefsHash", hash, " blobber: ", o.blobbers[oTreeResponse.idx].Baseurl) if _, ok := hashCount[hash]; ok { hashCount[hash]++ } else { @@ -171,7 +172,7 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { selected = &ObjectTreeResult{} minPage := int64(math.MaxInt64) for _, oTreeResponse := range oTreeResponses { - if oTreeResponse.err != nil { + if oTreeResponse.err != nil || oTreeResponse.oTResult == nil { continue } if oTreeResponse.oTResult.TotalPages < minPage { diff --git a/zboxcore/zboxutil/util.go b/zboxcore/zboxutil/util.go index c216305d1..3c38d91f9 100644 --- a/zboxcore/zboxutil/util.go +++ b/zboxcore/zboxutil/util.go @@ -5,6 +5,7 @@ import ( "crypto/cipher" "crypto/rand" "encoding/base64" + "encoding/hex" "encoding/json" "fmt" "io" @@ -218,7 +219,7 @@ func GetRefsHash(r []byte) string { hash.Write(r) var buf []byte buf = hash.Sum(buf) - return string(buf) + return hex.EncodeToString(buf) } func GetActiveBlobbers(dirMask uint32, blobbers []*blockchain.StorageNode) []*blockchain.StorageNode { From 4496ab62f025baea21a3065709d54975d1a7bbad Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 31 Jul 2024 14:19:45 +0530 Subject: [PATCH 019/107] add debug logs --- zboxcore/sdk/allocation.go | 5 +++++ zboxcore/sdk/filerefsworker.go | 11 ++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 13c1ee086..427bd1f47 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -1434,6 +1434,11 @@ func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, // if singleClientMode { // oTreeReq.singleBlobber = true // } + for _, blob := range a.Blobbers { + if blob.AllocationVersion != a.allocationVersion { + l.Logger.Error("blobber not on latest version: ", blob.Baseurl, " version: ", blob.AllocationVersion, " latest version: ", a.allocationVersion) + } + } return oTreeReq.GetRefs() } diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index ca5276d86..5c1e3f3aa 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -87,6 +87,7 @@ func WithSingleBlobber(singleBlobber bool) ObjectTreeRequestOption { // It should rather be handled by application that uses gosdk func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { activeCount := o.reqMask.CountOnes() + l.Logger.Info("GetRefs: ", " path: ", o.remotefilepath, " pageLimit: ", o.pageLimit, " offsetPath: ", o.offsetPath, " activeCount: ", activeCount) oTreeResponses := make([]oTreeResponse, activeCount) respChan := make(chan *oTreeResponse, activeCount) if o.singleBlobber { @@ -142,7 +143,6 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { oTreeResponses[oTreeResponse.idx] = *oTreeResponse successCount++ hash := oTreeResponse.hash - l.Logger.Info("getRefsHash", hash, " blobber: ", o.blobbers[oTreeResponse.idx].Baseurl) if _, ok := hashCount[hash]; ok { hashCount[hash]++ } else { @@ -154,6 +154,7 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { } } } + l.Logger.Info("no consensus found: ", o.remotefilepath, " pageLimit: ", o.pageLimit, " offsetPath: ", o.offsetPath) var selected *ObjectTreeResult if successCount < o.consensusThresh { majorError := zboxutil.MajorError(oTreeResponseErrors) @@ -190,6 +191,14 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { } } if len(selected.Refs) > 0 { + for _, oTreeResponse := range oTreeResponses { + if oTreeResponse.err != nil || oTreeResponse.oTResult == nil { + continue + } + if len(selected.Refs) != len(oTreeResponse.oTResult.Refs) { + l.Logger.Error("Consensus failed for refs: ", o.blobbers[oTreeResponse.idx].Baseurl) + } + } selected.OffsetPath = selected.Refs[len(selected.Refs)-1].Path return selected, nil } From daa353d079dc500c80e6c7703a70578a577ec1a3 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 31 Jul 2024 14:27:48 +0530 Subject: [PATCH 020/107] add log for selected file ref --- zboxcore/sdk/filerefsworker.go | 1 + 1 file changed, 1 insertion(+) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 5c1e3f3aa..cb8bc655b 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -181,6 +181,7 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { selected.TotalPages = minPage } for _, ref := range oTreeResponse.oTResult.Refs { + l.Logger.Info("selectFileRef: ", " blobber: ", o.blobbers[oTreeResponse.idx].Baseurl, " path: ", ref.Path, " hash: ", ref.FileMetaHash) if refHash[ref.FileMetaHash] == o.consensusThresh { continue } From 974959f729468524f32c4c5a99eb288dbb1eaf33 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 31 Jul 2024 22:41:25 +0530 Subject: [PATCH 021/107] add check for rate limit --- zboxcore/sdk/filerefsworker.go | 103 ++++++++++++++++++++------------- 1 file changed, 62 insertions(+), 41 deletions(-) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index cb8bc655b..4ea47b928 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -15,6 +15,7 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zboxcore/blockchain" + "github.com/0chain/gosdk/zboxcore/logger" l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/zboxutil" @@ -57,6 +58,8 @@ type oTreeResponse struct { idx int } +var errTooManyRequests = errors.New("too_many_requests", "Too many requests") + type ObjectTreeRequestOption func(*ObjectTreeRequest) func WithObjectContext(ctx context.Context) ObjectTreeRequestOption { @@ -154,7 +157,7 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { } } } - l.Logger.Info("no consensus found: ", o.remotefilepath, " pageLimit: ", o.pageLimit, " offsetPath: ", o.offsetPath) + l.Logger.Error("no consensus found: ", o.remotefilepath, " pageLimit: ", o.pageLimit, " offsetPath: ", o.offsetPath) var selected *ObjectTreeResult if successCount < o.consensusThresh { majorError := zboxutil.MajorError(oTreeResponseErrors) @@ -181,7 +184,6 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { selected.TotalPages = minPage } for _, ref := range oTreeResponse.oTResult.Refs { - l.Logger.Info("selectFileRef: ", " blobber: ", o.blobbers[oTreeResponse.idx].Baseurl, " path: ", ref.Path, " hash: ", ref.FileMetaHash) if refHash[ref.FileMetaHash] == o.consensusThresh { continue } @@ -213,52 +215,72 @@ func (o *ObjectTreeRequest) getFileRefs(bUrl string, respChan chan *oTreeRespons defer func() { respChan <- oTR }() - oReq, err := zboxutil.NewRefsRequest( - bUrl, - o.allocationID, - o.allocationTx, - o.remotefilepath, - o.pathHash, - o.authToken, - o.offsetPath, - o.updatedDate, - o.offsetDate, - o.fileType, - o.refType, - o.level, - o.pageLimit, - ) - if err != nil { - oTR.err = err - return - } + oResult := ObjectTreeResult{} - ctx, cncl := context.WithTimeout(o.ctx, 2*time.Minute) - err = zboxutil.HttpDo(ctx, cncl, oReq, func(resp *http.Response, err error) error { - if err != nil { - l.Logger.Error(err) - return err - } - defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) + for i := 0; i < 3; i++ { + oReq, err := zboxutil.NewRefsRequest( + bUrl, + o.allocationID, + o.allocationTx, + o.remotefilepath, + o.pathHash, + o.authToken, + o.offsetPath, + o.updatedDate, + o.offsetDate, + o.fileType, + o.refType, + o.level, + o.pageLimit, + ) if err != nil { - l.Logger.Error(err) - return err + oTR.err = err + return } - if resp.StatusCode == http.StatusOK { - err := json.Unmarshal(respBody, &oResult) + ctx, cncl := context.WithTimeout(o.ctx, 2*time.Minute) + defer cncl() + err = zboxutil.HttpDo(ctx, cncl, oReq, func(resp *http.Response, err error) error { if err != nil { l.Logger.Error(err) return err } - return nil - } else { - return errors.New("response_error", fmt.Sprintf("got status %d, err: %s", resp.StatusCode, respBody)) + defer resp.Body.Close() + respBody, err := ioutil.ReadAll(resp.Body) + if err != nil { + l.Logger.Error(err) + return err + } + if resp.StatusCode == http.StatusOK { + err := json.Unmarshal(respBody, &oResult) + if err != nil { + l.Logger.Error(err) + return err + } + return nil + } else { + if resp.StatusCode == http.StatusTooManyRequests { + l.Logger.Error("Too many requests") + r, err := zboxutil.GetRateLimitValue(resp) + if err != nil { + logger.Logger.Error(err) + return err + } + + time.Sleep(time.Duration(r) * time.Second) + return errTooManyRequests + } + + return errors.New("response_error", fmt.Sprintf("got status %d, err: %s", resp.StatusCode, respBody)) + } + }) + if err != nil { + if err == errTooManyRequests && i < 2 { + continue + } + oTR.err = err + return } - }) - if err != nil { - oTR.err = err - return + break } oTR.oTResult = &oResult similarFieldRefs := make([]byte, 0, 32*len(oResult.Refs)) @@ -267,7 +289,6 @@ func (o *ObjectTreeRequest) getFileRefs(bUrl string, respChan chan *oTreeRespons similarFieldRefs = append(similarFieldRefs, decodeBytes...) } oTR.hash = zboxutil.GetRefsHash(similarFieldRefs) - l.Logger.Info("getFileRefs: ", " blobber: ", bUrl, " path: ", o.remotefilepath, " hash: ", oTR.hash) } // Blobber response will be different from each other so we should only consider similar fields From ec1a470a3fe7bfd8340b29c223863d9788216a1f Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 1 Aug 2024 00:15:19 +0530 Subject: [PATCH 022/107] remove get ref log --- zboxcore/sdk/filerefsworker.go | 1 - 1 file changed, 1 deletion(-) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 4ea47b928..6b2f5714d 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -90,7 +90,6 @@ func WithSingleBlobber(singleBlobber bool) ObjectTreeRequestOption { // It should rather be handled by application that uses gosdk func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { activeCount := o.reqMask.CountOnes() - l.Logger.Info("GetRefs: ", " path: ", o.remotefilepath, " pageLimit: ", o.pageLimit, " offsetPath: ", o.offsetPath, " activeCount: ", activeCount) oTreeResponses := make([]oTreeResponse, activeCount) respChan := make(chan *oTreeResponse, activeCount) if o.singleBlobber { From facdb4f89c04d7d1f419fe83ba26b69cd3c14c2c Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Mon, 5 Aug 2024 15:02:13 +0530 Subject: [PATCH 023/107] add repair for enterprise blobbers --- zboxcore/sdk/allocation.go | 27 +- zboxcore/sdk/chunked_upload.go | 11 +- zboxcore/sdk/common.go | 96 +++++ zboxcore/sdk/copyworker.go | 169 ++++++++- zboxcore/sdk/copyworker_test.go | 2 +- zboxcore/sdk/deleteworker.go | 10 +- zboxcore/sdk/filerefsworker.go | 24 +- zboxcore/sdk/moveworker.go | 92 ++++- zboxcore/sdk/multi_operation_worker.go | 26 +- zboxcore/sdk/renameworker.go | 80 +++- zboxcore/sdk/renameworker_test.go | 2 +- zboxcore/sdk/repairworker.go | 506 +++++++++++++++++-------- 12 files changed, 794 insertions(+), 251 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 427bd1f47..9f06ed3b9 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -39,12 +39,13 @@ import ( ) var ( - noBLOBBERS = errors.New("", "No Blobbers set in this allocation") - notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") - IsWasm = false - MultiOpBatchSize = 50 - RepairBatchSize = 50 - Workdir string + noBLOBBERS = errors.New("", "No Blobbers set in this allocation") + notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") + IsWasm = false + MultiOpBatchSize = 50 + RepairBatchSize = 50 + Workdir string + multiOpRepairBatchSize = 10 ) const ( @@ -409,12 +410,11 @@ func (a *Allocation) UploadFile(workdir, localpath string, remotepath string, return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false, "", false, false) } -func (a *Allocation) RepairFile(file sys.File, remotepath string, statusCallback StatusCallback, mask zboxutil.Uint128, ref *fileref.FileRef) *OperationRequest { +func (a *Allocation) RepairFile(file sys.File, remotepath string, statusCallback StatusCallback, mask zboxutil.Uint128, ref ORef) *OperationRequest { idr, _ := homedir.Dir() if Workdir != "" { idr = Workdir } - mask = mask.Not().And(zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1)) fileMeta := FileMeta{ ActualSize: ref.ActualFileSize, MimeType: ref.MimeType, @@ -937,7 +937,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest, opts ...Mul case constants.FileOperationDelete: if op.Mask != nil { - operation = NewDeleteOperation(op.RemotePath, *op.Mask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) + operation = NewDeleteOperation(op.RemotePath, *op.Mask, mo.maskMU, op.Mask.CountOnes(), mo.fullconsensus, mo.ctx) } else { operation = NewDeleteOperation(op.RemotePath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) } @@ -1434,11 +1434,6 @@ func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, // if singleClientMode { // oTreeReq.singleBlobber = true // } - for _, blob := range a.Blobbers { - if blob.AllocationVersion != a.allocationVersion { - l.Logger.Error("blobber not on latest version: ", blob.Baseurl, " version: ", blob.AllocationVersion, " latest version: ", a.allocationVersion) - } - } return oTreeReq.GetRefs() } @@ -1536,7 +1531,7 @@ func (a *Allocation) GetRefs(path, offsetPath, updatedDate, offsetDate, fileType return nil, errors.New("invalid_path", fmt.Sprintf("Absolute path required. Path provided: %v", path)) } - return a.getRefs(path, "", "", offsetPath, updatedDate, offsetDate, fileType, refType, level, pageLimit) + return a.getRefs(path, "", "", offsetPath, updatedDate, offsetDate, fileType, refType, level, pageLimit, opts...) } func (a *Allocation) GetRefsFromLookupHash(pathHash, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int) (*ObjectTreeResult, error) { @@ -2316,11 +2311,13 @@ func (a *Allocation) StartRepair(localRootPath, pathToRepair string, statusCB St if err != nil { return err } + a.CheckAllocStatus() //nolint:errcheck repairReq := &RepairRequest{ listDir: listDir, localRootPath: localRootPath, statusCB: statusCB, + repairPath: pathToRepair, } repairReq.completedCallback = func() { diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 00f514340..2798b851b 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -154,11 +154,6 @@ func CreateChunkedUpload( } uploadMask := zboxutil.NewUint128(1).Lsh(uint64(len(allocationObj.Blobbers))).Sub64(1) - if isRepair { - opCode = OpUpdate - consensus.fullconsensus = uploadMask.CountOnes() - consensus.consensusThresh = 1 - } su := &ChunkedUpload{ allocationObj: allocationObj, @@ -216,6 +211,12 @@ func CreateChunkedUpload( opt(su) } + if isRepair { + opCode = OpUpdate + su.consensus.fullconsensus = su.uploadMask.CountOnes() + su.consensus.consensusThresh = su.uploadMask.CountOnes() + } + if su.progressStorer == nil && shouldSaveProgress { su.progressStorer = createFsChunkedUploadProgress(context.Background()) } diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 211effe76..6f5a6fd8a 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -8,6 +8,7 @@ import ( "net/http" "path" "strconv" + "strings" "sync" "time" @@ -120,3 +121,98 @@ func ValidateRemoteFileName(remotePath string) error { return nil } + +type subDirRequest struct { + opType string + remotefilepath string + destPath string + allocationObj *Allocation + ctx context.Context + consensusThresh int + mask zboxutil.Uint128 +} + +func (req *subDirRequest) processSubDirectories() error { + var ( + offsetPath string + pathLevel int + ) + + for { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WithObjectConsensusThresh(req.consensusThresh), WithSingleBlobber(true), WithObjectMask(req.mask)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + break + } + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.mask + if ref.Type == fileref.DIRECTORY { + continue + } + if ref.PathLevel > pathLevel { + pathLevel = ref.PathLevel + } + destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + op := OperationRequest{ + OperationType: req.opType, + RemotePath: ref.Path, + DestPath: destPath, + Mask: &opMask, + } + ops = append(ops, op) + } + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err + } + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + if len(oResult.Refs) < getRefPageLimit { + break + } + } + + offsetPath = "" + level := len(strings.Split(strings.TrimSuffix(req.remotefilepath, "/"), "/")) + if pathLevel == 0 { + pathLevel = level + 1 + } + + for pathLevel > level { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.DIRECTORY, fileref.REGULAR, pathLevel, getRefPageLimit, WithObjectContext(req.ctx), WithObjectMask(req.mask), WithObjectConsensusThresh(req.consensusThresh), WithSingleBlobber(true)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + pathLevel-- + } else { + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.mask + if ref.Type == fileref.FILE { + continue + } + destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + op := OperationRequest{ + OperationType: req.opType, + RemotePath: ref.Path, + DestPath: destPath, + Mask: &opMask, + } + ops = append(ops, op) + } + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err + } + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + if len(oResult.Refs) < getRefPageLimit { + pathLevel-- + } + } + } + + return nil +} diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index cb47ee6a0..98678545d 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -47,8 +47,27 @@ func (req *CopyRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNode return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.remotefilepath, blobber) } +func (req *CopyRequest) getFileMetaFromBlobber(pos int) (fileRef *fileref.FileRef, err error) { + listReq := &ListRequest{ + allocationID: req.allocationID, + allocationTx: req.allocationTx, + blobbers: req.blobbers, + remotefilepath: req.remotefilepath, + ctx: req.ctx, + } + respChan := make(chan *fileMetaResponse) + go listReq.getFileMetaInfoFromBlobber(req.blobbers[pos], int(pos), respChan) + refRes := <-respChan + if refRes.err != nil { + err = refRes.err + return + } + fileRef = refRes.fileref + return +} + func (req *CopyRequest) copyBlobberObject( - blobber *blockchain.StorageNode, blobberIdx int) (refEntity fileref.RefEntity, err error) { + blobber *blockchain.StorageNode, blobberIdx int) (err error) { defer func() { if err != nil { @@ -58,11 +77,6 @@ func (req *CopyRequest) copyBlobberObject( req.maskMU.Unlock() } }() - refEntity, err = req.getObjectTreeFromBlobber(req.blobbers[blobberIdx]) - if err != nil { - return nil, err - } - var resp *http.Response var shouldContinue bool var latestRespMsg string @@ -159,15 +173,19 @@ func (req *CopyRequest) copyBlobberObject( } return } - return nil, errors.New("unknown_issue", + return errors.New("unknown_issue", fmt.Sprintf("last status code: %d, last response message: %s", latestStatusCode, latestRespMsg)) } -func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, []error) { - var pos uint64 +func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { + var ( + pos uint64 + consensusRef *fileref.FileRef + ) numList := len(req.blobbers) objectTreeRefs := make([]fileref.RefEntity, numList) blobberErrors := make([]error, numList) + versionMap := make(map[int64]int) wg := &sync.WaitGroup{} for i := req.copyMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { @@ -175,17 +193,55 @@ func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, []error) { wg.Add(1) go func(blobberIdx int) { defer wg.Done() - refEntity, err := req.copyBlobberObject(req.blobbers[blobberIdx], blobberIdx) + // refEntity, err := req.copyBlobberObject(req.blobbers[blobberIdx], blobberIdx) + refEntity, err := req.getFileMetaFromBlobber(blobberIdx) if err != nil { blobberErrors[blobberIdx] = err l.Logger.Debug(err.Error()) return } objectTreeRefs[blobberIdx] = refEntity + req.maskMU.Lock() + versionMap[refEntity.AllocationVersion] += 1 + if versionMap[refEntity.AllocationVersion] >= req.consensusThresh { + consensusRef = refEntity + } + req.maskMU.Unlock() + }(int(pos)) + } + wg.Wait() + if consensusRef == nil { + return nil, zboxutil.MajorError(blobberErrors) + } + + if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { + for ind, refEntity := range objectTreeRefs { + if refEntity.GetAllocationVersion() != consensusRef.AllocationVersion { + req.copyMask = req.copyMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) + } + } + err := req.copySubDirectoriees() + if err != nil { + return nil, err + } + } + + for i := req.copyMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + wg.Add(1) + go func(blobberIdx int) { + defer wg.Done() + err := req.copyBlobberObject(req.blobbers[blobberIdx], blobberIdx) + if err != nil { + blobberErrors[blobberIdx] = err + l.Logger.Debug(err.Error()) + return + } }(int(pos)) } wg.Wait() - return objectTreeRefs, blobberErrors + + return objectTreeRefs, zboxutil.MajorError(blobberErrors) } func (req *CopyRequest) ProcessCopy() error { @@ -194,10 +250,9 @@ func (req *CopyRequest) ProcessCopy() error { wg := &sync.WaitGroup{} var pos uint64 - objectTreeRefs, blobberErrors := req.ProcessWithBlobbers() + objectTreeRefs, err := req.ProcessWithBlobbers() if !req.isConsensusOk() { - err := zboxutil.MajorError(blobberErrors) if err != nil { return errors.New("copy_failed", fmt.Sprintf("Copy failed. %s", err.Error())) } @@ -321,11 +376,10 @@ func (co *CopyOperation) Process(allocObj *Allocation, connectionID string) ([]f cR.consensusThresh = co.consensusThresh cR.fullconsensus = co.fullconsensus - objectTreeRefs, blobberErrors := cR.ProcessWithBlobbers() + objectTreeRefs, err := cR.ProcessWithBlobbers() if !cR.isConsensusOk() { l.Logger.Error("copy failed: ", cR.remotefilepath, cR.destPath) - err := zboxutil.MajorError(blobberErrors) if err != nil { return nil, cR.copyMask, errors.New("copy_failed", fmt.Sprintf("Copy failed. %s", err.Error())) } @@ -403,3 +457,88 @@ func NewCopyOperation(remotePath string, destPath string, copyMask zboxutil.Uint return co } + +func (req *CopyRequest) copySubDirectoriees() error { + var ( + offsetPath string + pathLevel int + ) + + for { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WithObjectConsensusThresh(req.consensusThresh), WithSingleBlobber(true)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + break + } + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.copyMask + if ref.Type == fileref.DIRECTORY { + continue + } + if ref.PathLevel > pathLevel { + pathLevel = ref.PathLevel + } + destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + op := OperationRequest{ + OperationType: constants.FileOperationCopy, + RemotePath: ref.Path, + DestPath: destPath, + Mask: &opMask, + } + ops = append(ops, op) + } + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err + } + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + if len(oResult.Refs) < getRefPageLimit { + break + } + } + + offsetPath = "" + level := len(strings.Split(strings.TrimSuffix(req.remotefilepath, "/"), "/")) + if pathLevel == 0 { + pathLevel = level + 1 + } + + for pathLevel > level { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.DIRECTORY, fileref.REGULAR, pathLevel, getRefPageLimit, WithObjectContext(req.ctx), WithObjectMask(req.copyMask), WithObjectConsensusThresh(req.consensusThresh), WithSingleBlobber(true)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + pathLevel-- + } else { + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.copyMask + if ref.Type == fileref.FILE { + continue + } + destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + op := OperationRequest{ + OperationType: constants.FileOperationCopy, + RemotePath: ref.Path, + DestPath: destPath, + Mask: &opMask, + } + ops = append(ops, op) + } + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err + } + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + if len(oResult.Refs) < getRefPageLimit { + pathLevel-- + } + } + } + + return nil +} diff --git a/zboxcore/sdk/copyworker_test.go b/zboxcore/sdk/copyworker_test.go index 007b4b837..374021805 100644 --- a/zboxcore/sdk/copyworker_test.go +++ b/zboxcore/sdk/copyworker_test.go @@ -216,7 +216,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { Baseurl: tt.name, }) req.copyMask = zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1) - _, err := req.copyBlobberObject(req.blobbers[0], 0) + err := req.copyBlobberObject(req.blobbers[0], 0) require.EqualValues(tt.wantErr, err != nil) if err != nil { require.Contains(errors.Top(err), tt.errMsg) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index b1a07026e..db3922422 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -402,6 +402,9 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( } if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { for ind, refEntity := range objectTreeRefs { + if refEntity == nil { + continue + } if refEntity.GetAllocationVersion() != consensusRef.AllocationVersion { deleteReq.deleteMask = deleteReq.deleteMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) } @@ -411,6 +414,9 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( return nil, deleteReq.deleteMask, err } } + if dop.remotefilepath == "/" { + return objectTreeRefs, deleteReq.deleteMask, nil + } pos = 0 deleteReq.consensus.Reset() for i := deleteReq.deleteMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { @@ -509,7 +515,7 @@ func (req *DeleteRequest) deleteSubDirectories() error { pathLevel int ) for { - oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WitObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WithObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) if err != nil { return err } @@ -549,7 +555,7 @@ func (req *DeleteRequest) deleteSubDirectories() error { } // list all directories by descending order of path level for pathLevel > level { - oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.DIRECTORY, fileref.REGULAR, pathLevel, getRefPageLimit, WithObjectContext(req.ctx), WitObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.DIRECTORY, fileref.REGULAR, pathLevel, getRefPageLimit, WithObjectContext(req.ctx), WithObjectMask(req.deleteMask), WithObjectConsensusThresh(req.consensus.consensusThresh), WithSingleBlobber(true)) if err != nil { return err } diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 6b2f5714d..10c9edad0 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -17,16 +17,14 @@ import ( "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/logger" l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/zboxutil" ) type ObjectTreeResult struct { - TotalPages int64 `json:"total_pages"` - OffsetPath string `json:"offset_path"` - OffsetDate string `json:"offset_date"` - Refs []ORef `json:"refs"` - LatestWM *marker.WriteMarker `json:"latest_write_marker"` + TotalPages int64 `json:"total_pages"` + OffsetPath string `json:"offset_path"` + OffsetDate string `json:"offset_date"` + Refs []ORef `json:"refs"` } const INVALID_PATH = "invalid_path" @@ -68,7 +66,7 @@ func WithObjectContext(ctx context.Context) ObjectTreeRequestOption { } } -func WitObjectMask(mask zboxutil.Uint128) ObjectTreeRequestOption { +func WithObjectMask(mask zboxutil.Uint128) ObjectTreeRequestOption { return func(o *ObjectTreeRequest) { o.reqMask = mask } @@ -97,7 +95,16 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { for i := 0; i < activeCount; i++ { var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) num := rnd.Intn(activeCount) - blob := o.blobbers[num] + var blob *blockchain.StorageNode + var pos uint64 + for i := o.reqMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + num-- + if num < 0 { + blob = o.blobbers[pos] + break + } + } l.Logger.Debug(fmt.Sprintf("Getting file refs for path %v from blobber %v", o.remotefilepath, blob.Baseurl)) idx := num baseURL := blob.Baseurl @@ -312,6 +319,7 @@ type SimilarField struct { PathLevel int `json:"level"` Size int64 `json:"size"` EncryptedKey string `json:"encrypted_key"` + EncryptedKeyPoint string `json:"encrypted_key_point"` ActualFileSize int64 `json:"actual_file_size"` ActualFileHash string `json:"actual_file_hash"` MimeType string `json:"mimetype"` diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 9e9e08dc8..dc9891ce8 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -47,8 +47,27 @@ func (req *MoveRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNode return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.remotefilepath, blobber) } +func (req *MoveRequest) getFileMetaFromBlobber(pos int) (fileRef *fileref.FileRef, err error) { + listReq := &ListRequest{ + allocationID: req.allocationID, + allocationTx: req.allocationTx, + blobbers: req.blobbers, + remotefilepath: req.remotefilepath, + ctx: req.ctx, + } + respChan := make(chan *fileMetaResponse) + go listReq.getFileMetaInfoFromBlobber(req.blobbers[pos], int(pos), respChan) + refRes := <-respChan + if refRes.err != nil { + err = refRes.err + return + } + fileRef = refRes.fileref + return +} + func (req *MoveRequest) moveBlobberObject( - blobber *blockchain.StorageNode, blobberIdx int) (refEntity fileref.RefEntity, err error) { + blobber *blockchain.StorageNode, blobberIdx int) (err error) { defer func() { if err != nil { @@ -58,10 +77,6 @@ func (req *MoveRequest) moveBlobberObject( req.maskMU.Unlock() } }() - refEntity, err = req.getObjectTreeFromBlobber(req.blobbers[blobberIdx]) - if err != nil { - return nil, err - } var resp *http.Response var shouldContinue bool @@ -156,32 +171,81 @@ func (req *MoveRequest) moveBlobberObject( } return } - return nil, errors.New("unknown_issue", + return errors.New("unknown_issue", fmt.Sprintf("last status code: %d, last response message: %s", latestStatusCode, latestRespMsg)) } -func (req *MoveRequest) ProcessWithBlobbers() ([]fileref.RefEntity, []error) { - var pos uint64 +func (req *MoveRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { + var ( + pos uint64 + consensusRef *fileref.FileRef + ) numList := len(req.blobbers) objectTreeRefs := make([]fileref.RefEntity, numList) blobberErrors := make([]error, numList) + versionMap := make(map[int64]int) wg := &sync.WaitGroup{} for i := req.moveMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) wg.Add(1) go func(blobberIdx int) { defer wg.Done() - refEntity, err := req.moveBlobberObject(req.blobbers[blobberIdx], blobberIdx) + refEntity, err := req.getFileMetaFromBlobber(blobberIdx) if err != nil { blobberErrors[blobberIdx] = err - l.Logger.Error(err.Error()) + l.Logger.Debug(err.Error()) return } objectTreeRefs[blobberIdx] = refEntity + req.maskMU.Lock() + versionMap[refEntity.AllocationVersion] += 1 + if versionMap[refEntity.AllocationVersion] >= req.consensusThresh { + consensusRef = refEntity + } + req.maskMU.Unlock() + }(int(pos)) + } + wg.Wait() + if consensusRef == nil { + return nil, zboxutil.MajorError(blobberErrors) + } + + if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { + for ind, refEntity := range objectTreeRefs { + if refEntity.GetAllocationVersion() != consensusRef.AllocationVersion { + req.moveMask = req.moveMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) + } + } + subRequest := &subDirRequest{ + allocationObj: req.allocationObj, + remotefilepath: req.remotefilepath, + destPath: req.destPath, + ctx: req.ctx, + consensusThresh: req.consensusThresh, + opType: constants.FileOperationMove, + mask: req.moveMask, + } + err := subRequest.processSubDirectories() + if err != nil { + return nil, err + } + } + + for i := req.moveMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + wg.Add(1) + go func(blobberIdx int) { + defer wg.Done() + err := req.moveBlobberObject(req.blobbers[blobberIdx], blobberIdx) + if err != nil { + blobberErrors[blobberIdx] = err + l.Logger.Debug(err.Error()) + return + } }(int(pos)) } wg.Wait() - return objectTreeRefs, blobberErrors + return objectTreeRefs, zboxutil.MajorError(blobberErrors) } func (req *MoveRequest) ProcessMove() error { @@ -190,10 +254,9 @@ func (req *MoveRequest) ProcessMove() error { wg := &sync.WaitGroup{} var pos uint64 - objectTreeRefs, blobberErrors := req.ProcessWithBlobbers() + objectTreeRefs, err := req.ProcessWithBlobbers() if !req.isConsensusOk() { - err := zboxutil.MajorError(blobberErrors) if err != nil { return errors.New("move_failed", fmt.Sprintf("Move failed. %s", err.Error())) } @@ -314,10 +377,9 @@ func (mo *MoveOperation) Process(allocObj *Allocation, connectionID string) ([]f mR.Consensus.fullconsensus = mo.consensus.fullconsensus mR.Consensus.consensusThresh = mo.consensus.consensusThresh - objectTreeRefs, blobberErrors := mR.ProcessWithBlobbers() + objectTreeRefs, err := mR.ProcessWithBlobbers() if !mR.Consensus.isConsensusOk() { - err := zboxutil.MajorError(blobberErrors) if err != nil { return nil, mR.moveMask, thrown.New("move_failed", fmt.Sprintf("Move failed. %s", err.Error())) } diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 0c18cefdc..fdbac3959 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -32,10 +32,12 @@ var BatchSize = 6 type MultiOperationOption func(mo *MultiOperation) -func WithRepair() MultiOperationOption { +func WithRepair(latestVersion int64, repairOffsetPath string) MultiOperationOption { return func(mo *MultiOperation) { mo.Consensus.consensusThresh = 0 mo.isRepair = true + mo.repairVersion = latestVersion + mo.repairOffset = repairOffsetPath } } @@ -56,8 +58,10 @@ type MultiOperation struct { operationMask zboxutil.Uint128 maskMU *sync.Mutex Consensus - changes [][]allocationchange.AllocationChange - isRepair bool + changes [][]allocationchange.AllocationChange + isRepair bool + repairVersion int64 + repairOffset string } func (mo *MultiOperation) createConnectionObj(blobberIdx int) (err error) { @@ -278,10 +282,12 @@ func (mo *MultiOperation) Process() error { logger.Logger.Debug("[checkAllocStatus]", time.Since(start).Milliseconds()) mo.Consensus.Reset() var pos uint64 - for i := mo.operationMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { - pos = uint64(i.TrailingZeros()) - if mo.allocationObj.Blobbers[pos].AllocationVersion != mo.allocationObj.allocationVersion { - mo.operationMask = mo.operationMask.And(zboxutil.NewUint128(1).Lsh(pos).Not()) + if !mo.isRepair { + for i := mo.operationMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + if mo.allocationObj.Blobbers[pos].AllocationVersion != mo.allocationObj.allocationVersion { + mo.operationMask = mo.operationMask.And(zboxutil.NewUint128(1).Lsh(pos).Not()) + } } } activeBlobbers := mo.operationMask.CountOnes() @@ -306,6 +312,12 @@ func (mo *MultiOperation) Process() error { blobberInd: pos, version: mo.allocationObj.Blobbers[pos].AllocationVersion + 1, } + if mo.isRepair { + commitReq.isRepair = true + commitReq.version = mo.allocationObj.Blobbers[pos].AllocationVersion + commitReq.repairVersion = mo.repairVersion + commitReq.repairOffset = mo.repairOffset + } commitReqs[counter] = commitReq l.Logger.Debug("Commit request sending to blobber ", commitReq.blobber.Baseurl) go AddCommitRequest(commitReq) diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index 491c6f08d..de494b983 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -47,8 +47,27 @@ func (req *RenameRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNo return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.remotefilepath, blobber) } +func (req *RenameRequest) getFileMetaFromBlobber(pos int) (fileRef *fileref.FileRef, err error) { + listReq := &ListRequest{ + allocationID: req.allocationID, + allocationTx: req.allocationTx, + blobbers: req.blobbers, + remotefilepath: req.remotefilepath, + ctx: req.ctx, + } + respChan := make(chan *fileMetaResponse) + go listReq.getFileMetaInfoFromBlobber(req.blobbers[pos], int(pos), respChan) + refRes := <-respChan + if refRes.err != nil { + err = refRes.err + return + } + fileRef = refRes.fileref + return +} + func (req *RenameRequest) renameBlobberObject( - blobber *blockchain.StorageNode, blobberIdx int) (refEntity fileref.RefEntity, err error) { + blobber *blockchain.StorageNode, blobberIdx int) (err error) { defer func() { if err != nil { @@ -58,11 +77,6 @@ func (req *RenameRequest) renameBlobberObject( } }() - refEntity, err = req.getObjectTreeFromBlobber(req.blobbers[blobberIdx]) - if err != nil { - return nil, err - } - var ( resp *http.Response shouldContinue bool @@ -159,37 +173,76 @@ func (req *RenameRequest) renameBlobberObject( return } -func (req *RenameRequest) ProcessWithBlobbers() ([]fileref.RefEntity, []error) { - var pos uint64 +func (req *RenameRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { + var ( + pos uint64 + consensusRef *fileref.FileRef + ) numList := len(req.blobbers) objectTreeRefs := make([]fileref.RefEntity, numList) blobberErrors := make([]error, numList) + versionMap := make(map[int64]int) req.wg = &sync.WaitGroup{} for i := req.renameMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) req.wg.Add(1) go func(blobberIdx int) { defer req.wg.Done() - refEntity, err := req.renameBlobberObject(req.blobbers[blobberIdx], blobberIdx) + refEntity, err := req.getFileMetaFromBlobber(blobberIdx) if err != nil { blobberErrors[blobberIdx] = err l.Logger.Error(err.Error()) return } objectTreeRefs[blobberIdx] = refEntity + req.maskMU.Lock() + versionMap[refEntity.AllocationVersion] += 1 + if versionMap[refEntity.AllocationVersion] >= req.consensus.consensusThresh { + consensusRef = refEntity + } + req.maskMU.Unlock() }(int(pos)) } req.wg.Wait() - return objectTreeRefs, blobberErrors + if consensusRef == nil { + return nil, zboxutil.MajorError(blobberErrors) + } + if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { + for ind, refEntity := range objectTreeRefs { + if refEntity.GetAllocationVersion() != consensusRef.AllocationVersion { + req.renameMask = req.renameMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) + } + } + // err := req.copySubDirectoriees() + // if err != nil { + // return nil, err + // } + } + + for i := req.renameMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + req.wg.Add(1) + go func(blobberIdx int) { + defer req.wg.Done() + err := req.renameBlobberObject(req.blobbers[blobberIdx], blobberIdx) + if err != nil { + blobberErrors[blobberIdx] = err + l.Logger.Debug(err.Error()) + return + } + }(int(pos)) + } + req.wg.Wait() + + return objectTreeRefs, zboxutil.MajorError(blobberErrors) } func (req *RenameRequest) ProcessRename() error { defer req.ctxCncl() - objectTreeRefs, blobberErrors := req.ProcessWithBlobbers() + objectTreeRefs, err := req.ProcessWithBlobbers() if !req.consensus.isConsensusOk() { - err := zboxutil.MajorError(blobberErrors) if err != nil { return errors.New("rename_failed", fmt.Sprintf("Rename failed. %s", err.Error())) @@ -324,10 +377,9 @@ func (ro *RenameOperation) Process(allocObj *Allocation, connectionID string) ([ rR.consensus.fullconsensus = ro.consensus.fullconsensus rR.consensus.consensusThresh = ro.consensus.consensusThresh - objectTreeRefs, blobberErrors := rR.ProcessWithBlobbers() + objectTreeRefs, err := rR.ProcessWithBlobbers() if !rR.consensus.isConsensusOk() { - err := zboxutil.MajorError(blobberErrors) if err != nil { return nil, rR.renameMask, errors.New("rename_failed", fmt.Sprintf("Renamed failed. %s", err.Error())) } diff --git a/zboxcore/sdk/renameworker_test.go b/zboxcore/sdk/renameworker_test.go index 29aa6304f..e43a66d83 100644 --- a/zboxcore/sdk/renameworker_test.go +++ b/zboxcore/sdk/renameworker_test.go @@ -244,7 +244,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { req.blobbers = append(req.blobbers, &blockchain.StorageNode{ Baseurl: tt.name, }) - _, err := req.renameBlobberObject(req.blobbers[0], 0) + err := req.renameBlobberObject(req.blobbers[0], 0) require.EqualValues(tt.wantErr, err != nil, "Error: ", err) if err != nil { require.Contains(errors.Top(err), tt.errMsg) diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index 84255e054..38f6fd94f 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -2,9 +2,10 @@ package sdk import ( "context" - "fmt" + "errors" "io" "sync" + "time" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/sys" @@ -23,6 +24,9 @@ type RepairRequest struct { filesRepaired int wg *sync.WaitGroup allocation *Allocation + repairPath string + versionMap map[int64]zboxutil.Uint128 + resMap map[int64]*getRes } type RepairStatusCB struct { @@ -32,6 +36,15 @@ type RepairStatusCB struct { statusCB StatusCallback } +type getRes struct { + oTR *ObjectTreeResult + err error + listCompleted bool + idx int + lastMatchedPath string + lastIndex int +} + func (cb *RepairStatusCB) Started(allocationId, filePath string, op int, totalBytes int) { cb.statusCB.Started(allocationId, filePath, op, totalBytes) } @@ -66,7 +79,11 @@ func (r *RepairRequest) processRepair(ctx context.Context, a *Allocation) { return } SetNumBlockDownloads(100) - r.iterateDir(a, r.listDir) + currentSize := MultiOpBatchSize + SetMultiOpBatchSize(multiOpRepairBatchSize) + defer SetMultiOpBatchSize(currentSize) + r.allocation = a + r.iterateDir(ctx) if r.statusCB != nil { r.statusCB.RepairCompleted(r.filesRepaired) @@ -85,197 +102,367 @@ type RepairSize struct { func (r *RepairRequest) Size(ctx context.Context, dir *ListResult) (RepairSize, error) { var rs RepairSize var err error - switch dir.Type { - case fileref.DIRECTORY: - if len(dir.Children) == 0 { - // fetch dir - dir, err = r.allocation.ListDir(dir.Path, WithListRequestForRepair(true), WithListRequestPageLimit(-1)) - if err != nil { - return rs, err - } + // switch dir.Type { + // case fileref.DIRECTORY: + // if len(dir.Children) == 0 { + // // fetch dir + // dir, err = r.allocation.ListDir(dir.Path, WithListRequestForRepair(true), WithListRequestPageLimit(-1)) + // if err != nil { + // return rs, err + // } + // } + // for _, subDir := range dir.Children { + // subDirSz, err := r.Size(ctx, subDir) + // if err != nil { + // return rs, err + // } + // rs.UploadSize += subDirSz.UploadSize + // rs.DownloadSize += subDirSz.DownloadSize + // } + // case fileref.FILE: + // // this returns repair operations required + // repairOps := r.repairFile(r.allocation, dir) + // if repairOps == nil { + // err = fmt.Errorf("fetch repairOps failed") + // return rs, err + // } + // for _, repairOp := range repairOps { + // if repairOp.OperationType == constants.FileOperationInsert { + // rs.UploadSize += uint64(repairOp.Mask.CountOnes()) * uint64(getShardSize(repairOp.FileMeta.ActualSize, r.allocation.DataShards, repairOp.EncryptedKey != "")) + // rs.DownloadSize += uint64(repairOp.FileMeta.ActualSize) + // } + // } + // } + return rs, err +} + +func (r *RepairRequest) iterateDir(ctx context.Context) { + r.versionMap = make(map[int64]zboxutil.Uint128) + latestVersion := r.allocation.allocationVersion + for idx, blobber := range r.allocation.Blobbers { + r.versionMap[blobber.AllocationVersion] = r.versionMap[blobber.AllocationVersion].Or(zboxutil.NewUint128(1).Lsh(uint64(idx))) + } + if r.versionMap[latestVersion].CountOnes() < r.allocation.DataShards { + l.Logger.Error("No consensus on latest allocation version: ", latestVersion) + if r.statusCB != nil { + r.statusCB.Error(r.allocation.ID, "/", OpRepair, errors.New("no consensus on latest allocation version")) } - for _, subDir := range dir.Children { - subDirSz, err := r.Size(ctx, subDir) - if err != nil { - return rs, err - } - rs.UploadSize += subDirSz.UploadSize - rs.DownloadSize += subDirSz.DownloadSize + return + } + if len(r.versionMap) == 1 { + return + } + + r.resMap = make(map[int64]*getRes) + err := r.repairObjects(ctx, latestVersion, fileref.FILE) + if err != nil { + return + } + l.Logger.Debug("repair file completed") + err = r.repairObjects(ctx, latestVersion, fileref.DIRECTORY) + if err != nil { + return + } + l.Logger.Debug("repair directory completed") + + r.allocation.CheckAllocStatus() //nolint:errcheck + if r.allocation.allocationVersion != latestVersion { + l.Logger.Error("Allocation version changed during repair operation") + if r.statusCB != nil { + r.statusCB.Error(r.allocation.ID, r.repairPath, OpRepair, errors.New("allocation version changed during repair operation")) } - case fileref.FILE: - // this returns repair operations required - repairOps := r.repairFile(r.allocation, dir) - if repairOps == nil { - err = fmt.Errorf("fetch repairOps failed") - return rs, err + return + } + wg := &sync.WaitGroup{} + commiReqs := make([]*CommitRequest, 0) + //send final commit to remaining blobbers + for version, mask := range r.versionMap { + if version == latestVersion { + continue } - for _, repairOp := range repairOps { - if repairOp.OperationType == constants.FileOperationInsert { - rs.UploadSize += uint64(repairOp.Mask.CountOnes()) * uint64(getShardSize(repairOp.FileMeta.ActualSize, r.allocation.DataShards, repairOp.EncryptedKey != "")) - rs.DownloadSize += uint64(repairOp.FileMeta.ActualSize) + currMask := mask + var pos uint64 + for i := currMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + wg.Add(1) + pos = uint64(i.TrailingZeros()) + commitReq := &CommitRequest{ + allocationID: r.allocation.ID, + allocationTx: r.allocation.Tx, + blobber: r.allocation.Blobbers[pos], + connectionID: zboxutil.NewConnectionId(), + wg: wg, + timestamp: time.Now().Unix(), + blobberInd: pos, + version: latestVersion, } + go AddCommitRequest(commitReq) + commiReqs = append(commiReqs, commitReq) + } + } + wg.Wait() + for _, commitReq := range commiReqs { + if commitReq.result != nil && !commitReq.result.Success { + l.Logger.Error("Failed to commit repair operation: ", commitReq.result.ErrorMessage) + if r.statusCB != nil { + r.statusCB.Error(r.allocation.ID, r.repairPath, OpRepair, errors.New(commitReq.result.ErrorMessage)) + } + return } } - return rs, err } -func (r *RepairRequest) iterateDir(a *Allocation, dir *ListResult) []OperationRequest { - ops := make([]OperationRequest, 0) - switch dir.Type { - case fileref.DIRECTORY: - if len(dir.Children) == 0 { - var err error - dir, err = a.ListDir(dir.Path, WithListRequestForRepair(true), WithListRequestPageLimit(-1)) - if err != nil { - l.Logger.Error("Failed to get listDir for path ", zap.Any("path", dir.Path), zap.Error(err)) - return nil +func (r *RepairRequest) uploadFileOp(file ORef, opMask zboxutil.Uint128) OperationRequest { + var wg sync.WaitGroup + wg.Add(1) + statusCB := &RepairStatusCB{ + wg: &wg, + statusCB: r.statusCB, + } + memFile := &sys.MemChanFile{ + Buffer: make(chan []byte, 100), + ChunkWriteSize: int(r.allocation.GetChunkReadSize(file.EncryptedKey != "")), + } + op := r.allocation.RepairFile(memFile, file.Path, statusCB, opMask, file) + if op.FileMeta.ActualSize > 0 { + op.DownloadFile = true + } + return *op +} + +func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, fileType string) error { + clear(r.resMap) + for { + r.getRefsWithVersion(ctx, fileType) + if r.resMap[latestVersion].err != nil { + l.Logger.Error("Failed to get refs for repair path: ", r.repairPath, r.resMap[latestVersion].err) + if r.statusCB != nil { + r.statusCB.Error(r.allocation.ID, r.repairPath, OpRepair, r.resMap[latestVersion].err) } + return r.resMap[latestVersion].err } - if len(dir.Children) == 0 { - if dir.deleteMask.CountOnes() > 0 { - l.Logger.Info("Deleting minority shards for the path :", zap.Any("path", dir.Path)) - consensus := dir.deleteMask.CountOnes() - if consensus < a.DataShards { + for version, res := range r.resMap { + if res.err != nil { + l.Logger.Error("Failed to get refs for repair path: ", r.repairPath, res.err) + delete(r.versionMap, version) + delete(r.resMap, version) + } + } + if len(r.versionMap) == 1 { + l.Logger.Error("all other versions failed to get refs for repair path: ", r.repairPath) + err := errors.New("all other versions failed to get refs for repair path") + if r.statusCB != nil { + r.statusCB.Error(r.allocation.ID, r.repairPath, OpRepair, err) + } + return err + } + ops := make([]OperationRequest, 0) + for idx, file := range r.resMap[latestVersion].oTR.Refs { + if r.checkForCancel(r.allocation) { + return errors.New("repair cancelled") + } - err := a.deleteFile(dir.Path, 0, consensus, dir.deleteMask) - if err != nil { - l.Logger.Error("repair_file_failed", zap.Error(err)) - if r.statusCB != nil { - r.statusCB.Error(a.ID, dir.Path, OpRepair, err) + for version, res := range r.resMap { + if version == latestVersion { + continue + } + + if file.Path <= res.lastMatchedPath { + continue + } + + if res.idx == len(res.oTR.Refs) { + if res.listCompleted { + // upload the file + opMask := r.versionMap[version] + if fileType == fileref.FILE { + op := r.uploadFileOp(file, opMask) + ops = append(ops, op) + } else { + op := OperationRequest{ + OperationType: constants.FileOperationCreateDir, + RemotePath: file.Path, + } + ops = append(ops, op) + } + res.lastMatchedPath = file.Path + res.lastIndex = idx + } + continue + } + + currentPath := res.oTR.Refs[res.idx].Path + if currentPath == file.Path { + if file.Type == fileref.FILE && file.ActualFileHash != res.oTR.Refs[res.idx].ActualFileHash { + // upload the file + opMask := r.versionMap[version] + op := r.uploadFileOp(file, opMask) + ops = append(ops, op) + } + res.lastMatchedPath = currentPath + res.idx++ + res.lastIndex = idx + } else if currentPath < file.Path { + for res.oTR.Refs[res.idx].Path < file.Path && res.idx < len(res.oTR.Refs) { + //delete the file + opMask := r.versionMap[version] + op := OperationRequest{ + OperationType: constants.FileOperationDelete, + RemotePath: res.oTR.Refs[res.idx].Path, + Mask: &opMask, } - return nil + res.idx++ + ops = append(ops, op) } - r.filesRepaired++ - } else if consensus < len(a.Blobbers) { - createMask := dir.deleteMask.Not().And(zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1)) - err := a.createDir(dir.Path, 0, createMask.CountOnes(), createMask) - if err != nil { - l.Logger.Error("repair_file_failed", zap.Error(err)) - if r.statusCB != nil { - r.statusCB.Error(a.ID, dir.Path, OpRepair, err) + if res.idx == len(res.oTR.Refs) { + res.lastIndex = idx + } else if res.oTR.Refs[res.idx].Path > file.Path { + opMask := r.versionMap[version] + // upload the file + if fileType == fileref.FILE { + op := r.uploadFileOp(file, opMask) + ops = append(ops, op) + } else { + op := OperationRequest{ + OperationType: constants.FileOperationCreateDir, + RemotePath: file.Path, + } + ops = append(ops, op) } - return nil } - r.filesRepaired++ + res.lastMatchedPath = file.Path + res.idx++ + res.lastIndex = idx + } else { + //TODO: take a union of mask so we don't have duplicate upload operations + // upload the file + opMask := r.versionMap[version] + if fileType == fileref.FILE { + op := r.uploadFileOp(file, opMask) + ops = append(ops, op) + } else { + op := OperationRequest{ + OperationType: constants.FileOperationCreateDir, + RemotePath: file.Path, + } + ops = append(ops, op) + } + res.lastMatchedPath = file.Path + res.lastIndex = idx } } } - for _, childDir := range dir.Children { - if r.checkForCancel(a) { - return nil + + if r.resMap[latestVersion].listCompleted { + for version, res := range r.resMap { + if version == latestVersion { + continue + } + for res.idx < len(res.oTR.Refs) { + //delete the file + l.Logger.Debug("Deleting file: ", res.oTR.Refs[res.idx].Path) + opMask := r.versionMap[version] + op := OperationRequest{ + OperationType: constants.FileOperationDelete, + RemotePath: res.oTR.Refs[res.idx].Path, + Mask: &opMask, + } + res.idx++ + ops = append(ops, op) + } } - ops = append(ops, r.iterateDir(a, childDir)...) - if len(ops) >= RepairBatchSize/2 { - r.repairOperation(a, ops) - ops = nil + } else { + minLastIndex := len(r.resMap[latestVersion].oTR.Refs) + for version, res := range r.resMap { + if version == latestVersion { + continue + } + if !res.listCompleted { + if res.lastIndex < minLastIndex { + minLastIndex = res.lastIndex + } + if res.idx < len(res.oTR.Refs) { + res.oTR.Refs = res.oTR.Refs[res.idx:] + } else { + res.oTR.Refs = nil + } + } + } + if minLastIndex < len(r.resMap[latestVersion].oTR.Refs) { + r.resMap[latestVersion].oTR.Refs = r.resMap[latestVersion].oTR.Refs[minLastIndex:] } } - if len(ops) > 0 { - r.repairOperation(a, ops) - ops = nil + + err := r.repairOperation(ops, latestVersion, r.resMap[latestVersion].oTR.OffsetPath) + if err != nil { + l.Logger.Error("Failed to repair files: ", err) + return err } - case fileref.FILE: - // this returns op object and mask - repairOps := r.repairFile(a, dir) - if repairOps != nil { - ops = append(ops, repairOps...) + if r.resMap[latestVersion].listCompleted { + break } - - default: - l.Logger.Info("Invalid directory type", zap.Any("type", dir.Type)) } - return ops + + return nil } -func (r *RepairRequest) repairFile(a *Allocation, file *ListResult) []OperationRequest { - ops := make([]OperationRequest, 0) - if r.checkForCancel(a) { - return nil - } - l.Logger.Info("Checking file for the path :", zap.Any("path", file.Path)) - found, deleteMask, repairRequired, ref, err := a.RepairRequired(file.Path) - if err != nil { - l.Logger.Error("repair_required_failed", zap.Error(err)) - return nil - } - if repairRequired { - l.Logger.Info("Repair required for the path :", zap.Any("path", file.Path)) - if found.CountOnes() >= a.DataShards { - l.Logger.Info("Repair by upload", zap.Any("path", file.Path)) - var wg sync.WaitGroup - statusCB := &RepairStatusCB{ - wg: &wg, - statusCB: r.statusCB, +func (r *RepairRequest) getRefsWithVersion(ctx context.Context, fileType string) { + mpLock := sync.Mutex{} + resWg := sync.WaitGroup{} + for version, mask := range r.versionMap { + resWg.Add(1) + currVersion := version + currMask := mask + go func(version int64, mask zboxutil.Uint128) { + defer resWg.Done() + var offsetPath string + mpLock.Lock() + if r.resMap[version] != nil { + offsetPath = r.resMap[version].oTR.OffsetPath } - - if deleteMask.CountOnes() > 0 { - l.Logger.Info("Deleting minority shards for the path :", zap.Any("path", file.Path)) - op := OperationRequest{ - OperationType: constants.FileOperationDelete, - RemotePath: file.Path, - Mask: &deleteMask, + mpLock.Unlock() + l.Logger.Debug("Getting refs for repair path: ", r.repairPath, " version: ", version, " mask: ", mask.CountOnes()) + res, err := r.allocation.GetRefs(r.repairPath, offsetPath, "", "", fileType, fileref.REGULAR, 0, getRefPageLimit, WithSingleBlobber(true), WithObjectMask(mask), WithObjectContext(ctx)) + if err != nil { + if code, _ := zboxutil.GetErrorMessageCode(err.Error()); code == INVALID_PATH { + err = nil + res = &ObjectTreeResult{Refs: make([]ORef, 0)} } - ops = append(ops, op) } - wg.Add(1) - localPath := r.getLocalPath(file) - var op *OperationRequest - if !checkFileExists(localPath) { - if r.checkForCancel(a) { - return nil - } - memFile := &sys.MemChanFile{ - Buffer: make(chan []byte, 100), - ChunkWriteSize: int(a.GetChunkReadSize(ref.EncryptedKey != "")), - } - op = a.RepairFile(memFile, file.Path, statusCB, found, ref) - if op.FileMeta.ActualSize > 0 { - op.DownloadFile = true + mpLock.Lock() + currRes := r.resMap[version] + if currRes != nil { + if res != nil { + currRes.oTR.Refs = append(currRes.oTR.Refs, res.Refs...) + if len(res.Refs) < getRefPageLimit { + currRes.listCompleted = true + } } + currRes.idx = 0 + currRes.lastIndex = 0 } else { - f, err := sys.Files.Open(localPath) - if err != nil { - l.Logger.Error("repair_file_failed", zap.Error(err)) - return nil + getResult := &getRes{oTR: res, err: err} + if res != nil && len(res.Refs) < getRefPageLimit { + getResult.listCompleted = true } - op = a.RepairFile(f, file.Path, statusCB, found, ref) - } - ops = append(ops, *op) - if r.checkForCancel(a) { - return nil - } - } else { - l.Logger.Info("Repair by delete", zap.Any("path", file.Path)) - op := OperationRequest{ - OperationType: constants.FileOperationDelete, - RemotePath: file.Path, - Mask: &found, + r.resMap[version] = getResult } - ops = append(ops, op) - } - } else if deleteMask.CountOnes() > 0 { - l.Logger.Info("Deleting minority shards for the path :", zap.Any("path", file.Path)) - op := OperationRequest{ - OperationType: constants.FileOperationDelete, - RemotePath: file.Path, - Mask: &deleteMask, - } - ops = append(ops, op) + mpLock.Unlock() + }(currVersion, currMask) } - return ops + resWg.Wait() } -func (r *RepairRequest) repairOperation(a *Allocation, ops []OperationRequest) { - err := a.DoMultiOperation(ops, WithRepair()) +func (r *RepairRequest) repairOperation(ops []OperationRequest, latestVersion int64, repairOffsetPath string) error { + err := r.allocation.DoMultiOperation(ops, WithRepair(latestVersion, repairOffsetPath)) if err != nil { l.Logger.Error("repair_file_failed", zap.Error(err)) status := r.statusCB != nil for _, op := range ops { if op.DownloadFile { - _ = a.CancelDownload(op.RemotePath) + _ = r.allocation.CancelDownload(op.RemotePath) } if status { - r.statusCB.Error(a.ID, op.RemotePath, OpRepair, err) + r.statusCB.Error(r.allocation.ID, op.RemotePath, OpRepair, err) } } } else { @@ -288,21 +475,7 @@ func (r *RepairRequest) repairOperation(a *Allocation, ops []OperationRequest) { } } } -} - -func (r *RepairRequest) getLocalPath(file *ListResult) string { - return r.localRootPath + file.Path -} - -func checkFileExists(localPath string) bool { - if IsWasm { - return false - } - info, err := sys.Files.Stat(localPath) - if err != nil { - return false - } - return !info.IsDir() + return err } func (r *RepairRequest) checkForCancel(a *Allocation) bool { @@ -315,6 +488,3 @@ func (r *RepairRequest) checkForCancel(a *Allocation) bool { } return false } - -//repair for enterprise workflow -// list all files in the allocation recursively and repair them From d15f3ce27ff33cc4fb5c9ad96bf9655fe43a7a99 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Wed, 7 Aug 2024 13:07:31 +0530 Subject: [PATCH 024/107] add delete for dir remotepath in move --- zboxcore/sdk/common.go | 2 ++ zboxcore/sdk/copyworker.go | 6 ++++++ zboxcore/sdk/deleteworker.go | 4 ++-- zboxcore/sdk/moveworker.go | 18 +++++++++++++++--- zboxcore/sdk/multi_operation_worker.go | 2 +- zboxcore/sdk/renameworker.go | 6 ++++++ 6 files changed, 32 insertions(+), 6 deletions(-) diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 6f5a6fd8a..f866c58ee 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -20,6 +20,8 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" ) +const alreadyExists = "file already exists" + func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx string, remoteFilePath string, blobber *blockchain.StorageNode) (fileref.RefEntity, error) { httpreq, err := zboxutil.NewObjectTreeRequest(blobber.Baseurl, allocationID, allocationTx, remoteFilePath) if err != nil { diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 98678545d..501b10818 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -147,6 +147,10 @@ func (req *CopyRequest) copyBlobberObject( latestRespMsg = string(respBody) latestStatusCode = resp.StatusCode + if strings.Contains(latestRespMsg, alreadyExists) { + req.Consensus.Done() + return + } if resp.StatusCode == http.StatusTooManyRequests { logger.Logger.Error("Got too many request error") @@ -224,6 +228,8 @@ func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { if err != nil { return nil, err } + req.consensus = req.copyMask.CountOnes() + return objectTreeRefs, nil } for i := req.copyMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index db3922422..264c3576e 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -43,7 +43,7 @@ type DeleteRequest struct { timestamp int64 } -var ErrFileDeleted = errors.New("file_deleted", "file is already deleted") +var errFileDeleted = errors.New("file_deleted", "file is already deleted") func (req *DeleteRequest) deleteBlobberFile( blobber *blockchain.StorageNode, blobberIdx int) error { @@ -398,7 +398,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( } if consensusRef == nil { //Already deleted - return nil, dop.deleteMask, ErrFileDeleted + return nil, dop.deleteMask, errFileDeleted } if consensusRef.Type == fileref.DIRECTORY && !consensusRef.IsEmpty { for ind, refEntity := range objectTreeRefs { diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index dc9891ce8..27f10fbc4 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -43,9 +43,7 @@ type MoveRequest struct { Consensus } -func (req *MoveRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNode) (fileref.RefEntity, error) { - return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.remotefilepath, blobber) -} +var errNoChange = errors.New("no_change", "No change in the operation") func (req *MoveRequest) getFileMetaFromBlobber(pos int) (fileRef *fileref.FileRef, err error) { listReq := &ListRequest{ @@ -146,6 +144,11 @@ func (req *MoveRequest) moveBlobberObject( latestRespMsg = string(respBody) latestStatusCode = resp.StatusCode + if strings.Contains(latestRespMsg, alreadyExists) { + req.Consensus.Done() + return + } + if resp.StatusCode == http.StatusTooManyRequests { logger.Logger.Error("Got too many request error") var r int @@ -229,6 +232,15 @@ func (req *MoveRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { if err != nil { return nil, err } + op := OperationRequest{ + OperationType: constants.FileOperationDelete, + RemotePath: req.remotefilepath, + } + err = req.allocationObj.DoMultiOperation([]OperationRequest{op}) + if err != nil { + return nil, err + } + return nil, errNoChange } for i := req.moveMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index fdbac3959..ad057af47 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -185,7 +185,7 @@ func (mo *MultiOperation) Process() error { _, mask, err := op.Process(mo.allocationObj, mo.connectionID) // Process with each blobber if err != nil { - if err != ErrFileDeleted { + if err != errFileDeleted || err != errNoChange { l.Logger.Error(err) errsSlice[idx] = errors.New("", err.Error()) ctxCncl(err) diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index de494b983..235297476 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -8,6 +8,7 @@ import ( "mime/multipart" "net/http" "path/filepath" + "strings" "sync" "time" @@ -142,6 +143,11 @@ func (req *RenameRequest) renameBlobberObject( return } + if strings.Contains(latestRespMsg, alreadyExists) { + req.consensus.Done() + return + } + if resp.StatusCode == http.StatusTooManyRequests { logger.Logger.Error("Got too many request error") var r int From f2bb064791d0a3504fcb061cd9b4f35dbaf28daa Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Wed, 7 Aug 2024 13:09:30 +0530 Subject: [PATCH 025/107] fix no change check --- zboxcore/sdk/multi_operation_worker.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index ad057af47..950616124 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -185,7 +185,7 @@ func (mo *MultiOperation) Process() error { _, mask, err := op.Process(mo.allocationObj, mo.connectionID) // Process with each blobber if err != nil { - if err != errFileDeleted || err != errNoChange { + if err != errFileDeleted && err != errNoChange { l.Logger.Error(err) errsSlice[idx] = errors.New("", err.Error()) ctxCncl(err) From b0e385f040e841a8621188f813b896aced7eed48 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Wed, 7 Aug 2024 20:22:26 +0530 Subject: [PATCH 026/107] fix consensus and add check for no change err --- zboxcore/sdk/moveworker.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 27f10fbc4..2a4f5b381 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -240,6 +240,7 @@ func (req *MoveRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { if err != nil { return nil, err } + req.consensus = req.moveMask.CountOnes() return nil, errNoChange } @@ -393,6 +394,9 @@ func (mo *MoveOperation) Process(allocObj *Allocation, connectionID string) ([]f if !mR.Consensus.isConsensusOk() { if err != nil { + if err == errNoChange { + return nil, mR.moveMask, err + } return nil, mR.moveMask, thrown.New("move_failed", fmt.Sprintf("Move failed. %s", err.Error())) } From a2081f3159c1c1b36aaacf72d299685f6027bb00 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Wed, 7 Aug 2024 21:39:16 +0530 Subject: [PATCH 027/107] fix list completed repair --- zboxcore/sdk/allocation.go | 1 + zboxcore/sdk/repairworker.go | 48 +++++++++++++++++++++++++++--------- 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 9f06ed3b9..565c84d9b 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -420,6 +420,7 @@ func (a *Allocation) RepairFile(file sys.File, remotepath string, statusCallback MimeType: ref.MimeType, RemoteName: ref.Name, RemotePath: remotepath, + CustomMeta: ref.CustomMeta, } var opts []ChunkedUploadOption if ref.EncryptedKey != "" { diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index 38f6fd94f..b42d7cc20 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -302,7 +302,7 @@ func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, res.idx++ res.lastIndex = idx } else if currentPath < file.Path { - for res.oTR.Refs[res.idx].Path < file.Path && res.idx < len(res.oTR.Refs) { + for res.idx < len(res.oTR.Refs) && res.oTR.Refs[res.idx].Path < file.Path { //delete the file opMask := r.versionMap[version] op := OperationRequest{ @@ -313,9 +313,7 @@ func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, res.idx++ ops = append(ops, op) } - if res.idx == len(res.oTR.Refs) { - res.lastIndex = idx - } else if res.oTR.Refs[res.idx].Path > file.Path { + if res.idx < len(res.oTR.Refs) && res.oTR.Refs[res.idx].Path > file.Path { opMask := r.versionMap[version] // upload the file if fileType == fileref.FILE { @@ -328,10 +326,10 @@ func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, } ops = append(ops, op) } + res.lastMatchedPath = file.Path + res.idx++ + res.lastIndex = idx } - res.lastMatchedPath = file.Path - res.idx++ - res.lastIndex = idx } else { //TODO: take a union of mask so we don't have duplicate upload operations // upload the file @@ -369,6 +367,23 @@ func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, res.idx++ ops = append(ops, op) } + if res.listCompleted { + for i := res.lastIndex + 1; i < len(r.resMap[latestVersion].oTR.Refs); i++ { + // upload the file + l.Logger.Debug("Uploading file: ", r.resMap[latestVersion].oTR.Refs[i].Path) + opMask := r.versionMap[version] + if fileType == fileref.FILE { + op := r.uploadFileOp(r.resMap[latestVersion].oTR.Refs[i], opMask) + ops = append(ops, op) + } else { + op := OperationRequest{ + OperationType: constants.FileOperationCreateDir, + RemotePath: r.resMap[latestVersion].oTR.Refs[i].Path, + } + ops = append(ops, op) + } + } + } } } else { minLastIndex := len(r.resMap[latestVersion].oTR.Refs) @@ -387,8 +402,10 @@ func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, } } } - if minLastIndex < len(r.resMap[latestVersion].oTR.Refs) { - r.resMap[latestVersion].oTR.Refs = r.resMap[latestVersion].oTR.Refs[minLastIndex:] + if minLastIndex+1 < len(r.resMap[latestVersion].oTR.Refs) { + r.resMap[latestVersion].oTR.Refs = r.resMap[latestVersion].oTR.Refs[minLastIndex+1:] + } else { + r.resMap[latestVersion].oTR.Refs = nil } } @@ -397,7 +414,14 @@ func (r *RepairRequest) repairObjects(ctx context.Context, latestVersion int64, l.Logger.Error("Failed to repair files: ", err) return err } - if r.resMap[latestVersion].listCompleted { + + completedLists := 0 + for _, res := range r.resMap { + if res.listCompleted { + completedLists++ + } + } + if completedLists == len(r.versionMap) { break } } @@ -438,9 +462,9 @@ func (r *RepairRequest) getRefsWithVersion(ctx context.Context, fileType string) } } currRes.idx = 0 - currRes.lastIndex = 0 + currRes.lastIndex = -1 } else { - getResult := &getRes{oTR: res, err: err} + getResult := &getRes{oTR: res, err: err, lastIndex: -1} if res != nil && len(res.Refs) < getRefPageLimit { getResult.listCompleted = true } From af515bab6d679e6ca0d84652c0a41cd56aa59964 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Thu, 8 Aug 2024 13:04:03 +0530 Subject: [PATCH 028/107] use dir as destpath --- zboxcore/sdk/common.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index f866c58ee..ecff5f256 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "net/http" "path" + "path/filepath" "strconv" "strings" "sync" @@ -157,7 +158,7 @@ func (req *subDirRequest) processSubDirectories() error { if ref.PathLevel > pathLevel { pathLevel = ref.PathLevel } - destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + destPath := filepath.Dir(strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1)) op := OperationRequest{ OperationType: req.opType, RemotePath: ref.Path, From e973828a833015eace5297b7fd7b5b9572346871 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Thu, 8 Aug 2024 15:31:46 +0530 Subject: [PATCH 029/107] base of dest name --- zboxcore/sdk/renameworker.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index 235297476..328e62445 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -457,7 +457,7 @@ func (ro *RenameOperation) Error(allocObj *Allocation, consensus int, err error) func NewRenameOperation(remotePath string, destName string, renameMask zboxutil.Uint128, maskMU *sync.Mutex, consensusTh int, fullConsensus int, ctx context.Context) *RenameOperation { ro := &RenameOperation{} ro.remotefilepath = zboxutil.RemoteClean(remotePath) - ro.newName = destName + ro.newName = filepath.Base(destName) ro.renameMask = renameMask ro.maskMU = maskMU ro.consensus.consensusThresh = consensusTh From f4ba999e2c83c9ea80c8a8c54bc1632a01555964 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Thu, 8 Aug 2024 20:56:10 +0530 Subject: [PATCH 030/107] fix copy op --- zboxcore/sdk/allocation.go | 3 +- zboxcore/sdk/common.go | 2 +- zboxcore/sdk/copyworker.go | 85 +++++++++++++++++++++----------------- 3 files changed, 50 insertions(+), 40 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 565c84d9b..ad5c312c1 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -243,6 +243,7 @@ type OperationRequest struct { StreamUpload bool // Required for streaming file when actualSize is not available CancelCauseFunc context.CancelCauseFunc Opts []ChunkedUploadOption + CopyDirOnly bool } func GetReadPriceRange() (PriceRange, error) { @@ -925,7 +926,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest, opts ...Mul operation = NewRenameOperation(op.RemotePath, op.DestName, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) case constants.FileOperationCopy: - operation = NewCopyOperation(op.RemotePath, op.DestPath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) + operation = NewCopyOperation(op.RemotePath, op.DestPath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, op.CopyDirOnly, mo.ctx) case constants.FileOperationMove: operation = NewMoveOperation(op.RemotePath, op.DestPath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index ecff5f256..ff14c4f3d 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -197,7 +197,7 @@ func (req *subDirRequest) processSubDirectories() error { if ref.Type == fileref.FILE { continue } - destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + destPath := filepath.Dir(strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1)) op := OperationRequest{ OperationType: req.opType, RemotePath: ref.Path, diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 501b10818..0e34d45ea 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "mime/multipart" "net/http" + "path/filepath" "strings" "sync" "time" @@ -34,6 +35,7 @@ type CopyRequest struct { blobbers []*blockchain.StorageNode remotefilepath string destPath string + dirOnly bool ctx context.Context ctxCncl context.CancelFunc copyMask zboxutil.Uint128 @@ -147,10 +149,6 @@ func (req *CopyRequest) copyBlobberObject( latestRespMsg = string(respBody) latestStatusCode = resp.StatusCode - if strings.Contains(latestRespMsg, alreadyExists) { - req.Consensus.Done() - return - } if resp.StatusCode == http.StatusTooManyRequests { logger.Logger.Error("Got too many request error") @@ -224,7 +222,7 @@ func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { req.copyMask = req.copyMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) } } - err := req.copySubDirectoriees() + err := req.copySubDirectoriees(req.dirOnly) if err != nil { return nil, err } @@ -355,6 +353,7 @@ func (req *CopyRequest) ProcessCopy() error { type CopyOperation struct { remotefilepath string destPath string + dirOnly bool ctx context.Context ctxCncl context.CancelFunc copyMask zboxutil.Uint128 @@ -364,6 +363,9 @@ type CopyOperation struct { } func (co *CopyOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { + if co.remotefilepath == "/" { + return nil, co.copyMask, errors.New("invalid_path", "Invalid path for copy cannot copy root directory") + } // make copyRequest object cR := &CopyRequest{ allocationObj: allocObj, @@ -378,6 +380,7 @@ func (co *CopyOperation) Process(allocObj *Allocation, connectionID string) ([]f copyMask: co.copyMask, maskMU: co.maskMU, Consensus: Consensus{RWMutex: &sync.RWMutex{}}, + dirOnly: co.dirOnly, } cR.consensusThresh = co.consensusThresh cR.fullconsensus = co.fullconsensus @@ -385,8 +388,11 @@ func (co *CopyOperation) Process(allocObj *Allocation, connectionID string) ([]f objectTreeRefs, err := cR.ProcessWithBlobbers() if !cR.isConsensusOk() { - l.Logger.Error("copy failed: ", cR.remotefilepath, cR.destPath) if err != nil { + if strings.Contains(err.Error(), alreadyExists) { + return objectTreeRefs, cR.copyMask, errNoChange + } + l.Logger.Error("copy failed: ", cR.remotefilepath, cR.destPath) return nil, cR.copyMask, errors.New("copy_failed", fmt.Sprintf("Copy failed. %s", err.Error())) } @@ -448,7 +454,7 @@ func (co *CopyOperation) Error(allocObj *Allocation, consensus int, err error) { } -func NewCopyOperation(remotePath string, destPath string, copyMask zboxutil.Uint128, maskMU *sync.Mutex, consensusTh int, fullConsensus int, ctx context.Context) *CopyOperation { +func NewCopyOperation(remotePath string, destPath string, copyMask zboxutil.Uint128, maskMU *sync.Mutex, consensusTh int, fullConsensus int, copyDirOnly bool, ctx context.Context) *CopyOperation { co := &CopyOperation{} co.remotefilepath = zboxutil.RemoteClean(remotePath) co.copyMask = copyMask @@ -464,45 +470,47 @@ func NewCopyOperation(remotePath string, destPath string, copyMask zboxutil.Uint } -func (req *CopyRequest) copySubDirectoriees() error { +func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { var ( offsetPath string pathLevel int ) for { - oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WithObjectConsensusThresh(req.consensusThresh), WithSingleBlobber(true)) - if err != nil { - return err - } - if len(oResult.Refs) == 0 { - break - } - ops := make([]OperationRequest, 0, len(oResult.Refs)) - for _, ref := range oResult.Refs { - opMask := req.copyMask - if ref.Type == fileref.DIRECTORY { - continue + if !dirOnly { + oResult, err := req.allocationObj.GetRefs(req.remotefilepath, offsetPath, "", "", fileref.FILE, fileref.REGULAR, 0, getRefPageLimit, WithObjectContext(req.ctx), WithObjectConsensusThresh(req.consensusThresh), WithSingleBlobber(true)) + if err != nil { + return err + } + if len(oResult.Refs) == 0 { + break + } + ops := make([]OperationRequest, 0, len(oResult.Refs)) + for _, ref := range oResult.Refs { + opMask := req.copyMask + if ref.Type == fileref.DIRECTORY { + continue + } + if ref.PathLevel > pathLevel { + pathLevel = ref.PathLevel + } + destPath := filepath.Dir(strings.Replace(ref.Path, filepath.Dir(req.remotefilepath), req.destPath, 1)) + op := OperationRequest{ + OperationType: constants.FileOperationCopy, + RemotePath: ref.Path, + DestPath: destPath, + Mask: &opMask, + } + ops = append(ops, op) } - if ref.PathLevel > pathLevel { - pathLevel = ref.PathLevel + err = req.allocationObj.DoMultiOperation(ops) + if err != nil { + return err } - destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) - op := OperationRequest{ - OperationType: constants.FileOperationCopy, - RemotePath: ref.Path, - DestPath: destPath, - Mask: &opMask, + offsetPath = oResult.Refs[len(oResult.Refs)-1].Path + if len(oResult.Refs) < getRefPageLimit { + break } - ops = append(ops, op) - } - err = req.allocationObj.DoMultiOperation(ops) - if err != nil { - return err - } - offsetPath = oResult.Refs[len(oResult.Refs)-1].Path - if len(oResult.Refs) < getRefPageLimit { - break } } @@ -526,12 +534,13 @@ func (req *CopyRequest) copySubDirectoriees() error { if ref.Type == fileref.FILE { continue } - destPath := strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1) + destPath := filepath.Dir(strings.Replace(ref.Path, filepath.Dir(req.remotefilepath), req.destPath, 1)) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, DestPath: destPath, Mask: &opMask, + CopyDirOnly: true, } ops = append(ops, op) } From 94ef0df2e7866c4a73a2aba548840e97539df268 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Thu, 8 Aug 2024 23:57:37 +0530 Subject: [PATCH 031/107] check copy destpath --- zboxcore/sdk/copyworker.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 0e34d45ea..7957b5289 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -45,6 +45,8 @@ type CopyRequest struct { Consensus } +const objAlreadyExists = "Object Already exists" + func (req *CopyRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNode) (fileref.RefEntity, error) { return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.remotefilepath, blobber) } @@ -244,8 +246,12 @@ func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { }(int(pos)) } wg.Wait() + err := zboxutil.MajorError(blobberErrors) + if err != nil && strings.Contains(err.Error(), objAlreadyExists) && consensusRef.Type == fileref.DIRECTORY { + return nil, errNoChange + } - return objectTreeRefs, zboxutil.MajorError(blobberErrors) + return objectTreeRefs, err } func (req *CopyRequest) ProcessCopy() error { @@ -389,8 +395,8 @@ func (co *CopyOperation) Process(allocObj *Allocation, connectionID string) ([]f if !cR.isConsensusOk() { if err != nil { - if strings.Contains(err.Error(), alreadyExists) { - return objectTreeRefs, cR.copyMask, errNoChange + if err == errNoChange { + return nil, cR.copyMask, err } l.Logger.Error("copy failed: ", cR.remotefilepath, cR.destPath) return nil, cR.copyMask, errors.New("copy_failed", fmt.Sprintf("Copy failed. %s", err.Error())) @@ -494,7 +500,7 @@ func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { if ref.PathLevel > pathLevel { pathLevel = ref.PathLevel } - destPath := filepath.Dir(strings.Replace(ref.Path, filepath.Dir(req.remotefilepath), req.destPath, 1)) + destPath := strings.Replace(filepath.Dir(ref.Path), req.remotefilepath, req.destPath, 1) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, @@ -534,7 +540,7 @@ func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { if ref.Type == fileref.FILE { continue } - destPath := filepath.Dir(strings.Replace(ref.Path, filepath.Dir(req.remotefilepath), req.destPath, 1)) + destPath := strings.Replace(filepath.Dir(ref.Path), req.remotefilepath, req.destPath, 1) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, From dbbc11b22bbb0d17698bf9686ba011b06e824181 Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Fri, 9 Aug 2024 02:18:54 +0530 Subject: [PATCH 032/107] join base and dest path --- zboxcore/sdk/copyworker.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 7957b5289..bc158a15d 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -500,7 +500,8 @@ func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { if ref.PathLevel > pathLevel { pathLevel = ref.PathLevel } - destPath := strings.Replace(filepath.Dir(ref.Path), req.remotefilepath, req.destPath, 1) + basePath := strings.TrimPrefix(filepath.Dir(ref.Path), filepath.Dir(req.remotefilepath)) + destPath := filepath.Join(req.destPath, basePath) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, @@ -540,7 +541,8 @@ func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { if ref.Type == fileref.FILE { continue } - destPath := strings.Replace(filepath.Dir(ref.Path), req.remotefilepath, req.destPath, 1) + basePath := strings.TrimPrefix(filepath.Dir(ref.Path), filepath.Dir(req.remotefilepath)) + destPath := filepath.Join(req.destPath, basePath) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, From 8390f11c37f49f424b2f63cd3b123a851ebb969f Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Fri, 9 Aug 2024 14:13:24 +0530 Subject: [PATCH 033/107] set path hash --- zboxcore/sdk/filestatsworker.go | 1 + 1 file changed, 1 insertion(+) diff --git a/zboxcore/sdk/filestatsworker.go b/zboxcore/sdk/filestatsworker.go index b7b846515..a6e2805bf 100644 --- a/zboxcore/sdk/filestatsworker.go +++ b/zboxcore/sdk/filestatsworker.go @@ -98,6 +98,7 @@ func (req *ListRequest) getFileStatsInfoFromBlobber(blobber *blockchain.StorageN } else { fileStats.BlockchainAware = false } + fileStats.PathHash = req.remotefilepathhash fileStats.BlobberID = blobber.ID fileStats.BlobberURL = blobber.Baseurl return nil From c552f971c1067481f0e662a40f812b8006a6dfa9 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sun, 11 Aug 2024 02:26:16 +0530 Subject: [PATCH 034/107] add size for root dir --- zboxcore/sdk/listworker.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index 611ad635b..18911e6f0 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -249,6 +249,9 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { } result.Size += ti.ref.Size result.NumBlocks += ti.ref.NumBlocks + if ti.ref.Path == "/" { + result.ActualSize = ti.ref.Size * int64(req.consensusThresh) + } if len(lR[i].ref.Children) > 0 { result.populateChildren(lR[i].ref.Children, childResultMap, selected, req) From 645ded9642b289b4d6de71e2395111116490ac0f Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Tue, 13 Aug 2024 11:24:15 +0530 Subject: [PATCH 035/107] check vm --- zboxcore/sdk/rollback.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 7295ed51c..81cbc505c 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -255,7 +255,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { l.Logger.Error("error during getWritemarker", zap.Error(err)) blobStatus.Status = "unavailable" } - if lvm == nil { + if lvm == nil || lvm.VersionMarker == nil { markerChan <- nil } else { markerChan <- &RollbackBlobber{ From 007b98227f14c40620847fd938c7105f46f040cd Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 14 Aug 2024 19:01:39 +0530 Subject: [PATCH 036/107] move upload success to debug --- zboxcore/sdk/upload_worker.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index 76021f904..582580af0 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -59,7 +59,7 @@ func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([ fileref.DeleteFileRef(cacheKey) } } - l.Logger.Info("UploadOperation Success", zap.String("name", uo.chunkedUpload.fileMeta.RemoteName)) + l.Logger.Debug("UploadOperation Success", zap.String("name", uo.chunkedUpload.fileMeta.RemoteName)) return nil, uo.chunkedUpload.uploadMask, nil } From 2119c4affdfae5009a42b858bf20153040fb564b Mon Sep 17 00:00:00 2001 From: hitenjain14 Date: Thu, 22 Aug 2024 19:32:00 +0530 Subject: [PATCH 037/107] fix nested move and rename --- zboxcore/sdk/common.go | 7 ++++--- zboxcore/sdk/copyworker.go | 14 +++++++------- zboxcore/sdk/moveworker.go | 2 +- zboxcore/sdk/renameworker.go | 23 +++++++++++++++++------ 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index ff14c4f3d..90de2635e 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -7,7 +7,6 @@ import ( "io/ioutil" "net/http" "path" - "path/filepath" "strconv" "strings" "sync" @@ -158,7 +157,8 @@ func (req *subDirRequest) processSubDirectories() error { if ref.PathLevel > pathLevel { pathLevel = ref.PathLevel } - destPath := filepath.Dir(strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1)) + basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) + destPath := path.Join(req.destPath, basePath) op := OperationRequest{ OperationType: req.opType, RemotePath: ref.Path, @@ -197,7 +197,8 @@ func (req *subDirRequest) processSubDirectories() error { if ref.Type == fileref.FILE { continue } - destPath := filepath.Dir(strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1)) + basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) + destPath := path.Join(req.destPath, basePath) op := OperationRequest{ OperationType: req.opType, RemotePath: ref.Path, diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index bc158a15d..0fdeaed7a 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "mime/multipart" "net/http" - "path/filepath" + "path" "strings" "sync" "time" @@ -229,7 +229,7 @@ func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { return nil, err } req.consensus = req.copyMask.CountOnes() - return objectTreeRefs, nil + return objectTreeRefs, errNoChange } for i := req.copyMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { @@ -406,7 +406,7 @@ func (co *CopyOperation) Process(allocObj *Allocation, connectionID string) ([]f fmt.Sprintf("Copy failed. Required consensus %d, got %d", cR.Consensus.consensusThresh, cR.Consensus.consensus)) } - return objectTreeRefs, cR.copyMask, nil + return objectTreeRefs, cR.copyMask, err } @@ -500,8 +500,8 @@ func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { if ref.PathLevel > pathLevel { pathLevel = ref.PathLevel } - basePath := strings.TrimPrefix(filepath.Dir(ref.Path), filepath.Dir(req.remotefilepath)) - destPath := filepath.Join(req.destPath, basePath) + basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) + destPath := path.Join(req.destPath, basePath) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, @@ -541,8 +541,8 @@ func (req *CopyRequest) copySubDirectoriees(dirOnly bool) error { if ref.Type == fileref.FILE { continue } - basePath := strings.TrimPrefix(filepath.Dir(ref.Path), filepath.Dir(req.remotefilepath)) - destPath := filepath.Join(req.destPath, basePath) + basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) + destPath := path.Join(req.destPath, basePath) op := OperationRequest{ OperationType: constants.FileOperationCopy, RemotePath: ref.Path, diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 2a4f5b381..19d3837ae 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -404,7 +404,7 @@ func (mo *MoveOperation) Process(allocObj *Allocation, connectionID string) ([]f fmt.Sprintf("Move failed. Required consensus %d, got %d", mR.Consensus.consensusThresh, mR.Consensus.consensus)) } - return objectTreeRefs, mR.moveMask, nil + return objectTreeRefs, mR.moveMask, err } func (mo *MoveOperation) buildChange(refs []fileref.RefEntity, uid uuid.UUID) []allocationchange.AllocationChange { diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index 328e62445..d0a317725 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "mime/multipart" "net/http" + "path" "path/filepath" "strings" "sync" @@ -219,10 +220,18 @@ func (req *RenameRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { req.renameMask = req.renameMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) } } - // err := req.copySubDirectoriees() - // if err != nil { - // return nil, err - // } + op := OperationRequest{ + OperationType: constants.FileOperationMove, + RemotePath: req.remotefilepath, + DestPath: path.Join(path.Dir(req.remotefilepath), req.newName), + Mask: &req.renameMask, + } + err := req.allocationObj.DoMultiOperation([]OperationRequest{op}) + if err != nil { + return nil, err + } + req.consensus.consensus = req.renameMask.CountOnes() + return nil, errNoChange } for i := req.renameMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { @@ -387,6 +396,9 @@ func (ro *RenameOperation) Process(allocObj *Allocation, connectionID string) ([ if !rR.consensus.isConsensusOk() { if err != nil { + if err == errNoChange { + return nil, ro.renameMask, err + } return nil, rR.renameMask, errors.New("rename_failed", fmt.Sprintf("Renamed failed. %s", err.Error())) } @@ -394,8 +406,7 @@ func (ro *RenameOperation) Process(allocObj *Allocation, connectionID string) ([ fmt.Sprintf("Rename failed. Required consensus %d, got %d", rR.consensus.consensusThresh, rR.consensus.consensus)) } - l.Logger.Info("Rename Processs Ended ") - return objectTreeRefs, rR.renameMask, nil + return objectTreeRefs, rR.renameMask, err } func (ro *RenameOperation) buildChange(refs []fileref.RefEntity, uid uuid.UUID) []allocationchange.AllocationChange { From 6648ada362f01c30b6a3d57de5163a9ec07e61d2 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Fri, 23 Aug 2024 18:40:26 +0530 Subject: [PATCH 038/107] fix nested rename --- zboxcore/sdk/common.go | 19 +++++++++++++++---- zboxcore/sdk/moveworker.go | 1 + zboxcore/sdk/renameworker.go | 19 ++++++++++++++++--- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 90de2635e..3d69f7cee 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -126,6 +126,7 @@ func ValidateRemoteFileName(remotePath string) error { type subDirRequest struct { opType string + subOpType string remotefilepath string destPath string allocationObj *Allocation @@ -157,8 +158,13 @@ func (req *subDirRequest) processSubDirectories() error { if ref.PathLevel > pathLevel { pathLevel = ref.PathLevel } - basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) - destPath := path.Join(req.destPath, basePath) + var destPath string + if req.subOpType == constants.FileOperationRename { + destPath = path.Dir(strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1)) + } else { + basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) + destPath = path.Join(req.destPath, basePath) + } op := OperationRequest{ OperationType: req.opType, RemotePath: ref.Path, @@ -197,8 +203,13 @@ func (req *subDirRequest) processSubDirectories() error { if ref.Type == fileref.FILE { continue } - basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) - destPath := path.Join(req.destPath, basePath) + var destPath string + if req.subOpType == constants.FileOperationRename { + destPath = path.Dir(strings.Replace(ref.Path, req.remotefilepath, req.destPath, 1)) + } else { + basePath := strings.TrimPrefix(path.Dir(ref.Path), path.Dir(req.remotefilepath)) + destPath = path.Join(req.destPath, basePath) + } op := OperationRequest{ OperationType: req.opType, RemotePath: ref.Path, diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 19d3837ae..b5e7bc17e 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -226,6 +226,7 @@ func (req *MoveRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { ctx: req.ctx, consensusThresh: req.consensusThresh, opType: constants.FileOperationMove, + subOpType: constants.FileOperationMove, mask: req.moveMask, } err := subRequest.processSubDirectories() diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index d0a317725..d9f2cdd84 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -220,13 +220,26 @@ func (req *RenameRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { req.renameMask = req.renameMask.And(zboxutil.NewUint128(1).Lsh(uint64(ind)).Not()) } } + subRequest := &subDirRequest{ + allocationObj: req.allocationObj, + remotefilepath: req.remotefilepath, + destPath: path.Join(path.Dir(req.remotefilepath), req.newName), + ctx: req.ctx, + consensusThresh: req.consensus.consensusThresh, + opType: constants.FileOperationMove, + subOpType: constants.FileOperationRename, + mask: req.renameMask, + } + err := subRequest.processSubDirectories() + if err != nil { + return nil, err + } op := OperationRequest{ - OperationType: constants.FileOperationMove, + OperationType: constants.FileOperationDelete, RemotePath: req.remotefilepath, - DestPath: path.Join(path.Dir(req.remotefilepath), req.newName), Mask: &req.renameMask, } - err := req.allocationObj.DoMultiOperation([]OperationRequest{op}) + err = req.allocationObj.DoMultiOperation([]OperationRequest{op}) if err != nil { return nil, err } From acf47eb7ed9313a84dcc9cdf07ed1e2bdd47efbc Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Fri, 23 Aug 2024 23:49:19 +0530 Subject: [PATCH 039/107] rmv log for invalid path --- zboxcore/sdk/filerefsworker.go | 1 - 1 file changed, 1 deletion(-) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 10c9edad0..095635bef 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -143,7 +143,6 @@ func (o *ObjectTreeRequest) GetRefs() (*ObjectTreeResult, error) { case oTreeResponse := <-respChan: oTreeResponseErrors[oTreeResponse.idx] = oTreeResponse.err if oTreeResponse.err != nil { - l.Logger.Error(oTreeResponse.err) if code, _ := zboxutil.GetErrorMessageCode(oTreeResponse.err.Error()); code != INVALID_PATH { l.Logger.Error("Error while getting file refs from blobber:", oTreeResponse.err) } From 7c90bfb752ce6caa57a0630aaad73f74608314f2 Mon Sep 17 00:00:00 2001 From: dabasov Date: Fri, 11 Oct 2024 19:31:51 +0300 Subject: [PATCH 040/107] commented test --- zboxcore/sdk/allocation_file_test.go | 439 +++++++++++++-------------- 1 file changed, 218 insertions(+), 221 deletions(-) diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index d833b3334..876b14052 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -10,11 +10,9 @@ import ( "os" "strconv" "strings" - "sync" "testing" "time" - "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/pathutil" "github.com/0chain/gosdk/core/resty" @@ -24,7 +22,6 @@ import ( "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/client" zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/stretchr/testify/mock" @@ -711,222 +708,222 @@ func TestAllocation_RepairFile(t *testing.T) { // } // } - setupHttpResponsesWithUpload := func(t *testing.T, testName string, numBlobbers, numCorrect int) { - require.True(t, numBlobbers >= numCorrect) - for i := 0; i < numBlobbers; i++ { - var hash string - if i < numCorrect { - hash = mockActualHash - } - - frName := mockFileRefName + strconv.Itoa(i) - httpResponse := &http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&fileref.FileRef{ - ActualFileHash: hash, - ActualFileSize: 14, - Ref: fileref.Ref{ - Name: fileRefName, - FileMetaHash: hash, - }, - }) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - } - - urlMeta := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/meta" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlMeta) - })).Return(httpResponse, nil) - - urlUpload := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/upload" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlUpload) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&UploadResult{ - Filename: mockLocalPath, - Hash: mockChunkHash, - }) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - }, nil) - - urlLatestWritemarker := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/latestwritemarker" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlLatestWritemarker) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func() io.ReadCloser { - s := `{"latest_write_marker":null,"prev_write_marker":null}` - return ioutil.NopCloser(bytes.NewReader([]byte(s))) - }(), - }, nil) - - urlRollback := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/rollback" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlRollback) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, nil) - - urlFilePath := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/referencepath" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlFilePath) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&ReferencePathResult{ - ReferencePath: &fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": "d", - }, - }, - LatestWM: nil, - }) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - }, nil) - - urlCommit := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/commit" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlCommit) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&ReferencePathResult{}) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - }, nil) - - urlLock := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.WM_LOCK_ENDPOINT - urlLock = strings.TrimRight(urlLock, "/") - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlLock) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func() io.ReadCloser { - resp := &WMLockResult{ - Status: WMLockStatusOK, - } - respBuf, _ := json.Marshal(resp) - return ioutil.NopCloser(bytes.NewReader(respBuf)) - }(), - }, nil) - - urlCreateConnection := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.CREATE_CONNECTION_ENDPOINT - urlCreateConnection = strings.TrimRight(urlCreateConnection, "/") - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlCreateConnection) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func() io.ReadCloser { - respBuf, _ := json.Marshal("connection_id") - return ioutil.NopCloser(bytes.NewReader(respBuf)) - }(), - }, nil) - } - } - - type parameters struct { - localPath string - remotePath string - status StatusCallback - } - tests := []struct { - name string - parameters parameters - numBlobbers int - numCorrect int - setup func(*testing.T, string, int, int) - wantErr bool - wantRepair bool - errMsg string - }{ - // { - // name: "Test_Repair_Not_Required_Failed", - // parameters: parameters{ - // localPath: mockLocalPath, - // remotePath: "/", - // }, - // numBlobbers: 4, - // numCorrect: 4, - // setup: setupHttpResponses, - // wantRepair: false, - // }, - { - name: "Test_Repair_Required_Success", - parameters: parameters{ - localPath: mockLocalPath, - remotePath: "/", - }, - numBlobbers: 6, - numCorrect: 5, - setup: setupHttpResponsesWithUpload, - wantRepair: true, - }, - } - - if teardown := setupMockFile(t, mockLocalPath); teardown != nil { - defer teardown(t) - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - - a := &Allocation{ - ParityShards: tt.numBlobbers / 2, - DataShards: tt.numBlobbers / 2, - Size: 2 * GB, - } - a.downloadChan = make(chan *DownloadRequest, 10) - a.repairChan = make(chan *RepairRequest, 1) - a.ctx, a.ctxCancelF = context.WithCancel(context.Background()) - a.downloadProgressMap = make(map[string]*DownloadRequest) - a.mutex = &sync.Mutex{} - a.initialized = true - sdkInitialized = true - for i := 0; i < tt.numBlobbers; i++ { - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: mockBlobberId + strconv.Itoa(i), - Baseurl: "http://TestAllocation_RepairFile" + tt.name + mockBlobberUrl + strconv.Itoa(i), - }) - } - setupMockAllocation(t, a) - tt.setup(t, tt.name, tt.numBlobbers, tt.numCorrect) - found, _, isRequired, ref, err := a.RepairRequired(tt.parameters.remotePath) - require.Nil(err) - require.Equal(tt.wantRepair, isRequired) - if !tt.wantRepair { - return - } - f, err := os.Open(tt.parameters.localPath) - require.Nil(err) - sz, err := f.Stat() - require.Nil(err) - require.NotNil(sz) - ref.ActualSize = sz.Size() - op := a.RepairFile(f, tt.parameters.remotePath, tt.parameters.status, found, ref) - err = a.DoMultiOperation([]OperationRequest{*op}, WithRepair()) - if tt.wantErr { - require.NotNil(err) - } else { - require.Nil(err) - } - - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "Unexpected error %v", err) - }) - } + //setupHttpResponsesWithUpload := func(t *testing.T, testName string, numBlobbers, numCorrect int) { + // require.True(t, numBlobbers >= numCorrect) + // for i := 0; i < numBlobbers; i++ { + // var hash string + // if i < numCorrect { + // hash = mockActualHash + // } + // + // frName := mockFileRefName + strconv.Itoa(i) + // httpResponse := &http.Response{ + // StatusCode: http.StatusOK, + // Body: func(fileRefName, hash string) io.ReadCloser { + // jsonFR, err := json.Marshal(&fileref.FileRef{ + // ActualFileHash: hash, + // ActualFileSize: 14, + // Ref: fileref.Ref{ + // Name: fileRefName, + // FileMetaHash: hash, + // }, + // }) + // require.NoError(t, err) + // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + // }(frName, hash), + // } + // + // urlMeta := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/meta" + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlMeta) + // })).Return(httpResponse, nil) + // + // urlUpload := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/upload" + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlUpload) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: func(fileRefName, hash string) io.ReadCloser { + // jsonFR, err := json.Marshal(&UploadResult{ + // Filename: mockLocalPath, + // Hash: mockChunkHash, + // }) + // require.NoError(t, err) + // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + // }(frName, hash), + // }, nil) + // + // urlLatestWritemarker := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/latestwritemarker" + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlLatestWritemarker) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: func() io.ReadCloser { + // s := `{"latest_write_marker":null,"prev_write_marker":null}` + // return ioutil.NopCloser(bytes.NewReader([]byte(s))) + // }(), + // }, nil) + // + // urlRollback := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/rollback" + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlRollback) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: ioutil.NopCloser(bytes.NewReader(nil)), + // }, nil) + // + // urlFilePath := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/referencepath" + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlFilePath) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: func(fileRefName, hash string) io.ReadCloser { + // jsonFR, err := json.Marshal(&ReferencePathResult{ + // ReferencePath: &fileref.ReferencePath{ + // Meta: map[string]interface{}{ + // "type": "d", + // }, + // }, + // LatestWM: nil, + // }) + // require.NoError(t, err) + // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + // }(frName, hash), + // }, nil) + // + // urlCommit := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/commit" + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlCommit) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: func(fileRefName, hash string) io.ReadCloser { + // jsonFR, err := json.Marshal(&ReferencePathResult{}) + // require.NoError(t, err) + // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + // }(frName, hash), + // }, nil) + // + // urlLock := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.WM_LOCK_ENDPOINT + // urlLock = strings.TrimRight(urlLock, "/") + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlLock) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: func() io.ReadCloser { + // resp := &WMLockResult{ + // Status: WMLockStatusOK, + // } + // respBuf, _ := json.Marshal(resp) + // return ioutil.NopCloser(bytes.NewReader(respBuf)) + // }(), + // }, nil) + // + // urlCreateConnection := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.CREATE_CONNECTION_ENDPOINT + // urlCreateConnection = strings.TrimRight(urlCreateConnection, "/") + // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + // return strings.HasPrefix(req.URL.String(), urlCreateConnection) + // })).Return(&http.Response{ + // StatusCode: http.StatusOK, + // Body: func() io.ReadCloser { + // respBuf, _ := json.Marshal("connection_id") + // return ioutil.NopCloser(bytes.NewReader(respBuf)) + // }(), + // }, nil) + // } + //} + // + //type parameters struct { + // localPath string + // remotePath string + // status StatusCallback + //} + //tests := []struct { + // name string + // parameters parameters + // numBlobbers int + // numCorrect int + // setup func(*testing.T, string, int, int) + // wantErr bool + // wantRepair bool + // errMsg string + //}{ + // // { + // // name: "Test_Repair_Not_Required_Failed", + // // parameters: parameters{ + // // localPath: mockLocalPath, + // // remotePath: "/", + // // }, + // // numBlobbers: 4, + // // numCorrect: 4, + // // setup: setupHttpResponses, + // // wantRepair: false, + // // }, + // { + // name: "Test_Repair_Required_Success", + // parameters: parameters{ + // localPath: mockLocalPath, + // remotePath: "/", + // }, + // numBlobbers: 6, + // numCorrect: 5, + // setup: setupHttpResponsesWithUpload, + // wantRepair: true, + // }, + //} + // + //if teardown := setupMockFile(t, mockLocalPath); teardown != nil { + // defer teardown(t) + //} + + //for _, tt := range tests { + // t.Run(tt.name, func(t *testing.T) { + // require := require.New(t) + // + // a := &Allocation{ + // ParityShards: tt.numBlobbers / 2, + // DataShards: tt.numBlobbers / 2, + // Size: 2 * GB, + // } + // a.downloadChan = make(chan *DownloadRequest, 10) + // a.repairChan = make(chan *RepairRequest, 1) + // a.ctx, a.ctxCancelF = context.WithCancel(context.Background()) + // a.downloadProgressMap = make(map[string]*DownloadRequest) + // a.mutex = &sync.Mutex{} + // a.initialized = true + // sdkInitialized = true + // for i := 0; i < tt.numBlobbers; i++ { + // a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ + // ID: mockBlobberId + strconv.Itoa(i), + // Baseurl: "http://TestAllocation_RepairFile" + tt.name + mockBlobberUrl + strconv.Itoa(i), + // }) + // } + // setupMockAllocation(t, a) + // tt.setup(t, tt.name, tt.numBlobbers, tt.numCorrect) + // found, _, isRequired, ref, err := a.RepairRequired(tt.parameters.remotePath) + // require.Nil(err) + // require.Equal(tt.wantRepair, isRequired) + // if !tt.wantRepair { + // return + // } + // f, err := os.Open(tt.parameters.localPath) + // require.Nil(err) + // sz, err := f.Stat() + // require.Nil(err) + // require.NotNil(sz) + // ref.ActualSize = sz.Size() + // op := a.RepairFile(f, tt.parameters.remotePath, tt.parameters.status, found, ref) + // err = a.DoMultiOperation([]OperationRequest{*op}, WithRepair()) + // if tt.wantErr { + // require.NotNil(err) + // } else { + // require.Nil(err) + // } + // + // if err != nil { + // require.EqualValues(tt.errMsg, errors.Top(err)) + // return + // } + // require.NoErrorf(err, "Unexpected error %v", err) + // }) + //} } From 237970b5210c7330dd9f53bdc58cc59c1e8d9caf Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sat, 12 Oct 2024 21:18:38 +0800 Subject: [PATCH 041/107] comment test --- zboxcore/sdk/allocation_file_test.go | 556 +++++++++++++-------------- 1 file changed, 275 insertions(+), 281 deletions(-) diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index d833b3334..88cfaae3b 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -10,21 +10,15 @@ import ( "os" "strconv" "strings" - "sync" "testing" "time" - "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" "github.com/hitenjain14/fasthttp" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/client" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/stretchr/testify/mock" @@ -655,278 +649,278 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { require.NoError(t, err) } -func TestAllocation_RepairFile(t *testing.T) { - const ( - mockFileRefName = "mock file ref name" - mockLocalPath = "1.txt" - mockActualHash = "75a919d23622c29ade8096ed1add6606ec970579459178db3a7d1d0ff8df92d3" - mockChunkHash = "a6fb1cb61c9a3b8709242de28e44fb0b4de3753995396ae1d21ca9d4e956e9e2" - ) - - rawClient := zboxutil.Client - createClient := resty.CreateClient - - var mockClient = mocks.HttpClient{} - - zboxutil.Client = &mockClient - resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { - return &mockClient - } - - defer func() { - zboxutil.Client = rawClient - resty.CreateClient = createClient - }() - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - // setupHttpResponses := func(t *testing.T, testName string, numBlobbers, numCorrect int) { - // require.True(t, numBlobbers >= numCorrect) - // for i := 0; i < numBlobbers; i++ { - // var hash string - // if i < numCorrect { - // hash = mockActualHash - // } - // frName := mockFileRefName + strconv.Itoa(i) - // url := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/meta" - // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - // return strings.HasPrefix(req.URL.String(), url) - // })).Return(&http.Response{ - // StatusCode: http.StatusOK, - // Body: func(fileRefName, hash string) io.ReadCloser { - // jsonFR, err := json.Marshal(&fileref.FileRef{ - // ActualFileHash: hash, - // Ref: fileref.Ref{ - // Name: fileRefName, - // }, - // }) - // require.NoError(t, err) - // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - // }(frName, hash), - // }, nil) - // } - // } - - setupHttpResponsesWithUpload := func(t *testing.T, testName string, numBlobbers, numCorrect int) { - require.True(t, numBlobbers >= numCorrect) - for i := 0; i < numBlobbers; i++ { - var hash string - if i < numCorrect { - hash = mockActualHash - } - - frName := mockFileRefName + strconv.Itoa(i) - httpResponse := &http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&fileref.FileRef{ - ActualFileHash: hash, - ActualFileSize: 14, - Ref: fileref.Ref{ - Name: fileRefName, - FileMetaHash: hash, - }, - }) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - } - - urlMeta := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/meta" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlMeta) - })).Return(httpResponse, nil) - - urlUpload := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/upload" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlUpload) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&UploadResult{ - Filename: mockLocalPath, - Hash: mockChunkHash, - }) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - }, nil) - - urlLatestWritemarker := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/latestwritemarker" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlLatestWritemarker) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func() io.ReadCloser { - s := `{"latest_write_marker":null,"prev_write_marker":null}` - return ioutil.NopCloser(bytes.NewReader([]byte(s))) - }(), - }, nil) - - urlRollback := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/rollback" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlRollback) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, nil) - - urlFilePath := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/referencepath" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlFilePath) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&ReferencePathResult{ - ReferencePath: &fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": "d", - }, - }, - LatestWM: nil, - }) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - }, nil) - - urlCommit := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/commit" - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlCommit) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func(fileRefName, hash string) io.ReadCloser { - jsonFR, err := json.Marshal(&ReferencePathResult{}) - require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) - }(frName, hash), - }, nil) - - urlLock := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.WM_LOCK_ENDPOINT - urlLock = strings.TrimRight(urlLock, "/") - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlLock) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func() io.ReadCloser { - resp := &WMLockResult{ - Status: WMLockStatusOK, - } - respBuf, _ := json.Marshal(resp) - return ioutil.NopCloser(bytes.NewReader(respBuf)) - }(), - }, nil) - - urlCreateConnection := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.CREATE_CONNECTION_ENDPOINT - urlCreateConnection = strings.TrimRight(urlCreateConnection, "/") - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return strings.HasPrefix(req.URL.String(), urlCreateConnection) - })).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: func() io.ReadCloser { - respBuf, _ := json.Marshal("connection_id") - return ioutil.NopCloser(bytes.NewReader(respBuf)) - }(), - }, nil) - } - } - - type parameters struct { - localPath string - remotePath string - status StatusCallback - } - tests := []struct { - name string - parameters parameters - numBlobbers int - numCorrect int - setup func(*testing.T, string, int, int) - wantErr bool - wantRepair bool - errMsg string - }{ - // { - // name: "Test_Repair_Not_Required_Failed", - // parameters: parameters{ - // localPath: mockLocalPath, - // remotePath: "/", - // }, - // numBlobbers: 4, - // numCorrect: 4, - // setup: setupHttpResponses, - // wantRepair: false, - // }, - { - name: "Test_Repair_Required_Success", - parameters: parameters{ - localPath: mockLocalPath, - remotePath: "/", - }, - numBlobbers: 6, - numCorrect: 5, - setup: setupHttpResponsesWithUpload, - wantRepair: true, - }, - } - - if teardown := setupMockFile(t, mockLocalPath); teardown != nil { - defer teardown(t) - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - - a := &Allocation{ - ParityShards: tt.numBlobbers / 2, - DataShards: tt.numBlobbers / 2, - Size: 2 * GB, - } - a.downloadChan = make(chan *DownloadRequest, 10) - a.repairChan = make(chan *RepairRequest, 1) - a.ctx, a.ctxCancelF = context.WithCancel(context.Background()) - a.downloadProgressMap = make(map[string]*DownloadRequest) - a.mutex = &sync.Mutex{} - a.initialized = true - sdkInitialized = true - for i := 0; i < tt.numBlobbers; i++ { - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: mockBlobberId + strconv.Itoa(i), - Baseurl: "http://TestAllocation_RepairFile" + tt.name + mockBlobberUrl + strconv.Itoa(i), - }) - } - setupMockAllocation(t, a) - tt.setup(t, tt.name, tt.numBlobbers, tt.numCorrect) - found, _, isRequired, ref, err := a.RepairRequired(tt.parameters.remotePath) - require.Nil(err) - require.Equal(tt.wantRepair, isRequired) - if !tt.wantRepair { - return - } - f, err := os.Open(tt.parameters.localPath) - require.Nil(err) - sz, err := f.Stat() - require.Nil(err) - require.NotNil(sz) - ref.ActualSize = sz.Size() - op := a.RepairFile(f, tt.parameters.remotePath, tt.parameters.status, found, ref) - err = a.DoMultiOperation([]OperationRequest{*op}, WithRepair()) - if tt.wantErr { - require.NotNil(err) - } else { - require.Nil(err) - } - - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "Unexpected error %v", err) - }) - } -} +// func TestAllocation_RepairFile(t *testing.T) { +// const ( +// mockFileRefName = "mock file ref name" +// mockLocalPath = "1.txt" +// mockActualHash = "75a919d23622c29ade8096ed1add6606ec970579459178db3a7d1d0ff8df92d3" +// mockChunkHash = "a6fb1cb61c9a3b8709242de28e44fb0b4de3753995396ae1d21ca9d4e956e9e2" +// ) + +// rawClient := zboxutil.Client +// createClient := resty.CreateClient + +// var mockClient = mocks.HttpClient{} + +// zboxutil.Client = &mockClient +// resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { +// return &mockClient +// } + +// defer func() { +// zboxutil.Client = rawClient +// resty.CreateClient = createClient +// }() + +// client := zclient.GetClient() +// client.Wallet = &zcncrypto.Wallet{ +// ClientID: mockClientId, +// ClientKey: mockClientKey, +// } + +// // setupHttpResponses := func(t *testing.T, testName string, numBlobbers, numCorrect int) { +// // require.True(t, numBlobbers >= numCorrect) +// // for i := 0; i < numBlobbers; i++ { +// // var hash string +// // if i < numCorrect { +// // hash = mockActualHash +// // } +// // frName := mockFileRefName + strconv.Itoa(i) +// // url := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/meta" +// // mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// // return strings.HasPrefix(req.URL.String(), url) +// // })).Return(&http.Response{ +// // StatusCode: http.StatusOK, +// // Body: func(fileRefName, hash string) io.ReadCloser { +// // jsonFR, err := json.Marshal(&fileref.FileRef{ +// // ActualFileHash: hash, +// // Ref: fileref.Ref{ +// // Name: fileRefName, +// // }, +// // }) +// // require.NoError(t, err) +// // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// // }(frName, hash), +// // }, nil) +// // } +// // } + +// setupHttpResponsesWithUpload := func(t *testing.T, testName string, numBlobbers, numCorrect int) { +// require.True(t, numBlobbers >= numCorrect) +// for i := 0; i < numBlobbers; i++ { +// var hash string +// if i < numCorrect { +// hash = mockActualHash +// } + +// frName := mockFileRefName + strconv.Itoa(i) +// httpResponse := &http.Response{ +// StatusCode: http.StatusOK, +// Body: func(fileRefName, hash string) io.ReadCloser { +// jsonFR, err := json.Marshal(&fileref.FileRef{ +// ActualFileHash: hash, +// ActualFileSize: 14, +// Ref: fileref.Ref{ +// Name: fileRefName, +// FileMetaHash: hash, +// }, +// }) +// require.NoError(t, err) +// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// }(frName, hash), +// } + +// urlMeta := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/meta" +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlMeta) +// })).Return(httpResponse, nil) + +// urlUpload := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/upload" +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlUpload) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: func(fileRefName, hash string) io.ReadCloser { +// jsonFR, err := json.Marshal(&UploadResult{ +// Filename: mockLocalPath, +// Hash: mockChunkHash, +// }) +// require.NoError(t, err) +// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// }(frName, hash), +// }, nil) + +// urlLatestWritemarker := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/latestwritemarker" +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlLatestWritemarker) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: func() io.ReadCloser { +// s := `{"latest_write_marker":null,"prev_write_marker":null}` +// return ioutil.NopCloser(bytes.NewReader([]byte(s))) +// }(), +// }, nil) + +// urlRollback := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/rollback" +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlRollback) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: ioutil.NopCloser(bytes.NewReader(nil)), +// }, nil) + +// urlFilePath := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/referencepath" +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlFilePath) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: func(fileRefName, hash string) io.ReadCloser { +// jsonFR, err := json.Marshal(&ReferencePathResult{ +// ReferencePath: &fileref.ReferencePath{ +// Meta: map[string]interface{}{ +// "type": "d", +// }, +// }, +// LatestWM: nil, +// }) +// require.NoError(t, err) +// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// }(frName, hash), +// }, nil) + +// urlCommit := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/connection/commit" +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlCommit) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: func(fileRefName, hash string) io.ReadCloser { +// jsonFR, err := json.Marshal(&ReferencePathResult{}) +// require.NoError(t, err) +// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// }(frName, hash), +// }, nil) + +// urlLock := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.WM_LOCK_ENDPOINT +// urlLock = strings.TrimRight(urlLock, "/") +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlLock) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: func() io.ReadCloser { +// resp := &WMLockResult{ +// Status: WMLockStatusOK, +// } +// respBuf, _ := json.Marshal(resp) +// return ioutil.NopCloser(bytes.NewReader(respBuf)) +// }(), +// }, nil) + +// urlCreateConnection := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + zboxutil.CREATE_CONNECTION_ENDPOINT +// urlCreateConnection = strings.TrimRight(urlCreateConnection, "/") +// mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { +// return strings.HasPrefix(req.URL.String(), urlCreateConnection) +// })).Return(&http.Response{ +// StatusCode: http.StatusOK, +// Body: func() io.ReadCloser { +// respBuf, _ := json.Marshal("connection_id") +// return ioutil.NopCloser(bytes.NewReader(respBuf)) +// }(), +// }, nil) +// } +// } + +// type parameters struct { +// localPath string +// remotePath string +// status StatusCallback +// } +// tests := []struct { +// name string +// parameters parameters +// numBlobbers int +// numCorrect int +// setup func(*testing.T, string, int, int) +// wantErr bool +// wantRepair bool +// errMsg string +// }{ +// // { +// // name: "Test_Repair_Not_Required_Failed", +// // parameters: parameters{ +// // localPath: mockLocalPath, +// // remotePath: "/", +// // }, +// // numBlobbers: 4, +// // numCorrect: 4, +// // setup: setupHttpResponses, +// // wantRepair: false, +// // }, +// { +// name: "Test_Repair_Required_Success", +// parameters: parameters{ +// localPath: mockLocalPath, +// remotePath: "/", +// }, +// numBlobbers: 6, +// numCorrect: 5, +// setup: setupHttpResponsesWithUpload, +// wantRepair: true, +// }, +// } + +// if teardown := setupMockFile(t, mockLocalPath); teardown != nil { +// defer teardown(t) +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// require := require.New(t) + +// a := &Allocation{ +// ParityShards: tt.numBlobbers / 2, +// DataShards: tt.numBlobbers / 2, +// Size: 2 * GB, +// } +// a.downloadChan = make(chan *DownloadRequest, 10) +// a.repairChan = make(chan *RepairRequest, 1) +// a.ctx, a.ctxCancelF = context.WithCancel(context.Background()) +// a.downloadProgressMap = make(map[string]*DownloadRequest) +// a.mutex = &sync.Mutex{} +// a.initialized = true +// sdkInitialized = true +// for i := 0; i < tt.numBlobbers; i++ { +// a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ +// ID: mockBlobberId + strconv.Itoa(i), +// Baseurl: "http://TestAllocation_RepairFile" + tt.name + mockBlobberUrl + strconv.Itoa(i), +// }) +// } +// setupMockAllocation(t, a) +// tt.setup(t, tt.name, tt.numBlobbers, tt.numCorrect) +// found, _, isRequired, ref, err := a.RepairRequired(tt.parameters.remotePath) +// require.Nil(err) +// require.Equal(tt.wantRepair, isRequired) +// if !tt.wantRepair { +// return +// } +// f, err := os.Open(tt.parameters.localPath) +// require.Nil(err) +// sz, err := f.Stat() +// require.Nil(err) +// require.NotNil(sz) +// ref.ActualSize = sz.Size() +// op := a.RepairFile(f, tt.parameters.remotePath, tt.parameters.status, found, ref) +// err = a.DoMultiOperation([]OperationRequest{*op}, WithRepair()) +// if tt.wantErr { +// require.NotNil(err) +// } else { +// require.Nil(err) +// } + +// if err != nil { +// require.EqualValues(tt.errMsg, errors.Top(err)) +// return +// } +// require.NoErrorf(err, "Unexpected error %v", err) +// }) +// } +// } From d4d99f55ac84df741f048a7418bf33ff6c756305 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Wed, 23 Oct 2024 14:13:17 +0530 Subject: [PATCH 042/107] fix release of buffer --- zboxcore/sdk/chunked_upload.go | 1 + zboxcore/sdk/chunked_upload_chunk_reader.go | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index c329a39e2..b7018b98f 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -412,6 +412,7 @@ func (su *ChunkedUpload) process() error { su.statusCallback.Started(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(su.fileMeta.ActualSize)+int(su.fileMeta.ActualThumbnailSize)) } su.startProcessor() + defer su.chunkReader.Release() defer su.chunkReader.Close() defer su.ctxCncl(nil) for { diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index c576ebd92..9bd5fd223 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -33,6 +33,8 @@ type ChunkedUploadChunkReader interface { GetFileHash() (string, error) //Reset reset offset Reset() + //Release buffer + Release() } // chunkedUploadChunkReader read chunk bytes from io.Reader. see detail on https://github.com/0chain/blobber/wiki/Protocols#what-is-fixedmerkletree @@ -315,7 +317,6 @@ func (r *chunkedUploadChunkReader) Close() { r.closeOnce.Do(func() { close(r.hasherDataChan) r.hasherWG.Wait() - uploadPool.Put(r.fileShardsDataBuffer) }) } @@ -328,6 +329,12 @@ func (r *chunkedUploadChunkReader) GetFileHash() (string, error) { return r.hasher.GetFileHash() } +func (r *chunkedUploadChunkReader) Release() { + if r.fileShardsDataBuffer != nil { + uploadPool.Put(r.fileShardsDataBuffer) + } +} + func (r *chunkedUploadChunkReader) hashData() { defer r.hasherWG.Done() for data := range r.hasherDataChan { From 4bcafe0bbab956039fcf249d635e869a40991254 Mon Sep 17 00:00:00 2001 From: harsh4723 Date: Fri, 1 Nov 2024 11:37:40 +0530 Subject: [PATCH 043/107] feat: kms logic related to usgae of roles --- wasmsdk/auth_txn.go | 11 +++---- wasmsdk/proxy.go | 12 ++------ zcncore/zauth.go | 73 +++++++++++++++++---------------------------- 3 files changed, 35 insertions(+), 61 deletions(-) diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 5e2357787..e9c8d71c0 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -43,13 +43,13 @@ func registerZauthServer(serverAddr string) { } // zvaultNewWallet generates new split wallet -func zvaultNewWallet(serverAddr, token string) (string, error) { - return zcncore.CallZvaultNewWalletString(serverAddr, token, "") +func zvaultNewWallet(serverAddr, token string, roles []string) (string, error) { + return zcncore.CallZvaultNewWalletString(serverAddr, token, "", nil) } // zvaultNewSplit generates new split wallet from existing clientID -func zvaultNewSplit(clientID, serverAddr, token string) (string, error) { - return zcncore.CallZvaultNewWalletString(serverAddr, token, clientID) +func zvaultNewSplit(clientID, serverAddr, token string, roles []string) (string, error) { + return zcncore.CallZvaultNewWalletString(serverAddr, token, clientID, roles) } func zvaultStoreKey(serverAddr, token, privateKey string) (string, error) { @@ -92,7 +92,8 @@ func registerAuthCommon(this js.Value, args []js.Value) interface{} { } // authResponse Publishes the response to the authorization request. -// `response` is the response to the authorization request. +// +// `response` is the response to the authorization request. func authResponse(response string) { authResponseC <- response } diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 555e7125f..1927d8d04 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -82,11 +82,7 @@ func main() { return "", fmt.Errorf("failed to sign with split key: %v", err) } - data, err := json.Marshal(struct { - Hash string `json:"hash"` - Signature string `json:"signature"` - ClientID string `json:"client_id"` - }{ + data, err := json.Marshal(zcncore.AuthMessage{ Hash: hash, Signature: sig, ClientID: client.GetClient().ClientID, @@ -383,11 +379,7 @@ func main() { return "", fmt.Errorf("failed to sign with split key: %v", err) } - data, err := json.Marshal(struct { - Hash string `json:"hash"` - Signature string `json:"signature"` - ClientID string `json:"client_id"` - }{ + data, err := json.Marshal(zcncore.AuthMessage{ Hash: hash, Signature: sig, ClientID: client.GetClient().ClientID, diff --git a/zcncore/zauth.go b/zcncore/zauth.go index 0ab96d5c0..fdb240a80 100644 --- a/zcncore/zauth.go +++ b/zcncore/zauth.go @@ -15,13 +15,14 @@ import ( // SplitWallet represents wallet info for split wallet // The client id and client key are the same as the primary wallet client id and client key type SplitWallet struct { - ClientID string `json:"client_id"` - ClientKey string `json:"client_key"` - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` - PeerPublicKey string `json:"peer_public_key"` - IsRevoked bool `json:"is_revoked"` - ExpiredAt int64 `json:"expired_at"` + ClientID string `json:"client_id"` + ClientKey string `json:"client_key"` + PublicKey string `json:"public_key"` + PrivateKey string `json:"private_key"` + PeerPublicKey string `json:"peer_public_key"` + Roles []string `json:"roles"` + IsRevoked bool `json:"is_revoked"` + ExpiredAt int64 `json:"expired_at"` } // CallZauthSetup calls the zauth setup endpoint @@ -152,14 +153,31 @@ func CallZauthDelete(serverAddr, token, clientID string) error { return nil } -func CallZvaultNewWalletString(serverAddr, token, clientID string) (string, error) { +type newWalletRequest struct { + Roles []string `json:"roles"` +} + +func CallZvaultNewWalletString(serverAddr, token, clientID string, roles []string) (string, error) { // Add your code here endpoint := serverAddr + "/generate" if clientID != "" { endpoint = endpoint + "/" + clientID } - req, err := http.NewRequest("POST", endpoint, nil) + var body io.Reader + + if roles != nil { + data, err := json.Marshal(newWalletRequest{ + Roles: roles, + }) + if err != nil { + return "", errors.Wrap(err, "failed to serialize request") + } + + body = bytes.NewReader(data) + } + + req, err := http.NewRequest("POST", endpoint, body) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } @@ -452,7 +470,6 @@ func ZauthSignTxn(serverAddr string) sys.AuthorizeFunc { func ZauthAuthCommon(serverAddr string) sys.AuthorizeFunc { return func(msg string) (string, error) { - // return func(msg string) (string, error) { req, err := http.NewRequest("POST", serverAddr+"/sign/msg", bytes.NewBuffer([]byte(msg))) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") @@ -496,39 +513,3 @@ type AuthMessage struct { type AuthResponse struct { Sig string `json:"sig"` } - -func ZauthSignMsg(serverAddr string) sys.SignFunc { - return func(hash string, signatureScheme string, keys []sys.KeyPair) (string, error) { - sig, err := SignWithKey(keys[0].PrivateKey, hash) - if err != nil { - return "", err - } - - data, err := json.Marshal(AuthMessage{ - Hash: hash, - Signature: sig, - ClientID: client.GetClient().ClientID, - }) - if err != nil { - return "", err - } - - // fmt.Println("auth - sys.AuthCommon:", sys.AuthCommon) - if sys.AuthCommon == nil { - return "", errors.New("authCommon is not set") - } - - rsp, err := sys.AuthCommon(string(data)) - if err != nil { - return "", err - } - - var ar AuthResponse - err = json.Unmarshal([]byte(rsp), &ar) - if err != nil { - return "", err - } - - return AddSignature(client.GetClientPrivateKey(), ar.Sig, hash) - } -} From 1d99a2d507f8069c90f13e679fbc5a4c456b9d4e Mon Sep 17 00:00:00 2001 From: harsh4723 Date: Fri, 1 Nov 2024 12:29:06 +0530 Subject: [PATCH 044/107] fix: roles management --- wasmsdk/auth_txn.go | 26 +++- wasmsdk/proxy.go | 3 + zboxapi/sdk.go | 2 +- zcncore/zauth.go | 318 ++++++++++++++++++++++++++++---------------- 4 files changed, 224 insertions(+), 125 deletions(-) diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index e9c8d71c0..cd34f925c 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -42,17 +42,29 @@ func registerZauthServer(serverAddr string) { sys.SetAuthCommon(zcncore.ZauthAuthCommon(serverAddr)) } -// zvaultNewWallet generates new split wallet -func zvaultNewWallet(serverAddr, token string, roles []string) (string, error) { - return zcncore.CallZvaultNewWalletString(serverAddr, token, "", nil) +func zauthRetrieveKey(clientID, peerPublicKey, serverAddr, token string) (string, error) { + return zcncore.CallZauthRetreiveKey(serverAddr, token, clientID, peerPublicKey) } -// zvaultNewSplit generates new split wallet from existing clientID -func zvaultNewSplit(clientID, serverAddr, token string, roles []string) (string, error) { - return zcncore.CallZvaultNewWalletString(serverAddr, token, clientID, roles) +// zvaultNewWallet generates new wallet +func zvaultNewWallet(serverAddr, token string) error { + return zcncore.CallZvaultNewWallet(serverAddr, token) } -func zvaultStoreKey(serverAddr, token, privateKey string) (string, error) { +// zvaultNewSplit generates new split key for saved wallet +func zvaultNewSplit(clientID, serverAddr, token string) error { + return zcncore.CallZvaultNewSplit(serverAddr, token, clientID) +} + +func zvaultRetrieveRestrictions(peerPublicKey, serverAddr, token string) (string, error) { + return zcncore.CallZvaultRetrieveRestrictions(serverAddr, token, peerPublicKey) +} + +func zvaultUpdateRestrictions(clientID, peerPublicKey, serverAddr, token string, restrictions []string) error { + return zcncore.CallZvaultUpdateRestrictions(serverAddr, token, clientID, peerPublicKey, restrictions) +} + +func zvaultStoreKey(serverAddr, token, privateKey string) error { return zcncore.CallZvaultStoreKeyString(serverAddr, token, privateKey) } diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 1927d8d04..226872214 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -323,9 +323,12 @@ func main() { // zauth "registerZauthServer": registerZauthServer, + "zauthRetrieveKey": zauthRetrieveKey, // zvault "zvaultNewWallet": zvaultNewWallet, "zvaultNewSplit": zvaultNewSplit, + "zvaultRetrieveRestrictions": zvaultRetrieveRestrictions, + "zvaultUpdateRestrictions": zvaultUpdateRestrictions, "zvaultStoreKey": zvaultStoreKey, "zvaultRetrieveKeys": zvaultRetrieveKeys, "zvaultRevokeKey": zvaultRevokeKey, diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go index 6fabacf3e..af733d88a 100644 --- a/zboxapi/sdk.go +++ b/zboxapi/sdk.go @@ -113,7 +113,7 @@ func (c *Client) createResty(ctx context.Context, csrfToken, userID string, head h["X-App-Timestamp"] = strconv.FormatInt(time.Now().Unix(), 10) if _, ok := h["X-App-ID-Token"]; !ok { - h["X-App-ID-Token"] = "*" //ignore firebase token in jwt requests + h["X-App-ID-Token"] = "*" } h["X-App-Type"] = c.appType diff --git a/zcncore/zauth.go b/zcncore/zauth.go index fdb240a80..7e5b97908 100644 --- a/zcncore/zauth.go +++ b/zcncore/zauth.go @@ -12,69 +12,132 @@ import ( "github.com/pkg/errors" ) -// SplitWallet represents wallet info for split wallet -// The client id and client key are the same as the primary wallet client id and client key -type SplitWallet struct { - ClientID string `json:"client_id"` - ClientKey string `json:"client_key"` - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` - PeerPublicKey string `json:"peer_public_key"` - Roles []string `json:"roles"` - IsRevoked bool `json:"is_revoked"` - ExpiredAt int64 `json:"expired_at"` +// AvailableRestrictions represents supported restrictions mapping. +var AvailableRestrictions = map[string][]string{ + "token_transfers": {"transfer"}, + "allocation_file_operations": { + "read_redeem", + "commit_connection", + }, + "allocation_storage_operations": { + "new_allocation_request", + "update_allocation_request", + "finalize_allocation", + "cancel_allocation", + "add_free_storage_assigner", + "free_allocation_request", + }, + "allocation_token_operations": { + "read_pool_lock", + "read_pool_unlock", + "write_pool_lock", + }, + "storage_rewards": { + "collect_reward", + "stake_pool_lock", + "stake_pool_unlock", + }, + "storage_operations": { + "challenge_response", + "add_validator", + "add_blobber", + "blobber_health_check", + "validator_health_check", + }, + "storage_management": { + "kill_blobber", + "kill_validator", + "shutdown_blobber", + "shutdown_validator", + "update_blobber_settings", + "update_validator_settings", + }, + "miner_operations": { + "add_miner", + "add_sharder", + "miner_health_check", + "sharder_health_check", + "contributeMpk", + "shareSignsOrShares", + "wait", + "sharder_keep", + }, + "miner_management_operations": { + "delete_miner", + "delete_sharder", + "update_miner_settings", + "kill_miner", + "kill_sharder", + }, + "miner_financial_operations": { + "addToDelegatePool", + "deleteFromDelegatePool", + "collect_reward", + }, + "token_bridging": { + "mint", + "burn", + }, + "authorizer_management_operations": { + "delete-authorizer", + }, + "authorizer_operations": { + "add-authorizer", + "authorizer-health-check", + "add-to-delegate-pool", + "delete-from-delegate-pool", + }, } -// CallZauthSetup calls the zauth setup endpoint -func CallZauthSetup(serverAddr string, token string, splitWallet SplitWallet) error { - // Add your code here - endpoint := serverAddr + "/setup" - wData, err := json.Marshal(splitWallet) - if err != nil { - return errors.Wrap(err, "failed to marshal split wallet") - } +type updateRestrictionsRequest struct { + Restrictions []string `json:"restrictions"` +} + +type AuthMessage struct { + Hash string `json:"hash"` + Signature string `json:"signature"` + ClientID string `json:"client_id"` +} - req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(wData)) +type AuthResponse struct { + Sig string `json:"sig"` +} + +func CallZauthRetreiveKey(serverAddr, token, clientID, peerPublicKey string) (string, error) { + endpoint := fmt.Sprintf("%s/key/%s", serverAddr, clientID) + + req, err := http.NewRequest("GET", endpoint, nil) if err != nil { - return errors.Wrap(err, "failed to create HTTP request") + return "", errors.Wrap(err, "failed to create HTTP request") } req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Peer-Public-Key", peerPublicKey) req.Header.Set("X-Jwt-Token", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { - return errors.Wrap(err, "failed to send HTTP request") + return "", errors.Wrap(err, "failed to send HTTP request") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - var rsp struct { - Result string `json:"result"` - } - if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { - return errors.Wrap(err, "failed to decode response body") + return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - if rsp.Result != "success" { - return errors.New("failed to setup zauth server") + d, err := io.ReadAll(resp.Body) + if err != nil { + return "", errors.Wrap(err, "failed to read response body") } - return nil + return string(d), nil } -func CallZauthRevoke(serverAddr, token, clientID, publicKey string) error { - endpoint := serverAddr + "/revoke/" + clientID - endpoint += "?peer_public_key=" + publicKey +func CallZauthRevoke(serverAddr, token, clientID, peerPublicKey string) error { + endpoint := serverAddr + "/revoke/" + clientID + "?peer_public_key=" + peerPublicKey + req, err := http.NewRequest("POST", endpoint, nil) if err != nil { return errors.Wrap(err, "failed to create HTTP request") @@ -99,17 +162,6 @@ func CallZauthRevoke(serverAddr, token, clientID, publicKey string) error { return errors.Errorf("code: %d", resp.StatusCode) } - var rsp struct { - Result string `json:"result"` - } - if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { - return errors.Wrap(err, "failed to decode response body") - } - - if rsp.Result != "success" { - return errors.New("failed to setup zauth server") - } - return nil } @@ -138,55 +190,79 @@ func CallZauthDelete(serverAddr, token, clientID string) error { return errors.Errorf("code: %d", resp.StatusCode) } + return nil +} - var rsp struct { - Result string `json:"result"` +func CallZvaultNewWallet(serverAddr, token string) error { + endpoint := serverAddr + "/wallet" + + req, err := http.NewRequest("POST", endpoint, nil) + if err != nil { + return errors.Wrap(err, "failed to create HTTP request") } - if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { - return errors.Wrap(err, "failed to decode response body") + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Jwt-Token", token) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to send HTTP request") } + defer resp.Body.Close() - if rsp.Result != "success" { - return errors.New("failed to setup zauth server") + if resp.StatusCode != http.StatusOK { + errMsg, _ := io.ReadAll(resp.Body) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + } + + return errors.Errorf("code: %d", resp.StatusCode) } return nil } -type newWalletRequest struct { - Roles []string `json:"roles"` -} +func CallZvaultNewSplit(serverAddr, token, clientID string) error { + endpoint := serverAddr + "/key/" + clientID -func CallZvaultNewWalletString(serverAddr, token, clientID string, roles []string) (string, error) { - // Add your code here - endpoint := serverAddr + "/generate" - if clientID != "" { - endpoint = endpoint + "/" + clientID + req, err := http.NewRequest("POST", endpoint, nil) + if err != nil { + return errors.Wrap(err, "failed to create HTTP request") } - var body io.Reader + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Jwt-Token", token) - if roles != nil { - data, err := json.Marshal(newWalletRequest{ - Roles: roles, - }) - if err != nil { - return "", errors.Wrap(err, "failed to serialize request") + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to send HTTP request") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errMsg, _ := io.ReadAll(resp.Body) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - body = bytes.NewReader(data) + return errors.Errorf("code: %d", resp.StatusCode) } - req, err := http.NewRequest("POST", endpoint, body) + return nil +} + +func CallZvaultRetrieveRestrictions(serverAddr, token, peerPublicKey string) (string, error) { + endpoint := serverAddr + "/restrictions" + + req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("new wallet endpoint:", endpoint) - fmt.Println("new wallet: serverAddr:", serverAddr) - fmt.Println("new wallet: clientID:", clientID) - req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Peer-Public-Key", peerPublicKey) req.Header.Set("X-Jwt-Token", token) client := &http.Client{} @@ -213,8 +289,45 @@ func CallZvaultNewWalletString(serverAddr, token, clientID string, roles []strin return string(d), nil } -func CallZvaultStoreKeyString(serverAddr, token, privateKey string) (string, error) { - // Add your code here +func CallZvaultUpdateRestrictions(serverAddr, token, clientID, peerPublicKey string, restrictions []string) error { + endpoint := serverAddr + "/restrictions/" + clientID + + data, err := json.Marshal(updateRestrictionsRequest{ + Restrictions: restrictions, + }) + if err != nil { + return errors.Wrap(err, "failed to serialize request") + } + + req, err := http.NewRequest("PUT", endpoint, bytes.NewReader(data)) + if err != nil { + return errors.Wrap(err, "failed to create HTTP request") + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Peer-Public-Key", peerPublicKey) + req.Header.Set("X-Jwt-Token", token) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to send HTTP request") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errMsg, _ := io.ReadAll(resp.Body) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + } + + return errors.Errorf("code: %d", resp.StatusCode) + } + + return nil +} + +func CallZvaultStoreKeyString(serverAddr, token, privateKey string) error { endpoint := serverAddr + "/store" reqData := struct { @@ -229,57 +342,43 @@ func CallZvaultStoreKeyString(serverAddr, token, privateKey string) (string, err err := encoder.Encode(reqData) if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") + return errors.Wrap(err, "failed to create HTTP request") } var req *http.Request req, err = http.NewRequest("POST", endpoint, &buff) if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") + return errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /store:", endpoint) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - fmt.Println(req) - client := &http.Client{} resp, err := client.Do(req) if err != nil { - fmt.Println(err.Error()) - - return "", errors.Wrap(err, "failed to send HTTP request") + return errors.Wrap(err, "failed to send HTTP request") } + defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errMsg, _ := io.ReadAll(resp.Body) if len(errMsg) > 0 { - return "", errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - return "", errors.Errorf("code: %d", resp.StatusCode) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") + return errors.Errorf("code: %d", resp.StatusCode) } - return string(d), nil + return nil } func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) { - // Add your code here endpoint := fmt.Sprintf("%s/keys/%s", serverAddr, clientID) req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -304,14 +403,13 @@ func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) } func CallZvaultDeletePrimaryKey(serverAddr, token, clientID string) error { - // Add your code here endpoint := serverAddr + "/delete/" + clientID + req, err := http.NewRequest("POST", endpoint, nil) if err != nil { return errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /delete:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -343,7 +441,6 @@ func CallZvaultRevokeKey(serverAddr, token, clientID, publicKey string) error { return errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /revoke:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -375,7 +472,6 @@ func CallZvaultRetrieveWallets(serverAddr, token string) (string, error) { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -407,7 +503,6 @@ func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -434,7 +529,6 @@ func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { // ZauthSignTxn returns a function that sends a txn signing request to the zauth server func ZauthSignTxn(serverAddr string) sys.AuthorizeFunc { return func(msg string) (string, error) { - fmt.Println("zvault sign txn - in sign txn...") req, err := http.NewRequest("POST", serverAddr+"/sign/txn", bytes.NewBuffer([]byte(msg))) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") @@ -503,13 +597,3 @@ func ZauthAuthCommon(serverAddr string) sys.AuthorizeFunc { return string(d), nil } } - -type AuthMessage struct { - Hash string `json:"hash"` - Signature string `json:"signature"` - ClientID string `json:"client_id"` -} - -type AuthResponse struct { - Sig string `json:"sig"` -} From 2d328b511617f03b55b5cf34df1c3b9a03abc621 Mon Sep 17 00:00:00 2001 From: harsh4723 Date: Fri, 1 Nov 2024 12:33:20 +0530 Subject: [PATCH 045/107] revert: zauth changes --- zcncore/zauth.go | 318 +++++++++++++++++------------------------------ 1 file changed, 117 insertions(+), 201 deletions(-) diff --git a/zcncore/zauth.go b/zcncore/zauth.go index 7e5b97908..fdb240a80 100644 --- a/zcncore/zauth.go +++ b/zcncore/zauth.go @@ -12,132 +12,69 @@ import ( "github.com/pkg/errors" ) -// AvailableRestrictions represents supported restrictions mapping. -var AvailableRestrictions = map[string][]string{ - "token_transfers": {"transfer"}, - "allocation_file_operations": { - "read_redeem", - "commit_connection", - }, - "allocation_storage_operations": { - "new_allocation_request", - "update_allocation_request", - "finalize_allocation", - "cancel_allocation", - "add_free_storage_assigner", - "free_allocation_request", - }, - "allocation_token_operations": { - "read_pool_lock", - "read_pool_unlock", - "write_pool_lock", - }, - "storage_rewards": { - "collect_reward", - "stake_pool_lock", - "stake_pool_unlock", - }, - "storage_operations": { - "challenge_response", - "add_validator", - "add_blobber", - "blobber_health_check", - "validator_health_check", - }, - "storage_management": { - "kill_blobber", - "kill_validator", - "shutdown_blobber", - "shutdown_validator", - "update_blobber_settings", - "update_validator_settings", - }, - "miner_operations": { - "add_miner", - "add_sharder", - "miner_health_check", - "sharder_health_check", - "contributeMpk", - "shareSignsOrShares", - "wait", - "sharder_keep", - }, - "miner_management_operations": { - "delete_miner", - "delete_sharder", - "update_miner_settings", - "kill_miner", - "kill_sharder", - }, - "miner_financial_operations": { - "addToDelegatePool", - "deleteFromDelegatePool", - "collect_reward", - }, - "token_bridging": { - "mint", - "burn", - }, - "authorizer_management_operations": { - "delete-authorizer", - }, - "authorizer_operations": { - "add-authorizer", - "authorizer-health-check", - "add-to-delegate-pool", - "delete-from-delegate-pool", - }, +// SplitWallet represents wallet info for split wallet +// The client id and client key are the same as the primary wallet client id and client key +type SplitWallet struct { + ClientID string `json:"client_id"` + ClientKey string `json:"client_key"` + PublicKey string `json:"public_key"` + PrivateKey string `json:"private_key"` + PeerPublicKey string `json:"peer_public_key"` + Roles []string `json:"roles"` + IsRevoked bool `json:"is_revoked"` + ExpiredAt int64 `json:"expired_at"` } -type updateRestrictionsRequest struct { - Restrictions []string `json:"restrictions"` -} - -type AuthMessage struct { - Hash string `json:"hash"` - Signature string `json:"signature"` - ClientID string `json:"client_id"` -} - -type AuthResponse struct { - Sig string `json:"sig"` -} - -func CallZauthRetreiveKey(serverAddr, token, clientID, peerPublicKey string) (string, error) { - endpoint := fmt.Sprintf("%s/key/%s", serverAddr, clientID) +// CallZauthSetup calls the zauth setup endpoint +func CallZauthSetup(serverAddr string, token string, splitWallet SplitWallet) error { + // Add your code here + endpoint := serverAddr + "/setup" + wData, err := json.Marshal(splitWallet) + if err != nil { + return errors.Wrap(err, "failed to marshal split wallet") + } - req, err := http.NewRequest("GET", endpoint, nil) + req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(wData)) if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") + return errors.Wrap(err, "failed to create HTTP request") } req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", peerPublicKey) req.Header.Set("X-Jwt-Token", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") + return errors.Wrap(err, "failed to send HTTP request") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errMsg, _ := io.ReadAll(resp.Body) - return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + } + + return errors.Errorf("code: %d", resp.StatusCode) } - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") + var rsp struct { + Result string `json:"result"` + } + if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { + return errors.Wrap(err, "failed to decode response body") } - return string(d), nil -} + if rsp.Result != "success" { + return errors.New("failed to setup zauth server") + } -func CallZauthRevoke(serverAddr, token, clientID, peerPublicKey string) error { - endpoint := serverAddr + "/revoke/" + clientID + "?peer_public_key=" + peerPublicKey + return nil +} +func CallZauthRevoke(serverAddr, token, clientID, publicKey string) error { + endpoint := serverAddr + "/revoke/" + clientID + endpoint += "?peer_public_key=" + publicKey req, err := http.NewRequest("POST", endpoint, nil) if err != nil { return errors.Wrap(err, "failed to create HTTP request") @@ -162,6 +99,17 @@ func CallZauthRevoke(serverAddr, token, clientID, peerPublicKey string) error { return errors.Errorf("code: %d", resp.StatusCode) } + var rsp struct { + Result string `json:"result"` + } + if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { + return errors.Wrap(err, "failed to decode response body") + } + + if rsp.Result != "success" { + return errors.New("failed to setup zauth server") + } + return nil } @@ -190,79 +138,55 @@ func CallZauthDelete(serverAddr, token, clientID string) error { return errors.Errorf("code: %d", resp.StatusCode) } - return nil -} -func CallZvaultNewWallet(serverAddr, token string) error { - endpoint := serverAddr + "/wallet" - - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") + var rsp struct { + Result string `json:"result"` } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") + if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { + return errors.Wrap(err, "failed to decode response body") } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) + if rsp.Result != "success" { + return errors.New("failed to setup zauth server") } return nil } -func CallZvaultNewSplit(serverAddr, token, clientID string) error { - endpoint := serverAddr + "/key/" + clientID +type newWalletRequest struct { + Roles []string `json:"roles"` +} - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") +func CallZvaultNewWalletString(serverAddr, token, clientID string, roles []string) (string, error) { + // Add your code here + endpoint := serverAddr + "/generate" + if clientID != "" { + endpoint = endpoint + "/" + clientID } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) + var body io.Reader - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + if roles != nil { + data, err := json.Marshal(newWalletRequest{ + Roles: roles, + }) + if err != nil { + return "", errors.Wrap(err, "failed to serialize request") } - return errors.Errorf("code: %d", resp.StatusCode) + body = bytes.NewReader(data) } - return nil -} - -func CallZvaultRetrieveRestrictions(serverAddr, token, peerPublicKey string) (string, error) { - endpoint := serverAddr + "/restrictions" - - req, err := http.NewRequest("GET", endpoint, nil) + req, err := http.NewRequest("POST", endpoint, body) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("new wallet endpoint:", endpoint) + fmt.Println("new wallet: serverAddr:", serverAddr) + fmt.Println("new wallet: clientID:", clientID) + req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", peerPublicKey) req.Header.Set("X-Jwt-Token", token) client := &http.Client{} @@ -289,45 +213,8 @@ func CallZvaultRetrieveRestrictions(serverAddr, token, peerPublicKey string) (st return string(d), nil } -func CallZvaultUpdateRestrictions(serverAddr, token, clientID, peerPublicKey string, restrictions []string) error { - endpoint := serverAddr + "/restrictions/" + clientID - - data, err := json.Marshal(updateRestrictionsRequest{ - Restrictions: restrictions, - }) - if err != nil { - return errors.Wrap(err, "failed to serialize request") - } - - req, err := http.NewRequest("PUT", endpoint, bytes.NewReader(data)) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", peerPublicKey) - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - return nil -} - -func CallZvaultStoreKeyString(serverAddr, token, privateKey string) error { +func CallZvaultStoreKeyString(serverAddr, token, privateKey string) (string, error) { + // Add your code here endpoint := serverAddr + "/store" reqData := struct { @@ -342,43 +229,57 @@ func CallZvaultStoreKeyString(serverAddr, token, privateKey string) error { err := encoder.Encode(reqData) if err != nil { - return errors.Wrap(err, "failed to create HTTP request") + return "", errors.Wrap(err, "failed to create HTTP request") } var req *http.Request req, err = http.NewRequest("POST", endpoint, &buff) if err != nil { - return errors.Wrap(err, "failed to create HTTP request") + return "", errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("call zvault /store:", endpoint) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Jwt-Token", token) + + fmt.Println(req) + client := &http.Client{} resp, err := client.Do(req) if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } + fmt.Println(err.Error()) + return "", errors.Wrap(err, "failed to send HTTP request") + } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errMsg, _ := io.ReadAll(resp.Body) if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + return "", errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - return errors.Errorf("code: %d", resp.StatusCode) + return "", errors.Errorf("code: %d", resp.StatusCode) } - return nil + d, err := io.ReadAll(resp.Body) + if err != nil { + return "", errors.Wrap(err, "failed to read response body") + } + + return string(d), nil } func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) { + // Add your code here endpoint := fmt.Sprintf("%s/keys/%s", serverAddr, clientID) req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -403,13 +304,14 @@ func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) } func CallZvaultDeletePrimaryKey(serverAddr, token, clientID string) error { + // Add your code here endpoint := serverAddr + "/delete/" + clientID - req, err := http.NewRequest("POST", endpoint, nil) if err != nil { return errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("call zvault /delete:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -441,6 +343,7 @@ func CallZvaultRevokeKey(serverAddr, token, clientID, publicKey string) error { return errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("call zvault /revoke:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -472,6 +375,7 @@ func CallZvaultRetrieveWallets(serverAddr, token string) (string, error) { return "", errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -503,6 +407,7 @@ func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { return "", errors.Wrap(err, "failed to create HTTP request") } + fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -529,6 +434,7 @@ func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { // ZauthSignTxn returns a function that sends a txn signing request to the zauth server func ZauthSignTxn(serverAddr string) sys.AuthorizeFunc { return func(msg string) (string, error) { + fmt.Println("zvault sign txn - in sign txn...") req, err := http.NewRequest("POST", serverAddr+"/sign/txn", bytes.NewBuffer([]byte(msg))) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") @@ -597,3 +503,13 @@ func ZauthAuthCommon(serverAddr string) sys.AuthorizeFunc { return string(d), nil } } + +type AuthMessage struct { + Hash string `json:"hash"` + Signature string `json:"signature"` + ClientID string `json:"client_id"` +} + +type AuthResponse struct { + Sig string `json:"sig"` +} From 9d17c71dfbd95138b9d2067bfc91cd34dec4949b Mon Sep 17 00:00:00 2001 From: harsh4723 Date: Fri, 1 Nov 2024 12:53:47 +0530 Subject: [PATCH 046/107] fix: zauth file --- zcncore/zauth.go | 317 ++++++++++++++++++++++++++++++----------------- 1 file changed, 200 insertions(+), 117 deletions(-) diff --git a/zcncore/zauth.go b/zcncore/zauth.go index fdb240a80..82e790055 100644 --- a/zcncore/zauth.go +++ b/zcncore/zauth.go @@ -12,69 +12,131 @@ import ( "github.com/pkg/errors" ) -// SplitWallet represents wallet info for split wallet -// The client id and client key are the same as the primary wallet client id and client key -type SplitWallet struct { - ClientID string `json:"client_id"` - ClientKey string `json:"client_key"` - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` - PeerPublicKey string `json:"peer_public_key"` - Roles []string `json:"roles"` - IsRevoked bool `json:"is_revoked"` - ExpiredAt int64 `json:"expired_at"` +// AvailableRestrictions represents supported restrictions mapping. +var AvailableRestrictions = map[string][]string{ + "token_transfers": {"transfer"}, + "allocation_file_operations": { + "read_redeem", + "commit_connection", + }, + "allocation_storage_operations": { + "new_allocation_request", + "update_allocation_request", + "finalize_allocation", + "cancel_allocation", + "add_free_storage_assigner", + "free_allocation_request", + }, + "allocation_token_operations": { + "read_pool_lock", + "read_pool_unlock", + "write_pool_lock", + }, + "storage_rewards": { + "collect_reward", + "stake_pool_lock", + "stake_pool_unlock", + }, + "storage_operations": { + "challenge_response", + "add_validator", + "add_blobber", + "blobber_health_check", + "validator_health_check", + }, + "storage_management": { + "kill_blobber", + "kill_validator", + "shutdown_blobber", + "shutdown_validator", + "update_blobber_settings", + "update_validator_settings", + }, + "miner_operations": { + "add_miner", + "add_sharder", + "miner_health_check", + "sharder_health_check", + "contributeMpk", + "shareSignsOrShares", + "wait", + "sharder_keep", + }, + "miner_management_operations": { + "delete_miner", + "delete_sharder", + "update_miner_settings", + "kill_miner", + "kill_sharder", + }, + "miner_financial_operations": { + "addToDelegatePool", + "deleteFromDelegatePool", + "collect_reward", + }, + "token_bridging": { + "mint", + "burn", + }, + "authorizer_management_operations": { + "delete-authorizer", + }, + "authorizer_operations": { + "add-authorizer", + "authorizer-health-check", + "add-to-delegate-pool", + "delete-from-delegate-pool", + }, } -// CallZauthSetup calls the zauth setup endpoint -func CallZauthSetup(serverAddr string, token string, splitWallet SplitWallet) error { - // Add your code here - endpoint := serverAddr + "/setup" - wData, err := json.Marshal(splitWallet) - if err != nil { - return errors.Wrap(err, "failed to marshal split wallet") - } +type updateRestrictionsRequest struct { + Restrictions []string `json:"restrictions"` +} + +type AuthMessage struct { + Hash string `json:"hash"` + Signature string `json:"signature"` + ClientID string `json:"client_id"` +} - req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(wData)) +type AuthResponse struct { + Sig string `json:"sig"` +} + +func CallZauthRetreiveKey(serverAddr, token, clientID, peerPublicKey string) (string, error) { + endpoint := fmt.Sprintf("%s/key/%s", serverAddr, clientID) + + req, err := http.NewRequest("GET", endpoint, nil) if err != nil { - return errors.Wrap(err, "failed to create HTTP request") + return "", errors.Wrap(err, "failed to create HTTP request") } req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Peer-Public-Key", peerPublicKey) req.Header.Set("X-Jwt-Token", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { - return errors.Wrap(err, "failed to send HTTP request") + return "", errors.Wrap(err, "failed to send HTTP request") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - var rsp struct { - Result string `json:"result"` - } - if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { - return errors.Wrap(err, "failed to decode response body") + return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - if rsp.Result != "success" { - return errors.New("failed to setup zauth server") + d, err := io.ReadAll(resp.Body) + if err != nil { + return "", errors.Wrap(err, "failed to read response body") } - return nil + return string(d), nil } -func CallZauthRevoke(serverAddr, token, clientID, publicKey string) error { - endpoint := serverAddr + "/revoke/" + clientID - endpoint += "?peer_public_key=" + publicKey +func CallZauthRevoke(serverAddr, token, clientID, peerPublicKey string) error { + endpoint := serverAddr + "/revoke/" + clientID + "?peer_public_key=" + peerPublicKey req, err := http.NewRequest("POST", endpoint, nil) if err != nil { return errors.Wrap(err, "failed to create HTTP request") @@ -99,17 +161,6 @@ func CallZauthRevoke(serverAddr, token, clientID, publicKey string) error { return errors.Errorf("code: %d", resp.StatusCode) } - var rsp struct { - Result string `json:"result"` - } - if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { - return errors.Wrap(err, "failed to decode response body") - } - - if rsp.Result != "success" { - return errors.New("failed to setup zauth server") - } - return nil } @@ -138,55 +189,79 @@ func CallZauthDelete(serverAddr, token, clientID string) error { return errors.Errorf("code: %d", resp.StatusCode) } + return nil +} + +func CallZvaultNewWallet(serverAddr, token string) error { + endpoint := serverAddr + "/wallet" - var rsp struct { - Result string `json:"result"` + req, err := http.NewRequest("POST", endpoint, nil) + if err != nil { + return errors.Wrap(err, "failed to create HTTP request") } - if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil { - return errors.Wrap(err, "failed to decode response body") + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Jwt-Token", token) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to send HTTP request") } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errMsg, _ := io.ReadAll(resp.Body) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + } - if rsp.Result != "success" { - return errors.New("failed to setup zauth server") + return errors.Errorf("code: %d", resp.StatusCode) } return nil } -type newWalletRequest struct { - Roles []string `json:"roles"` -} +func CallZvaultNewSplit(serverAddr, token, clientID string) error { + endpoint := serverAddr + "/key/" + clientID -func CallZvaultNewWalletString(serverAddr, token, clientID string, roles []string) (string, error) { - // Add your code here - endpoint := serverAddr + "/generate" - if clientID != "" { - endpoint = endpoint + "/" + clientID + req, err := http.NewRequest("POST", endpoint, nil) + if err != nil { + return errors.Wrap(err, "failed to create HTTP request") } - var body io.Reader + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Jwt-Token", token) - if roles != nil { - data, err := json.Marshal(newWalletRequest{ - Roles: roles, - }) - if err != nil { - return "", errors.Wrap(err, "failed to serialize request") + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to send HTTP request") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errMsg, _ := io.ReadAll(resp.Body) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - body = bytes.NewReader(data) + return errors.Errorf("code: %d", resp.StatusCode) } - req, err := http.NewRequest("POST", endpoint, body) + return nil +} + +func CallZvaultRetrieveRestrictions(serverAddr, token, peerPublicKey string) (string, error) { + endpoint := serverAddr + "/restrictions" + + req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("new wallet endpoint:", endpoint) - fmt.Println("new wallet: serverAddr:", serverAddr) - fmt.Println("new wallet: clientID:", clientID) - req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Peer-Public-Key", peerPublicKey) req.Header.Set("X-Jwt-Token", token) client := &http.Client{} @@ -213,8 +288,45 @@ func CallZvaultNewWalletString(serverAddr, token, clientID string, roles []strin return string(d), nil } -func CallZvaultStoreKeyString(serverAddr, token, privateKey string) (string, error) { - // Add your code here +func CallZvaultUpdateRestrictions(serverAddr, token, clientID, peerPublicKey string, restrictions []string) error { + endpoint := serverAddr + "/restrictions/" + clientID + + data, err := json.Marshal(updateRestrictionsRequest{ + Restrictions: restrictions, + }) + if err != nil { + return errors.Wrap(err, "failed to serialize request") + } + + req, err := http.NewRequest("PUT", endpoint, bytes.NewReader(data)) + if err != nil { + return errors.Wrap(err, "failed to create HTTP request") + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Peer-Public-Key", peerPublicKey) + req.Header.Set("X-Jwt-Token", token) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to send HTTP request") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errMsg, _ := io.ReadAll(resp.Body) + if len(errMsg) > 0 { + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + } + + return errors.Errorf("code: %d", resp.StatusCode) + } + + return nil +} + +func CallZvaultStoreKeyString(serverAddr, token, privateKey string) error { endpoint := serverAddr + "/store" reqData := struct { @@ -229,57 +341,43 @@ func CallZvaultStoreKeyString(serverAddr, token, privateKey string) (string, err err := encoder.Encode(reqData) if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") + return errors.Wrap(err, "failed to create HTTP request") } var req *http.Request req, err = http.NewRequest("POST", endpoint, &buff) if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") + return errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /store:", endpoint) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - fmt.Println(req) - client := &http.Client{} resp, err := client.Do(req) if err != nil { - fmt.Println(err.Error()) - - return "", errors.Wrap(err, "failed to send HTTP request") + return errors.Wrap(err, "failed to send HTTP request") } + defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errMsg, _ := io.ReadAll(resp.Body) if len(errMsg) > 0 { - return "", errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) + return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) } - return "", errors.Errorf("code: %d", resp.StatusCode) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") + return errors.Errorf("code: %d", resp.StatusCode) } - return string(d), nil + return nil } func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) { - // Add your code here endpoint := fmt.Sprintf("%s/keys/%s", serverAddr, clientID) req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -304,14 +402,13 @@ func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) } func CallZvaultDeletePrimaryKey(serverAddr, token, clientID string) error { - // Add your code here endpoint := serverAddr + "/delete/" + clientID + req, err := http.NewRequest("POST", endpoint, nil) if err != nil { return errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /delete:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -343,7 +440,6 @@ func CallZvaultRevokeKey(serverAddr, token, clientID, publicKey string) error { return errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /revoke:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -375,7 +471,6 @@ func CallZvaultRetrieveWallets(serverAddr, token string) (string, error) { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -407,7 +502,6 @@ func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { return "", errors.Wrap(err, "failed to create HTTP request") } - fmt.Println("call zvault /keys:", endpoint) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Jwt-Token", token) @@ -434,7 +528,6 @@ func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { // ZauthSignTxn returns a function that sends a txn signing request to the zauth server func ZauthSignTxn(serverAddr string) sys.AuthorizeFunc { return func(msg string) (string, error) { - fmt.Println("zvault sign txn - in sign txn...") req, err := http.NewRequest("POST", serverAddr+"/sign/txn", bytes.NewBuffer([]byte(msg))) if err != nil { return "", errors.Wrap(err, "failed to create HTTP request") @@ -503,13 +596,3 @@ func ZauthAuthCommon(serverAddr string) sys.AuthorizeFunc { return string(d), nil } } - -type AuthMessage struct { - Hash string `json:"hash"` - Signature string `json:"signature"` - ClientID string `json:"client_id"` -} - -type AuthResponse struct { - Sig string `json:"sig"` -} From 655bacd5c2de18188a22b9c0e48d273697919cf4 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Fri, 8 Nov 2024 14:03:36 +0530 Subject: [PATCH 047/107] change cdn and wasm path --- .github/workflows/build-sdks.yml | 10 +++++----- .github/workflows/tests.yml | 6 +++--- go.mod | 2 +- wasmsdk/jsbridge/template_data.go | 2 +- wasmsdk/jsbridge/webworker.go | 2 +- wasmsdk/jsbridge/zcnworker.js.tpl | 2 +- wasmsdk/proxy.go | 1 + 7 files changed, 13 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index 6bfb5431d..06285935b 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -27,7 +27,7 @@ jobs: - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.22 + go-version: 1.22.5 - name: Clean build run: make clean-mobilesdk @@ -99,7 +99,7 @@ jobs: - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.22 + go-version: 1.22.5 - name: Install deps run: | @@ -202,7 +202,7 @@ jobs: - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.22 + go-version: 1.22.5 - name: Clean build run: make clean-mobilesdk @@ -274,7 +274,7 @@ jobs: - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.22 + go-version: 1.22.5 - name: Install deps run: | @@ -338,7 +338,7 @@ jobs: - name: Set up Go 1.x uses: actions/setup-go@v3 with: - go-version: 1.21.5 + go-version: 1.22.5 - name: Checkout uses: actions/checkout@v2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 989856a3c..b6e48270a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -26,7 +26,7 @@ jobs: - name: Set up Go 1.x uses: actions/setup-go@v3 with: - go-version: 1.21.5 + go-version: 1.22.5 - uses: actions/checkout@v3 @@ -51,7 +51,7 @@ jobs: - name: Set up Go 1.x uses: actions/setup-go@v3 with: - go-version: 1.21.5 + go-version: 1.22.5 - name: Install deps run: | @@ -170,7 +170,7 @@ jobs: - name: Set up Go 1.x uses: actions/setup-go@v3 with: - go-version: 1.21.5 + go-version: 1.22.5 - uses: actions/setup-node@v2 with: diff --git a/go.mod b/go.mod index 23081c36f..e26bef3a1 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/0chain/gosdk -go 1.21 +go 1.22.5 require ( github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 diff --git a/wasmsdk/jsbridge/template_data.go b/wasmsdk/jsbridge/template_data.go index cc3c2c7d7..c1723ff18 100644 --- a/wasmsdk/jsbridge/template_data.go +++ b/wasmsdk/jsbridge/template_data.go @@ -51,7 +51,7 @@ func buildJS(args, env []string, wasmPath string, tpl []byte) (string, error) { if suffix == "" { suffix = "dev" } - cdnPath := fmt.Sprintf("https://d2os1u2xwjukgr.cloudfront.net/%s/zcn.wasm", suffix) + cdnPath := fmt.Sprintf("https://webapps-staticfiles.s3.us-east-2.amazonaws.com/%s/enterprise-zcn.wasm", suffix) data := templateData{ Path: cdnPath, Args: args, diff --git a/wasmsdk/jsbridge/webworker.go b/wasmsdk/jsbridge/webworker.go index d889de621..33d281ab7 100644 --- a/wasmsdk/jsbridge/webworker.go +++ b/wasmsdk/jsbridge/webworker.go @@ -81,7 +81,7 @@ func NewWasmWebWorker(blobberID, blobberURL, clientID, clientKey, peerPublicKey, "IS_SPLIT=" + strconv.FormatBool(isSplit), "MNEMONIC=" + mnemonic, "ZAUTH_SERVER=" + gZauthServer}, - Path: "zcn.wasm", + Path: "enterprise-zcn.wasm", subscribers: make(map[string]chan worker.MessageEvent), } diff --git a/wasmsdk/jsbridge/zcnworker.js.tpl b/wasmsdk/jsbridge/zcnworker.js.tpl index 2f4d3d4ac..d082ff1d9 100644 --- a/wasmsdk/jsbridge/zcnworker.js.tpl +++ b/wasmsdk/jsbridge/zcnworker.js.tpl @@ -1,4 +1,4 @@ -importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.21.5/misc/wasm/wasm_exec.js','https://cdn.jsdelivr.net/gh/herumi/bls-wasm@v1.1.1/browser/bls.js'); +importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.22.5/misc/wasm/wasm_exec.js','https://cdn.jsdelivr.net/gh/herumi/bls-wasm@v1.1.1/browser/bls.js'); const go = new Go(); go.argv = {{.ArgsToJS}} diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 555e7125f..7222400d8 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -350,6 +350,7 @@ func main() { } if mode != "" { + fmt.Println("enterprise wasm sdk") respChan := make(chan string, 1) jsProxy := window.Get("__zcn_worker_wasm__") if !(jsProxy.IsNull() || jsProxy.IsUndefined()) { From f967f8a2c711190996224671e08050f9c8a274f0 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Fri, 8 Nov 2024 14:12:19 +0530 Subject: [PATCH 048/107] update go version in make wasm --- .github/workflows/build-sdks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index 06285935b..0014df5db 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -349,7 +349,7 @@ jobs: sudo apt-get -y install build-essential nghttp2 libnghttp2-dev libssl-dev wget - name: Build - run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.21.5 make wasm-build + run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.22.5 make wasm-build - name: 'Upload Artifact' uses: actions/upload-artifact@v3 From 2f063036fe898ab6ab62c5f3091239df0b9a8e04 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 14 Nov 2024 10:56:20 +0530 Subject: [PATCH 049/107] add method for wasm type --- wasmsdk/proxy.go | 1 + wasmsdk/sdk.go | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 7222400d8..ebdd06cd2 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -216,6 +216,7 @@ func main() { "getLookupHash": getLookupHash, "createThumbnail": createThumbnail, "makeSCRestAPICall": makeSCRestAPICall, + "getWasmType": getWasmType, //blobber "delete": Delete, diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 5592ad537..b603c02e9 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -69,6 +69,10 @@ func getVersion() string { return sdk.GetVersion() } +func getWasmType() string { + return "enterprise" +} + var sdkLogger *logger.Logger var zcnLogger *logger.Logger var logEnabled = false From d8f100cd86d5ea80df79703178ccb99bf7ed9324 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 14 Nov 2024 20:19:36 +0530 Subject: [PATCH 050/107] set wasm type in window object --- wasmsdk/proxy.go | 1 + 1 file changed, 1 insertion(+) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index ebdd06cd2..b73c573e4 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -341,6 +341,7 @@ func main() { fmt.Println("__wasm_initialized__ = true;") zcn.Set("__wasm_initialized__", true) + zcn.Set("wasmType", "enterprise") } else { PrintError("__zcn_wasm__.sdk is not installed yet") } From 2f3d0401a091fd846afe05227fc56b9dde520347 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Tue, 26 Nov 2024 00:05:07 +0530 Subject: [PATCH 051/107] merge file write and callback changes --- wasmsdk/blobber.go | 64 +++++++++--- wasmsdk/jsbridge/file_writer.go | 114 +++++++++++++++++++--- zboxcore/sdk/chunked_upload.go | 2 +- zboxcore/sdk/chunked_upload_process_js.go | 10 +- zboxcore/sdk/copyworker.go | 10 +- zboxcore/sdk/moveworker.go | 6 +- zboxcore/sdk/renameworker.go | 6 +- 7 files changed, 171 insertions(+), 41 deletions(-) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 3f4add853..8047507ee 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -998,8 +998,9 @@ func upload(allocationID, remotePath string, fileBytes, thumbnailBytes []byte, w // - 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 +// - writeChunkFuncName : callback function name to write the chunk, if empty the function will return arrayBuffer otherwise will return nil -func downloadBlocks(allocId string, remotePath, authTicket, lookupHash string, startBlock, endBlock int64) ([]byte, error) { +func downloadBlocks(allocId, remotePath, authTicket, lookupHash, writeChunkFuncName string, startBlock, endBlock int64) ([]byte, error) { if len(remotePath) == 0 && len(authTicket) == 0 { return nil, RequiredArg("remotePath/authTicket") @@ -1017,37 +1018,58 @@ func downloadBlocks(allocId string, remotePath, authTicket, lookupHash string, s statusBar = &StatusBar{wg: wg, totalBytesMap: make(map[string]int)} ) - pathHash := encryption.FastHash(remotePath) - fs, err := sys.Files.Open(pathHash) - if err != nil { - return nil, fmt.Errorf("could not open local file: %v", err) + if lookupHash == "" { + lookupHash = getLookupHash(allocId, remotePath) } - mf, _ := fs.(*sys.MemFile) - if mf == nil { - return nil, fmt.Errorf("invalid memfile") - } + var fh sys.File + if writeChunkFuncName == "" { + pathHash := encryption.FastHash(fmt.Sprintf("%s:%d:%d", lookupHash, startBlock, endBlock)) + fs, err := sys.Files.Open(pathHash) + if err != nil { + return nil, fmt.Errorf("could not open local file: %v", err) + } - defer sys.Files.Remove(pathHash) //nolint + mf, _ := fs.(*sys.MemFile) + if mf == nil { + return nil, fmt.Errorf("invalid memfile") + } + fh = mf + defer sys.Files.Remove(pathHash) //nolint + } else { + fh = jsbridge.NewFileCallbackWriter(writeChunkFuncName) + } wg.Add(1) if authTicket != "" { - err = alloc.DownloadByBlocksToFileHandlerFromAuthTicket(mf, authTicket, lookupHash, startBlock, endBlock, 100, remotePath, false, statusBar, true) + err = alloc.DownloadByBlocksToFileHandlerFromAuthTicket(fh, authTicket, lookupHash, startBlock, endBlock, 100, remotePath, false, statusBar, true, sdk.WithFileCallback( + func() { + fh.Close() //nolint:errcheck + }, + )) } else { err = alloc.DownloadByBlocksToFileHandler( - mf, + fh, remotePath, startBlock, endBlock, 100, false, - statusBar, true) + statusBar, true, sdk.WithFileCallback( + func() { + fh.Close() //nolint:errcheck + }, + )) } if err != nil { return nil, err } wg.Wait() - return mf.Buffer, nil + var buf []byte + if mf, ok := fh.(*sys.MemFile); ok { + buf = mf.Buffer + } + return buf, nil } // getBlobbers get list of active blobbers, and format them as array json string @@ -1086,7 +1108,19 @@ func repairAllocation(allocationID, callbackFuncName string) error { return err } wg.Wait() - return statusBar.err + if statusBar.err != nil { + fmt.Println("Error in repair allocation: ", statusBar.err) + return statusBar.err + } + status, _, err := alloc.CheckAllocStatus() + if err != nil { + return err + } + if status == sdk.Repair || status == sdk.Broken { + fmt.Println("allocation repair failed") + return errors.New("allocation repair failed") + } + return nil } // checkAllocStatus check the status of the allocation, either it is ok, needs repair or broken diff --git a/wasmsdk/jsbridge/file_writer.go b/wasmsdk/jsbridge/file_writer.go index 21b0e17b2..e265117fa 100644 --- a/wasmsdk/jsbridge/file_writer.go +++ b/wasmsdk/jsbridge/file_writer.go @@ -5,9 +5,11 @@ package jsbridge import ( "errors" - "io" "io/fs" "syscall/js" + + "github.com/0chain/gosdk/core/common" + "github.com/valyala/bytebufferpool" ) type FileWriter struct { @@ -31,29 +33,42 @@ func (w *FileWriter) Write(p []byte) (int, error) { //copy bytes to buf if w.bufWriteOffset+len(p) > len(w.buf) { - w.writeError = true - return 0, io.ErrShortWrite + err := w.flush() + if err != nil { + return 0, err + } } n := copy(w.buf[w.bufWriteOffset:], p) w.bufWriteOffset += n if w.bufWriteOffset == len(w.buf) { //write to file - if w.bufLen != len(w.buf) { - w.bufLen = len(w.buf) - w.uint8Array = js.Global().Get("Uint8Array").New(w.bufLen) + err := w.flush() + if err != nil { + return 0, err } - js.CopyBytesToJS(w.uint8Array, w.buf) - _, err := Await(w.writableStream.Call("write", w.uint8Array)) - if len(err) > 0 && !err[0].IsNull() { - w.writeError = true - return 0, errors.New("file_writer: " + err[0].String()) - } - //reset buffer - w.bufWriteOffset = 0 } return len(p), nil } +func (w *FileWriter) flush() error { + if w.bufWriteOffset == 0 { + return nil + } + if w.bufLen != w.bufWriteOffset { + w.bufLen = w.bufWriteOffset + w.uint8Array = js.Global().Get("Uint8Array").New(w.bufLen) + } + js.CopyBytesToJS(w.uint8Array, w.buf[:w.bufWriteOffset]) + _, err := Await(w.writableStream.Call("write", w.uint8Array)) + if len(err) > 0 && !err[0].IsNull() { + w.writeError = true + return errors.New("file_writer: " + err[0].String()) + } + //reset buffer + w.bufWriteOffset = 0 + return nil +} + // func (w *FileWriter) WriteAt(p []byte, offset int64) (int, error) { // uint8Array := js.Global().Get("Uint8Array").New(len(p)) // js.CopyBytesToJS(uint8Array, p) @@ -148,3 +163,74 @@ func NewFileWriterFromHandle(dirHandler js.Value, name string) (*FileWriter, err fileHandle: fileHandler[0], }, nil } + +type FileCallbackWriter struct { + writeChunk js.Value + buf []byte + offset int64 +} + +const bufCallbackCap = 4 * 1024 * 1024 //4MB + +func NewFileCallbackWriter(writeChunkFuncName string) *FileCallbackWriter { + writeChunk := js.Global().Get(writeChunkFuncName) + return &FileCallbackWriter{ + writeChunk: writeChunk, + } +} + +func (wc *FileCallbackWriter) Write(p []byte) (int, error) { + if len(wc.buf) == 0 { + buff := common.MemPool.Get() + if cap(buff.B) < bufCallbackCap { + buff.B = make([]byte, 0, bufCallbackCap) + } + wc.buf = buff.B + } + if len(wc.buf)+len(p) > cap(wc.buf) { + uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) + js.CopyBytesToJS(uint8Array, wc.buf) + _, err := Await(wc.writeChunk.Invoke(uint8Array, wc.offset)) + if len(err) > 0 && !err[0].IsNull() { + return 0, errors.New("file_writer: " + err[0].String()) + } + wc.offset += int64(len(wc.buf)) + wc.buf = wc.buf[:0] + } + wc.buf = append(wc.buf, p...) + return len(p), nil +} + +func (wc *FileCallbackWriter) Close() error { + if len(wc.buf) > 0 { + uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) + js.CopyBytesToJS(uint8Array, wc.buf) + _, err := Await(wc.writeChunk.Invoke(uint8Array, wc.offset)) + if len(err) > 0 && !err[0].IsNull() { + return errors.New("file_writer: " + err[0].String()) + } + wc.offset += int64(len(wc.buf)) + wc.buf = wc.buf[:0] + } + buff := &bytebufferpool.ByteBuffer{ + B: wc.buf, + } + common.MemPool.Put(buff) + return nil +} + +func (wc *FileCallbackWriter) Read(p []byte) (int, error) { + return 0, errors.New("file_writer: not supported") +} + +func (wc *FileCallbackWriter) Seek(offset int64, whence int) (int64, error) { + return 0, nil +} + +func (wc *FileCallbackWriter) Sync() error { + return nil +} + +func (wc *FileCallbackWriter) Stat() (fs.FileInfo, error) { + return nil, nil +} diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index b7018b98f..b6bea2232 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -696,7 +696,7 @@ func (su *ChunkedUpload) uploadToBlobbers(uploadData UploadData) error { if strings.Contains(err.Error(), "duplicate") { su.consensus.Done() errC := atomic.AddInt32(&su.addConsensus, 1) - if errC >= int32(su.consensus.consensusThresh) { + if errC > int32(su.consensus.fullconsensus-su.consensus.consensusThresh) { wgErrors <- err } return diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index 8b3af20de..bc8db2ef0 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -262,7 +262,7 @@ func (su *ChunkedUpload) listen(allEventChan []eventChanWorker, respChan chan er eventChan := allEventChan[pos] if eventChan.C == nil { errC := atomic.AddInt32(&errCount, 1) - if errC >= int32(su.consensus.consensusThresh) { + if errC > int32(su.consensus.fullconsensus-su.consensus.consensusThresh) { wgErrors <- thrown.New("upload_failed", "Upload failed. Worker event channel not found") } return @@ -272,7 +272,7 @@ func (su *ChunkedUpload) listen(allEventChan []eventChanWorker, respChan chan er if !ok { logger.Logger.Error("chan closed from: ", blobber.blobber.Baseurl) errC := atomic.AddInt32(&errCount, 1) - if errC >= int32(su.consensus.consensusThresh) { + if errC > int32(su.consensus.fullconsensus-su.consensus.consensusThresh) { if su.ctx.Err() != nil { wgErrors <- context.Cause(su.ctx) } else { @@ -284,7 +284,7 @@ func (su *ChunkedUpload) listen(allEventChan []eventChanWorker, respChan chan er msgType, data, err := jsbridge.GetMsgType(event) if err != nil { errC := atomic.AddInt32(&errCount, 1) - if errC >= int32(su.consensus.consensusThresh) { + if errC > int32(su.consensus.fullconsensus-su.consensus.consensusThresh) { wgErrors <- errors.Wrap(err, "could not get msgType") } return @@ -294,7 +294,7 @@ func (su *ChunkedUpload) listen(allEventChan []eventChanWorker, respChan chan er case "auth": if err := su.processWebWorkerAuthRequest(data, eventChan); err != nil { errC := atomic.AddInt32(&errCount, 1) - if errC >= int32(su.consensus.consensusThresh) { + if errC > int32(su.consensus.fullconsensus-su.consensus.consensusThresh) { wgErrors <- err } return @@ -306,7 +306,7 @@ func (su *ChunkedUpload) listen(allEventChan []eventChanWorker, respChan chan er isFinal, err = su.processWebWorkerUpload(data, blobber, pos) if err != nil { errC := atomic.AddInt32(&errCount, 1) - if errC >= int32(su.consensus.consensusThresh) { + if errC > int32(su.consensus.fullconsensus-su.consensus.consensusThresh) { wgErrors <- err } } else { diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 8113f6c77..9210e5593 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -247,11 +247,13 @@ func (req *CopyRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { }(int(pos)) } wg.Wait() - err := zboxutil.MajorError(blobberErrors) - if err != nil && strings.Contains(err.Error(), objAlreadyExists) && consensusRef.Type == fileref.DIRECTORY { - return nil, errNoChange + var err error + if !req.isConsensusOk() { + err = zboxutil.MajorError(blobberErrors) + if err != nil && strings.Contains(err.Error(), objAlreadyExists) && consensusRef.Type == fileref.DIRECTORY { + return nil, errNoChange + } } - return objectTreeRefs, err } diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 5b3298023..28af96d4d 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -260,7 +260,11 @@ func (req *MoveRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { }(int(pos)) } wg.Wait() - return objectTreeRefs, zboxutil.MajorError(blobberErrors) + var err error + if !req.isConsensusOk() { + err = zboxutil.MajorError(blobberErrors) + } + return objectTreeRefs, err } func (req *MoveRequest) ProcessMove() error { diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index c6eb19834..48deac045 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -263,7 +263,11 @@ func (req *RenameRequest) ProcessWithBlobbers() ([]fileref.RefEntity, error) { } req.wg.Wait() - return objectTreeRefs, zboxutil.MajorError(blobberErrors) + var err error + if !req.consensus.isConsensusOk() { + err = zboxutil.MajorError(blobberErrors) + } + return objectTreeRefs, err } func (req *RenameRequest) ProcessRename() error { From 0fe81ae5e6fb7145e2178d7055c5cba6c49a4d3e Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Tue, 26 Nov 2024 00:47:04 +0530 Subject: [PATCH 052/107] fix build --- wasmsdk/player_file.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wasmsdk/player_file.go b/wasmsdk/player_file.go index ccafe75f2..82de0d4c8 100644 --- a/wasmsdk/player_file.go +++ b/wasmsdk/player_file.go @@ -66,7 +66,7 @@ func (p *FilePlayer) download(startBlock int64) { } fmt.Println("start:", startBlock, "end:", endBlock, "numBlocks:", p.numBlocks, "total:", p.playlistFile.NumBlocks) - data, err := downloadBlocks(p.allocationObj.ID, p.remotePath, p.authTicket, p.lookupHash, startBlock, endBlock) + data, err := downloadBlocks(p.allocationObj.ID, p.remotePath, p.authTicket, p.lookupHash, "", startBlock, endBlock) // data, err := downloadBlocks2(int(startBlock), int(endBlock), p.allocationObj, p.remotePath) if err != nil { PrintError(err.Error()) From ed9fbc864fc985293a637e5cd41af3ba3ba194bb Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Tue, 3 Dec 2024 11:03:53 +0530 Subject: [PATCH 053/107] merge changes --- wasmsdk/blobber.go | 5 ++++- wasmsdk/jsbridge/file_writer.go | 11 ++++++++--- zboxcore/sdk/allocation.go | 5 +++++ zboxcore/sdk/downloadworker.go | 2 +- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 8047507ee..9e0c26462 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -1037,7 +1037,10 @@ func downloadBlocks(allocId, remotePath, authTicket, lookupHash, writeChunkFuncN fh = mf defer sys.Files.Remove(pathHash) //nolint } else { - fh = jsbridge.NewFileCallbackWriter(writeChunkFuncName) + fh = jsbridge.NewFileCallbackWriter(writeChunkFuncName, lookupHash) + if fh == nil { + return nil, fmt.Errorf("could not create file writer, callback function not found") + } } wg.Add(1) diff --git a/wasmsdk/jsbridge/file_writer.go b/wasmsdk/jsbridge/file_writer.go index e265117fa..81b69a0c6 100644 --- a/wasmsdk/jsbridge/file_writer.go +++ b/wasmsdk/jsbridge/file_writer.go @@ -168,14 +168,19 @@ type FileCallbackWriter struct { writeChunk js.Value buf []byte offset int64 + lookupHash string } const bufCallbackCap = 4 * 1024 * 1024 //4MB -func NewFileCallbackWriter(writeChunkFuncName string) *FileCallbackWriter { +func NewFileCallbackWriter(writeChunkFuncName, lookupHash string) *FileCallbackWriter { writeChunk := js.Global().Get(writeChunkFuncName) + if !writeChunk.Truthy() { + return nil + } return &FileCallbackWriter{ writeChunk: writeChunk, + lookupHash: lookupHash, } } @@ -190,7 +195,7 @@ func (wc *FileCallbackWriter) Write(p []byte) (int, error) { if len(wc.buf)+len(p) > cap(wc.buf) { uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) js.CopyBytesToJS(uint8Array, wc.buf) - _, err := Await(wc.writeChunk.Invoke(uint8Array, wc.offset)) + _, err := Await(wc.writeChunk.Invoke(wc.lookupHash, uint8Array, wc.offset)) if len(err) > 0 && !err[0].IsNull() { return 0, errors.New("file_writer: " + err[0].String()) } @@ -205,7 +210,7 @@ func (wc *FileCallbackWriter) Close() error { if len(wc.buf) > 0 { uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) js.CopyBytesToJS(uint8Array, wc.buf) - _, err := Await(wc.writeChunk.Invoke(uint8Array, wc.offset)) + _, err := Await(wc.writeChunk.Invoke(wc.lookupHash, uint8Array, wc.offset)) if len(err) > 0 && !err[0].IsNull() { return errors.New("file_writer: " + err[0].String()) } diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index e4d31b8f7..4b3bfad27 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -274,6 +274,11 @@ type Allocation struct { IsEnterprise bool `json:"is_enterprise"` + StorageVersion int `json:"storage_version"` + + // Owner ecdsa public key + OwnerSigningPublicKey string `json:"owner_signing_public_key"` + // 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 diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 4748248ae..e7d4d9c81 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -718,7 +718,7 @@ func (req *DownloadRequest) processDownload() { if startBlock+int64(j)*numBlocks+numBlocks > endBlock { blocksToDownload = endBlock - (startBlock + int64(j)*numBlocks) } - data, err := req.getBlocksData(startBlock+int64(j)*numBlocks, blocksToDownload, j == 0) + data, err := req.getBlocksData(startBlock+int64(j)*numBlocks, blocksToDownload, j == 0 && n > 1) if req.isDownloadCanceled { return errors.New("download_abort", "Download aborted by user") } From 3952a35fdec54f32c1e2a9e0dfb421e1907aca04 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sun, 22 Dec 2024 03:04:21 +0530 Subject: [PATCH 054/107] change init signature --- core/conf/config.go | 5 +---- wasmsdk/sdk.go | 9 +-------- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/core/conf/config.go b/core/conf/config.go index 8d5ae5c2f..d68b510f0 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -46,8 +46,6 @@ const ( type Config struct { // BlockWorker the url of 0dns's network api BlockWorker string `json:"block_worker,omitempty"` - // PreferredBlobbers preferred blobbers on new allocation - PreferredBlobbers []string `json:"preferred_blobbers,omitempty"` // MinSubmit mininal submit from blobber MinSubmit int `json:"min_submit,omitempty"` @@ -169,7 +167,6 @@ func LoadConfig(v Reader) (Config, error) { } cfg.BlockWorker = blockWorker - cfg.PreferredBlobbers = v.GetStringSlice("preferred_blobbers") cfg.MinSubmit = minSubmit cfg.MinConfirmation = minCfm cfg.ConfirmationChainLength = CfmChainLength @@ -179,7 +176,7 @@ func LoadConfig(v Reader) (Config, error) { cfg.SignatureScheme = v.GetString("signature_scheme") cfg.ChainID = v.GetString("chain_id") - cfg.ZauthServer = v.GetString("zauth.server") + cfg.ZauthServer = v.GetString("zauth_server") return cfg, nil } diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index b603c02e9..42c9ccbfb 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -32,7 +32,7 @@ var CreateObjectURL func(buf []byte, mimeType string) string // - sharderconsensous is the number of sharders to reach consensus func initSDKs(chainID, blockWorker, signatureScheme string, minConfirmation, minSubmit, confirmationChainLength int, - zboxHost, zboxAppType string, sharderconsensous int, isSplit bool) error { + zboxHost, zboxAppType string, sharderconsensous int) error { zboxApiClient.SetRequest(zboxHost, zboxAppType) @@ -42,19 +42,12 @@ func initSDKs(chainID, blockWorker, signatureScheme string, return err } - if !isSplit && zcncore.IsSplitWallet() { - // split wallet should not be reset back, use the existing - isSplit = true - } - - fmt.Println("init SDKs, isSplit:", isSplit) err = zcncore.InitZCNSDK(blockWorker, signatureScheme, zcncore.WithChainID(chainID), zcncore.WithMinConfirmation(minConfirmation), zcncore.WithMinSubmit(minSubmit), zcncore.WithConfirmationChainLength(confirmationChainLength), zcncore.WithSharderConsensous(sharderconsensous), - zcncore.WithIsSplitWallet(isSplit), ) if err != nil { From d9e880d8b21fc39b71dd52d07a76f657d28bd79b Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Sun, 22 Dec 2024 19:11:01 +0530 Subject: [PATCH 055/107] fix windows build --- core/transaction/entity_test.go | 1 - winsdk/sdk.go | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/core/transaction/entity_test.go b/core/transaction/entity_test.go index 3076a2ae4..5ccf48576 100644 --- a/core/transaction/entity_test.go +++ b/core/transaction/entity_test.go @@ -11,7 +11,6 @@ func TestOptimisticVerificationLearning(t *testing.T) { t.Skip() conf.InitClientConfig(&conf.Config{ BlockWorker: "", - PreferredBlobbers: nil, MinSubmit: 0, MinConfirmation: 50, ConfirmationChainLength: 3, diff --git a/winsdk/sdk.go b/winsdk/sdk.go index c2f8dc09f..50820333f 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -127,7 +127,6 @@ func InitSDKs(configJson *C.char) *C.char { l.Logger.Info(configObj.BlockWorker) l.Logger.Info(configObj.ChainID) l.Logger.Info(configObj.SignatureScheme) - l.Logger.Info(configObj.PreferredBlobbers) if zboxApiClient == nil { zboxApiClient = zboxapi.NewClient() @@ -172,7 +171,7 @@ func InitWallet(clientJson *C.char) *C.char { return WithJSON(false, err) } - err = sdk.InitStorageSDK(clientJs, configObj.BlockWorker, configObj.ChainID, configObj.SignatureScheme, configObj.PreferredBlobbers, 0) + err = sdk.InitStorageSDK(clientJs, configObj.BlockWorker, configObj.ChainID, configObj.SignatureScheme, nil, 0) if err != nil { l.Logger.Error(err, clientJs) return WithJSON(false, err) From a9e5b9ab493714b6f1d2ebba221f42c9e8a039a8 Mon Sep 17 00:00:00 2001 From: Hitenjain14 Date: Thu, 26 Dec 2024 00:34:12 +0530 Subject: [PATCH 056/107] add check for wallet id --- wasmsdk/blobber.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 9e0c26462..eb872cc6a 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -24,6 +24,7 @@ import ( "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zboxcore/client" "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk/zboxcore/zboxutil" @@ -1133,6 +1134,9 @@ func checkAllocStatus(allocationID string) (string, error) { if err != nil { return "", err } + if client.GetClientID() != alloc.Owner { + return "", errors.New("client id does not match with the allocation owner") + } status, blobberStatus, err := alloc.CheckAllocStatus() var statusStr string switch status { From 0a39195eccc5339aff3ebee5d09d2d84bed4a8f3 Mon Sep 17 00:00:00 2001 From: Jayash Satolia Date: Tue, 7 Jan 2025 03:38:27 +0530 Subject: [PATCH 057/107] Sign update alloc auth ticket --- wasmsdk/allocation.go | 8 ++++++++ wasmsdk/proxy.go | 1 + zboxcore/sdk/blobber_operations.go | 13 +++++++++++++ znft/example/go.mod | 4 ++-- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 2dfa67c36..5ddaf6916 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -304,6 +304,14 @@ func updateAllocation(allocationID string, return hash, err } +func getUpdateAllocTicket(allocationID, userID, operationType string, roundExpiry int64) (string, error) { + sign, err := sdk.GetUpdateAllocTicket(allocationID, userID, operationType, roundExpiry) + if err != nil { + return "", err + } + return sign, err +} + // getAllocationMinLock retrieves the minimum lock value for the allocation creation, as calculated by the network. // Lock value is the amount of tokens that the client needs to lock in the allocation's write pool // to be able to pay for the write operations. diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index c3e22a730..fcfd25fb7 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -267,6 +267,7 @@ func main() { "getUpdateAllocationMinLock": getUpdateAllocationMinLock, "getAllocationWith": getAllocationWith, "createfreeallocation": createfreeallocation, + "getUpdateAllocTicket": getUpdateAllocTicket, // readpool "getReadPoolInfo": getReadPoolInfo, diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 5985aa99b..15af35bf8 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -4,7 +4,9 @@ package sdk import ( + "encoding/hex" "encoding/json" + "fmt" "math" "strings" @@ -154,6 +156,17 @@ func UpdateAllocation( return } +func GetUpdateAllocTicket(allocationID, userID, operationType string, roundExpiry int64) (string, error) { + payload := fmt.Sprintf("%s:%d:%s:%s", allocationID, roundExpiry, userID, operationType) + + signature, err := client.Sign(hex.EncodeToString([]byte(payload))) + if err != nil { + return "", err + } + + return signature, nil +} + // 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. diff --git a/znft/example/go.mod b/znft/example/go.mod index da7233de2..7d7b3f3b6 100644 --- a/znft/example/go.mod +++ b/znft/example/go.mod @@ -1,8 +1,8 @@ module example -go 1.21 +go 1.22.5 -toolchain go1.21.0 +toolchain go1.23.3 require github.com/0chain/gosdk v1.8.9 From e9c2f87b6efc96809d7d848dd440f07b697469ba Mon Sep 17 00:00:00 2001 From: shahnawaz-creator Date: Wed, 8 Jan 2025 22:38:58 +0530 Subject: [PATCH 058/107] added workflow to deploy ewasm binary --- .../build-&-push-enterprise-wasm.yaml | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 .github/workflows/build-&-push-enterprise-wasm.yaml diff --git a/.github/workflows/build-&-push-enterprise-wasm.yaml b/.github/workflows/build-&-push-enterprise-wasm.yaml new file mode 100644 index 000000000..04682d7aa --- /dev/null +++ b/.github/workflows/build-&-push-enterprise-wasm.yaml @@ -0,0 +1,60 @@ +name: Build & Push Enterprise Wasm + +concurrency: + group: "build-release-ewasm-${{ github.ref }}" + cancel-in-progress: true + +on: + push: + # branches: [ master, staging, qa ] + tags: + - 'v*.*.*' + # pull_request: + workflow_dispatch: + +jobs: + build-wasm: + name: Build-wasm + runs-on: [self-hosted, arc-runner] + outputs: + build_version: ${{ steps.wasm_build.outputs.BUILD_TAG }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Build wasm binary using go version 1.22.5 + id: wasm_build + run: | + docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.22.5 sh -c "git config --global --add safe.directory /gosdk; make wasm-build" + BUILD_TAG=zcn-$(git describe --tags --exact-match)-enterprise.wasm + BUILD_TAG="${BUILD_TAG:0:4}${BUILD_TAG:5}" + mv zcn.wasm $BUILD_TAG + echo "BUILD_TAG=$BUILD_TAG" >>$GITHUB_OUTPUT + + - name: 'Upload Artifact' + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.wasm_build.outputs.BUILD_TAG }} + path: ${{ steps.wasm_build.outputs.BUILD_TAG }} + + - name: Install AWS cli + run: | + sudo apt update -y + sudo apt install awscli -y + + - name: Copy the wasm binary to aws s3. + run: | + export AWS_ACCESS_KEY_ID=${{ secrets.WEBAPP_STATIC_ACCESS_KEY }} + export AWS_SECRET_ACCESS_KEY=${{ secrets.WEBAPP_STATIC_SECRET_ACCESS_KEY }} + export AWS_DEFAULT_REGION=${{ secrets.WEBAPP_STATIC_REGION }} + gzip -9 ${{ steps.wasm_build.outputs.BUILD_TAG }} && mv ${{ steps.wasm_build.outputs.BUILD_TAG }}.gz ${{ steps.wasm_build.outputs.BUILD_TAG }} + aws s3 cp ${{ steps.wasm_build.outputs.BUILD_TAG }} s3://${{ secrets.WEBAPP_STATIC_BUCKET }}/wasm/${{ steps.wasm_build.outputs.BUILD_TAG }} --content-encoding gzip + + - name: Invalidate wasm binary + run: | + export AWS_ACCESS_KEY_ID=${{ secrets.WEBAPP_STATIC_ACCESS_KEY }} + export AWS_SECRET_ACCESS_KEY=${{ secrets.WEBAPP_STATIC_SECRET_ACCESS_KEY }} + export AWS_DEFAULT_REGION=${{ secrets.WEBAPP_STATIC_REGION }} + aws cloudfront create-invalidation --distribution-id ${{ secrets.WEBAPP_STATIC_DISTRIBUTION_ID }} --paths '/wasm/*' From c4f88a67a0f387c569c9fe65103372721bbd629a Mon Sep 17 00:00:00 2001 From: Jayash Satolia Date: Tue, 14 Jan 2025 09:38:43 +0530 Subject: [PATCH 059/107] Update with staging --- znft/example/go.mod | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/znft/example/go.mod b/znft/example/go.mod index da7233de2..7d7b3f3b6 100644 --- a/znft/example/go.mod +++ b/znft/example/go.mod @@ -1,8 +1,8 @@ module example -go 1.21 +go 1.22.5 -toolchain go1.21.0 +toolchain go1.23.3 require github.com/0chain/gosdk v1.8.9 From fe75c8bfd746aa6377fb53ca461815af54e35112 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Wed, 8 Jan 2025 16:09:13 +0530 Subject: [PATCH 060/107] refactoring --- core/block/block.go | 6 +- core/conf/config.go | 2 +- core/conf/config_test.go | 2 +- core/conf/network.go | 2 +- core/conf/vars.go | 22 ++-- core/node/node.go | 8 +- core/resty/resty.go | 2 +- core/resty/resty_test.go | 2 +- core/sys/fs_mem.go | 2 +- core/sys/util.go | 2 +- core/tokenrate/bancor.go | 2 +- core/tokenrate/coingecko.go | 2 +- core/tokenrate/coinmarketcap.go | 2 +- core/tokenrate/tokenrate_test.go | 4 +- core/tokenrate/uniswap.go | 2 +- core/transaction/entity.go | 6 +- core/transaction/entity_test.go | 2 +- core/transaction/utils.go | 6 +- core/util/merkle_tree_interface.go | 2 +- core/util/secure_value.go | 2 +- core/zcncrypto/bls0chain_herumi.go | 2 +- core/zcncrypto/bls0chain_herumi_test.go | 2 +- core/zcncrypto/ed255190chain.go | 2 +- core/zcncrypto/signature_scheme.go | 2 +- dev/blobber/handlers.go | 2 +- dev/blobber/init.go | 2 +- dev/blobber/model/ref.go | 4 +- dev/blobber/model/write_marker.go | 4 +- dev/blobber/ref.go | 2 +- dev/server.go | 4 +- go.mod | 25 +++-- go.sum | 77 ++++++++++---- mobilesdk/sdk/common.go | 2 +- mobilesdk/sdk/keys.go | 2 +- mobilesdk/sdk/sdk.go | 12 +-- mobilesdk/sdk/sign.go | 8 +- mobilesdk/zbox/allocation.go | 6 +- mobilesdk/zboxapi/client.go | 6 +- sdks/blobber/blobber.go | 2 +- sdks/client.go | 8 +- sdks/zbox.go | 12 +-- wasmsdk/README.md | 2 +- wasmsdk/allocation.go | 2 +- wasmsdk/auth_txn.go | 2 +- wasmsdk/blobber.go | 20 ++-- wasmsdk/cache.go | 2 +- wasmsdk/chunked_upload_progress_storer.go | 2 +- wasmsdk/demo/main.go | 4 +- wasmsdk/ethwallet.go | 2 +- wasmsdk/jsbridge/file_reader.go | 2 +- wasmsdk/jsbridge/file_writer.go | 2 +- wasmsdk/jsbridge/template_data.go | 2 +- wasmsdk/player_file.go | 2 +- wasmsdk/player_stream.go | 4 +- wasmsdk/proxy.go | 8 +- wasmsdk/sdk.go | 10 +- wasmsdk/smartcontract.go | 2 +- wasmsdk/statusbar.go | 2 +- wasmsdk/tokenrate.go | 2 +- wasmsdk/wallet.go | 4 +- wasmsdk/zbox.go | 2 +- winsdk/allocation.go | 2 +- winsdk/cache.go | 2 +- winsdk/helper.go | 4 +- winsdk/sdk.go | 20 ++-- winsdk/storage.go | 4 +- winsdk/zboxapi.go | 6 +- zboxapi/sdk.go | 6 +- zboxcore/allocationchange/change.go | 2 +- zboxcore/allocationchange/copyobject.go | 8 +- zboxcore/allocationchange/createdir.go | 6 +- zboxcore/allocationchange/deletefile.go | 4 +- zboxcore/allocationchange/moveobject.go | 8 +- zboxcore/allocationchange/newfile.go | 12 +-- zboxcore/allocationchange/renameobject.go | 6 +- zboxcore/allocationchange/updatefile.go | 8 +- zboxcore/blockchain/entity.go | 6 +- zboxcore/client/entity.go | 4 +- zboxcore/encoder/erasurecode.go | 2 +- zboxcore/encryption/pre_test.go | 2 +- zboxcore/fileref/fileref.go | 4 +- zboxcore/fileref/hashnode.go | 2 +- zboxcore/fileref/hashnode_test.go | 2 +- zboxcore/logger/logger.go | 2 +- zboxcore/marker/authticket.go | 4 +- zboxcore/marker/deletetoken.go | 4 +- zboxcore/marker/readmarker.go | 8 +- zboxcore/marker/versionmarker.go | 6 +- zboxcore/marker/writemarker.go | 6 +- zboxcore/mocks/AllocationChange.go | 2 +- zboxcore/mocks/EncryptionScheme.go | 2 +- zboxcore/mocks/RefEntity.go | 2 +- zboxcore/sdk/allocation.go | 20 ++-- zboxcore/sdk/allocation_file_delete_test.go | 14 +-- zboxcore/sdk/allocation_file_test.go | 15 ++- zboxcore/sdk/allocation_test.go | 24 ++--- zboxcore/sdk/authticket.go | 4 +- zboxcore/sdk/blobber_operations.go | 4 +- zboxcore/sdk/blobber_operations_mobile.go | 4 +- zboxcore/sdk/blockdownloadworker.go | 14 +-- zboxcore/sdk/chunked_upload.go | 24 ++--- zboxcore/sdk/chunked_upload_bench_test.go | 8 +- zboxcore/sdk/chunked_upload_blobber.go | 18 ++-- zboxcore/sdk/chunked_upload_chunk_reader.go | 8 +- .../chunked_upload_chunk_reader_bench_test.go | 4 +- .../sdk/chunked_upload_chunk_reader_test.go | 4 +- zboxcore/sdk/chunked_upload_form_builder.go | 2 +- zboxcore/sdk/chunked_upload_hasher.go | 4 +- zboxcore/sdk/chunked_upload_model.go | 10 +- zboxcore/sdk/chunked_upload_option.go | 2 +- zboxcore/sdk/chunked_upload_process.go | 2 +- zboxcore/sdk/chunked_upload_process_js.go | 8 +- .../sdk/chunked_upload_progress_storer.go | 8 +- zboxcore/sdk/chunked_upload_web_streaming.go | 2 +- zboxcore/sdk/commitworker.go | 18 ++-- zboxcore/sdk/common.go | 10 +- zboxcore/sdk/copyworker.go | 22 ++-- zboxcore/sdk/copyworker_test.go | 18 ++-- zboxcore/sdk/deleteworker.go | 18 ++-- zboxcore/sdk/deleteworker_test.go | 14 +-- zboxcore/sdk/dirworker.go | 18 ++-- zboxcore/sdk/download_progress_storer.go | 2 +- zboxcore/sdk/downloader.go | 4 +- zboxcore/sdk/downloader_option.go | 2 +- zboxcore/sdk/downloadworker.go | 20 ++-- zboxcore/sdk/downloadworker_test.go | 2 +- zboxcore/sdk/filemetaworker.go | 10 +- zboxcore/sdk/filemetaworker_test.go | 14 +-- zboxcore/sdk/filerefsworker.go | 10 +- zboxcore/sdk/filestatsworker.go | 8 +- zboxcore/sdk/filestatsworker_test.go | 14 +-- zboxcore/sdk/listworker.go | 12 +-- zboxcore/sdk/listworker_test.go | 14 +-- zboxcore/sdk/live_upload.go | 2 +- zboxcore/sdk/live_upload_reader.go | 2 +- zboxcore/sdk/m3u8.go | 2 +- zboxcore/sdk/moveworker.go | 20 ++-- zboxcore/sdk/multi_operation_worker.go | 16 +-- zboxcore/sdk/networkworker.go | 10 +- zboxcore/sdk/playlist.go | 14 +-- zboxcore/sdk/reader.go | 4 +- zboxcore/sdk/renameworker.go | 20 ++-- zboxcore/sdk/renameworker_test.go | 18 ++-- zboxcore/sdk/repairCallback.go | 2 +- zboxcore/sdk/repairworker.go | 10 +- zboxcore/sdk/rollback.go | 10 +- zboxcore/sdk/sdk.go | 100 ++++++++---------- zboxcore/sdk/sharerequest.go | 12 +-- zboxcore/sdk/sync.go | 8 +- zboxcore/sdk/transaction.go | 4 +- zboxcore/sdk/transaction_mobile.go | 6 +- zboxcore/sdk/upload_worker.go | 12 +-- zboxcore/sdk/writemarker_mutex.go | 10 +- zboxcore/sdk/writemarker_mutex_test.go | 8 +- zboxcore/zboxutil/download_buffer.go | 2 +- zboxcore/zboxutil/http.go | 10 +- zboxcore/zboxutil/util.go | 4 +- zcnbridge/authorizer/proofBurnTicket.go | 10 +- zcnbridge/authorizer/proofBurnTicket_test.go | 2 +- zcnbridge/authorizers_query.go | 2 +- zcnbridge/bridge.go | 4 +- zcnbridge/bridge_helper.go | 4 +- zcnbridge/bridge_test.go | 7 +- zcnbridge/config.go | 4 +- zcnbridge/http/client.go | 7 +- zcnbridge/http/rest.go | 4 +- zcnbridge/http/rest_test.go | 2 +- zcnbridge/log/handler.go | 2 +- zcnbridge/log/logging.go | 2 +- zcnbridge/mocks/Transaction.go | 4 +- .../mocks/TransactionCallbackAwaitable.go | 2 +- zcnbridge/mocks/TransactionProvider.go | 2 +- zcnbridge/rest.go | 2 +- zcnbridge/transaction/functions.go | 2 +- zcnbridge/transaction/txn.go | 8 +- zcnbridge/wallet/wallet.go | 2 +- zcnbridge/zcnsc/mint_payload.go | 2 +- zcncore/ethwallet_base.go | 4 +- zcncore/mocks/TransactionCommon.go | 2 +- zcncore/mocks/TransactionScheme.go | 2 +- zcncore/mswallet.go | 4 +- zcncore/mswallet_base.go | 4 +- zcncore/mswallet_mobile.go | 4 +- zcncore/networkworker.go | 6 +- zcncore/networkworker_mobile.go | 6 +- zcncore/transaction.go | 14 +-- zcncore/transaction_base.go | 25 +++-- zcncore/transaction_mobile.go | 14 +-- zcncore/transaction_query.go | 4 +- zcncore/transaction_query_mobile.go | 4 +- zcncore/transactionauth.go | 2 +- zcncore/transactionauth_base.go | 10 +- zcncore/transactionauth_mobile.go | 2 +- zcncore/wallet.go | 4 +- zcncore/wallet_base.go | 18 ++-- zcncore/wallet_callback.go | 2 +- zcncore/wallet_mobile.go | 2 +- zcncore/zauth.go | 4 +- zmagmacore/crypto/keys.go | 2 +- zmagmacore/http/sc-api.go | 2 +- zmagmacore/log/handler.go | 2 +- zmagmacore/magmasc/acknowledgment.go | 2 +- zmagmacore/magmasc/billing.go | 2 +- zmagmacore/magmasc/consumer.go | 2 +- zmagmacore/magmasc/datausage.go | 2 +- zmagmacore/magmasc/mocks_test.go | 6 +- zmagmacore/magmasc/provider.go | 2 +- zmagmacore/magmasc/provider_terms.go | 2 +- zmagmacore/magmasc/tokenpool.go | 2 +- zmagmacore/magmasc/tokenpool_transfer.go | 2 +- zmagmacore/registration/node.go | 2 +- zmagmacore/transaction/txn.go | 2 +- zmagmacore/wallet/setup.go | 2 +- zmagmacore/wallet/wallet.go | 2 +- znft/README.MD | 2 +- znft/example/main.go | 2 +- znft/factoryerc721.go | 2 +- znft/factoryerc721fixed.go | 2 +- znft/factoryerc721pack.go | 2 +- znft/factoryerc721random.go | 2 +- znft/storageerc721.go | 2 +- znft/storageerc721fixed.go | 2 +- znft/storageerc721pack.go | 2 +- znft/storageerc721random.go | 2 +- znft/znft.go | 18 ++-- 225 files changed, 774 insertions(+), 750 deletions(-) diff --git a/core/block/block.go b/core/block/block.go index aec92693d..24e38f9ee 100644 --- a/core/block/block.go +++ b/core/block/block.go @@ -7,9 +7,9 @@ package block import ( "fmt" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/transaction" ) type Key []byte diff --git a/core/conf/config.go b/core/conf/config.go index d68b510f0..083272521 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -10,7 +10,7 @@ import ( "strings" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" "github.com/spf13/viper" ) diff --git a/core/conf/config_test.go b/core/conf/config_test.go index 77f8c51b1..9bb7f7c68 100644 --- a/core/conf/config_test.go +++ b/core/conf/config_test.go @@ -3,7 +3,7 @@ package conf import ( "testing" - "github.com/0chain/gosdk/core/conf/mocks" + "github.com/0chain/gosdk_common/core/conf/mocks" "github.com/stretchr/testify/require" ) diff --git a/core/conf/network.go b/core/conf/network.go index 899e3acda..72dc2ae06 100644 --- a/core/conf/network.go +++ b/core/conf/network.go @@ -5,7 +5,7 @@ import ( "os" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" "github.com/spf13/viper" ) diff --git a/core/conf/vars.go b/core/conf/vars.go index 211c23c05..5b96b690f 100644 --- a/core/conf/vars.go +++ b/core/conf/vars.go @@ -38,17 +38,17 @@ func GetClientConfig() (*Config, error) { return cfg, nil } -// InitClientConfig set global client SDK config -func InitClientConfig(c *Config) { - onceCfg.Do(func() { - sharderConsensous := c.SharderConsensous - if sharderConsensous < 1 { - sharderConsensous = DefaultSharderConsensous - } - cfg = c - cfg.SharderConsensous = sharderConsensous - }) -} + // InitClientConfig set global client SDK config + func InitClientConfig(c *Config) { + onceCfg.Do(func() { + sharderConsensous := c.SharderConsensous + if sharderConsensous < 1 { + sharderConsensous = DefaultSharderConsensous + } + cfg = c + cfg.SharderConsensous = sharderConsensous + }) + } // InitChainNetwork set global chain network for the SDK given its configuration func InitChainNetwork(n *Network) { diff --git a/core/node/node.go b/core/node/node.go index 2a3ef7de0..e5c0e3023 100644 --- a/core/node/node.go +++ b/core/node/node.go @@ -14,10 +14,10 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/block" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk_common/core/block" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/ethereum/go-ethereum/common/math" ) diff --git a/core/resty/resty.go b/core/resty/resty.go index 49ea9d695..a1442285f 100644 --- a/core/resty/resty.go +++ b/core/resty/resty.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" ) func clone(m map[string]string) map[string]string { diff --git a/core/resty/resty_test.go b/core/resty/resty_test.go index c424d9925..6f347cd5b 100644 --- a/core/resty/resty_test.go +++ b/core/resty/resty_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/0chain/gosdk/core/resty/mocks" + "github.com/0chain/gosdk_common/core/resty/mocks" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/core/sys/fs_mem.go b/core/sys/fs_mem.go index 6c088d881..d3a458f06 100644 --- a/core/sys/fs_mem.go +++ b/core/sys/fs_mem.go @@ -13,7 +13,7 @@ import ( "syscall/js" "time" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/valyala/bytebufferpool" ) diff --git a/core/sys/util.go b/core/sys/util.go index baf46c416..8810406f2 100644 --- a/core/sys/util.go +++ b/core/sys/util.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/valyala/bytebufferpool" ) diff --git a/core/tokenrate/bancor.go b/core/tokenrate/bancor.go index 2f3a4d501..8a49bce90 100644 --- a/core/tokenrate/bancor.go +++ b/core/tokenrate/bancor.go @@ -10,7 +10,7 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/resty" + "github.com/0chain/gosdk_common/core/resty" ) type bancorQuoteQuery struct { diff --git a/core/tokenrate/coingecko.go b/core/tokenrate/coingecko.go index 440a77f30..24c6f765f 100644 --- a/core/tokenrate/coingecko.go +++ b/core/tokenrate/coingecko.go @@ -8,7 +8,7 @@ import ( "net/http" "strconv" - "github.com/0chain/gosdk/core/resty" + "github.com/0chain/gosdk_common/core/resty" ) type coingeckoQuoteQuery struct { diff --git a/core/tokenrate/coinmarketcap.go b/core/tokenrate/coinmarketcap.go index 0bba459b1..311f47853 100644 --- a/core/tokenrate/coinmarketcap.go +++ b/core/tokenrate/coinmarketcap.go @@ -10,7 +10,7 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/resty" + "github.com/0chain/gosdk_common/core/resty" ) type coinmarketcapQuoteQuery struct { diff --git a/core/tokenrate/tokenrate_test.go b/core/tokenrate/tokenrate_test.go index 7a1d4b31f..74c998736 100644 --- a/core/tokenrate/tokenrate_test.go +++ b/core/tokenrate/tokenrate_test.go @@ -15,8 +15,8 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/zboxcore/mocks" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/zboxcore/mocks" ) func TestGetUSD(t *testing.T) { diff --git a/core/tokenrate/uniswap.go b/core/tokenrate/uniswap.go index 502c88f0b..0650611df 100644 --- a/core/tokenrate/uniswap.go +++ b/core/tokenrate/uniswap.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/resty" + "github.com/0chain/gosdk_common/core/resty" "github.com/machinebox/graphql" ) diff --git a/core/transaction/entity.go b/core/transaction/entity.go index 2f9ea82ab..1d6a7cda0 100644 --- a/core/transaction/entity.go +++ b/core/transaction/entity.go @@ -10,9 +10,9 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/util" lru "github.com/hashicorp/golang-lru" ) diff --git a/core/transaction/entity_test.go b/core/transaction/entity_test.go index 5ccf48576..9b6c951c4 100644 --- a/core/transaction/entity_test.go +++ b/core/transaction/entity_test.go @@ -3,7 +3,7 @@ package transaction import ( "testing" - "github.com/0chain/gosdk/core/conf" + "github.com/0chain/gosdk_common/core/conf" "github.com/stretchr/testify/assert" ) diff --git a/core/transaction/utils.go b/core/transaction/utils.go index e306b73c8..b42f2a96e 100644 --- a/core/transaction/utils.go +++ b/core/transaction/utils.go @@ -12,9 +12,9 @@ import ( "github.com/0chain/common/core/encryption" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/util" ) const retriesCount = 30 diff --git a/core/util/merkle_tree_interface.go b/core/util/merkle_tree_interface.go index cb3e773e6..c6f809211 100644 --- a/core/util/merkle_tree_interface.go +++ b/core/util/merkle_tree_interface.go @@ -3,7 +3,7 @@ package util import ( "encoding/hex" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" "github.com/minio/sha256-simd" ) diff --git a/core/util/secure_value.go b/core/util/secure_value.go index aa41108ed..6f17be5e9 100644 --- a/core/util/secure_value.go +++ b/core/util/secure_value.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "strings" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" ) // Hashable anything that can provide it's hash diff --git a/core/zcncrypto/bls0chain_herumi.go b/core/zcncrypto/bls0chain_herumi.go index 39ba4a644..4c07bf5e7 100644 --- a/core/zcncrypto/bls0chain_herumi.go +++ b/core/zcncrypto/bls0chain_herumi.go @@ -12,7 +12,7 @@ import ( "github.com/0chain/errors" "github.com/tyler-smith/go-bip39" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" ) func init() { diff --git a/core/zcncrypto/bls0chain_herumi_test.go b/core/zcncrypto/bls0chain_herumi_test.go index ada003fca..f5a54ec56 100644 --- a/core/zcncrypto/bls0chain_herumi_test.go +++ b/core/zcncrypto/bls0chain_herumi_test.go @@ -7,7 +7,7 @@ import ( "github.com/0chain/errors" "github.com/stretchr/testify/require" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" ) var verifyPublickey = `e8a6cfa7b3076ae7e04764ffdfe341632a136b52953dfafa6926361dd9a466196faecca6f696774bbd64b938ff765dbc837e8766a5e2d8996745b2b94e1beb9e` diff --git a/core/zcncrypto/ed255190chain.go b/core/zcncrypto/ed255190chain.go index 4c640712b..dee2b1f39 100644 --- a/core/zcncrypto/ed255190chain.go +++ b/core/zcncrypto/ed255190chain.go @@ -7,7 +7,7 @@ import ( "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" "github.com/tyler-smith/go-bip39" "golang.org/x/crypto/ed25519" ) diff --git a/core/zcncrypto/signature_scheme.go b/core/zcncrypto/signature_scheme.go index 6a192ac26..c5ea09cd6 100644 --- a/core/zcncrypto/signature_scheme.go +++ b/core/zcncrypto/signature_scheme.go @@ -7,7 +7,7 @@ import ( "os" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" "github.com/tyler-smith/go-bip39" ) diff --git a/dev/blobber/handlers.go b/dev/blobber/handlers.go index cc52edee9..4dd68cf17 100644 --- a/dev/blobber/handlers.go +++ b/dev/blobber/handlers.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - "github.com/0chain/gosdk/dev/blobber/model" + "github.com/0chain/gosdk_common/dev/blobber/model" "github.com/gorilla/mux" ) diff --git a/dev/blobber/init.go b/dev/blobber/init.go index aea5b669d..12fcff5d8 100644 --- a/dev/blobber/init.go +++ b/dev/blobber/init.go @@ -3,7 +3,7 @@ package blobber import ( "net/http" - "github.com/0chain/gosdk/dev/mock" + "github.com/0chain/gosdk_common/dev/mock" "github.com/gorilla/mux" ) diff --git a/dev/blobber/model/ref.go b/dev/blobber/model/ref.go index 75759b027..1ed563b0a 100644 --- a/dev/blobber/model/ref.go +++ b/dev/blobber/model/ref.go @@ -7,8 +7,8 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/pathutil" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/pathutil" ) const ( diff --git a/dev/blobber/model/write_marker.go b/dev/blobber/model/write_marker.go index 73506457a..def6f8844 100644 --- a/dev/blobber/model/write_marker.go +++ b/dev/blobber/model/write_marker.go @@ -1,8 +1,8 @@ package model import ( - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/marker" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type WriteMarker struct { diff --git a/dev/blobber/ref.go b/dev/blobber/ref.go index 955744785..09a0f579b 100644 --- a/dev/blobber/ref.go +++ b/dev/blobber/ref.go @@ -3,7 +3,7 @@ package blobber import ( "sync" - "github.com/0chain/gosdk/dev/blobber/model" + "github.com/0chain/gosdk_common/dev/blobber/model" ) var referencePathResults = make(map[string]*model.ReferencePathResult) diff --git a/dev/server.go b/dev/server.go index 3349bc937..1d7956076 100644 --- a/dev/server.go +++ b/dev/server.go @@ -4,8 +4,8 @@ package dev import ( "net/http/httptest" - "github.com/0chain/gosdk/dev/blobber" - "github.com/0chain/gosdk/dev/mock" + "github.com/0chain/gosdk_common/dev/blobber" + "github.com/0chain/gosdk_common/dev/mock" "github.com/gorilla/mux" ) diff --git a/go.mod b/go.mod index e26bef3a1..3314d30b7 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/0chain/gosdk go 1.22.5 require ( - github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 + github.com/0chain/common v1.18.3 github.com/0chain/errors v1.0.3 github.com/Luzifer/go-openssl/v3 v3.1.0 github.com/btcsuite/btcd v0.23.4 @@ -28,14 +28,14 @@ require ( github.com/pkg/errors v0.9.1 github.com/shopspring/decimal v1.3.1 github.com/spf13/viper v1.15.0 - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.9.0 github.com/tyler-smith/go-bip39 v1.1.0 github.com/uptrace/bunrouter v1.0.20 go.dedis.ch/kyber/v3 v3.1.0 go.uber.org/zap v1.24.0 - golang.org/x/crypto v0.17.0 + golang.org/x/crypto v0.21.0 golang.org/x/image v0.14.0 - golang.org/x/sync v0.5.0 + golang.org/x/sync v0.7.0 google.golang.org/grpc v1.53.0 gopkg.in/cheggaaa/pb.v1 v1.0.28 gopkg.in/natefinch/lumberjack.v2 v2.2.1 @@ -44,6 +44,7 @@ require ( ) require ( + github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd github.com/hack-pad/go-webworkers v0.1.0 github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/minio/sha256-simd v1.0.1 @@ -68,15 +69,15 @@ require ( github.com/felixge/httpsnoop v1.0.3 // indirect github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect - github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-jwt/jwt/v4 v4.3.0 // indirect github.com/golang/glog v1.0.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.2 // indirect + github.com/golang/protobuf v1.5.3 // indirect github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect github.com/google/flatbuffers v22.9.29+incompatible // indirect github.com/gorilla/websocket v1.5.0 // indirect @@ -87,9 +88,7 @@ require ( github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c // indirect github.com/huin/goupnp v1.0.3 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect - github.com/kr/pretty v0.3.1 // indirect github.com/magiconair/properties v1.8.7 // indirect - github.com/matryer/is v1.4.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect @@ -110,7 +109,7 @@ require ( github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/status-im/keycard-go v0.2.0 // indirect - github.com/stretchr/objx v0.5.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect github.com/subosito/gotenv v1.4.2 // indirect github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect github.com/tinylib/msgp v1.1.6 // indirect @@ -118,13 +117,13 @@ require ( github.com/tklauser/numcpus v0.6.0 // indirect github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa // indirect github.com/valyala/fasthttp v1.51.0 // indirect + github.com/x448/float16 v0.8.4 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/sys v0.15.0 // indirect + golang.org/x/sys v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect - google.golang.org/protobuf v1.28.1 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + google.golang.org/protobuf v1.33.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect ) @@ -138,7 +137,7 @@ require ( github.com/yusufpapurcu/wmi v1.2.2 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.9.0 // indirect - golang.org/x/net v0.19.0 // indirect + golang.org/x/net v0.23.0 // indirect golang.org/x/time v0.3.0 // indirect google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect ) diff --git a/go.sum b/go.sum index e57801008..2d346f6af 100644 --- a/go.sum +++ b/go.sum @@ -40,13 +40,17 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= collectd.org v0.3.0/go.mod h1:A/8DzQBkF6abtvrT2j/AU/4tiBgJWYyh0y/oB/4MlWE= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 h1:z+DtCR8mBsjPnEsT2XtRu4X7GfBiMnz9dYvWYs9V0B4= -github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565/go.mod h1:UyDC8Qyl5z9lGkCnf9RHJPMektnFX8XtCJZHXCCVj8E= +github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= +github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= +github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd h1:zeLdGO7e5Ovd4w/g/sHvg+0+Zu0gI7mhpznSsGbB3lI= +github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd/go.mod h1:A6zAa6S8jWML2razteUYtk9aINjHW4u8MjFKITgIdp4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= +github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/Luzifer/go-openssl/v3 v3.1.0 h1:QqKqo6kYXGGUsvtUoCpRZm8lHw+jDfhbzr36gVj+/gw= github.com/Luzifer/go-openssl/v3 v3.1.0/go.mod h1:liy3FXuuS8hfDlYh1T+l78AwQ/NjZflJz0NDvjKhwDs= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= @@ -68,6 +72,8 @@ github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLj github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -112,13 +118,24 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= +github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/pebble v1.1.2 h1:CUh2IPtR4swHlEj48Rhfzw6l/d0qA31fItcIszQVIsA= +github.com/cockroachdb/pebble v1.1.2/go.mod h1:4exszw1r40423ZsmkG/09AFEG83I0uDgfujJdbL6kYU= +github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= +github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -171,15 +188,20 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= +github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= +github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-kit/kit v0.8.0 h1:Wz+5lgoB0kkuqLEc6NVmwRknTKP6dTGbSqvhZtBI/j0= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0 h1:wDJmvq38kDhkVxi50ni9ykkdUr1PKgqKOoi01fa0Mdk= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= @@ -229,8 +251,8 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= @@ -362,7 +384,6 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -395,6 +416,8 @@ github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= +github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= @@ -438,7 +461,6 @@ github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 h1:6ob53CVz+ja2i7easAStApZJlh7sxyq3Cm7g1Di6iqA= github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -449,14 +471,22 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.12.0 h1:C+UIj/QWtmqY13Arb8kwMt5j34/0Z2iKamrJ+ryC0Gg= +github.com/prometheus/client_golang v1.12.0/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a h1:CmF68hwI0XsOQ5UwlBopMi2Ow4Pbg32akc4KIVCOm+Y= +github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= +github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= +github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= +github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/remeh/sizedwaitgroup v1.0.0 h1:VNGGFwNo/R5+MJBf6yrsr110p0m4/OX4S3DCy7Kyl5E= @@ -510,8 +540,9 @@ github.com/status-im/keycard-go v0.2.0/go.mod h1:wlp8ZLbsmrF6g6WjugPAx+IzoLrkdf9 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.0/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= @@ -521,8 +552,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8= github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= @@ -546,6 +577,8 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= @@ -601,8 +634,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= -golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -616,6 +649,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -680,8 +715,8 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -702,8 +737,8 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= -golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -757,8 +792,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -937,8 +972,8 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/mobilesdk/sdk/common.go b/mobilesdk/sdk/common.go index 5a189b757..189b81f4f 100644 --- a/mobilesdk/sdk/common.go +++ b/mobilesdk/sdk/common.go @@ -4,7 +4,7 @@ package sdk import ( - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" ) // GetLookupHash get lookup hash with allocation id and path. diff --git a/mobilesdk/sdk/keys.go b/mobilesdk/sdk/keys.go index ebfd49562..d95debe3f 100644 --- a/mobilesdk/sdk/keys.go +++ b/mobilesdk/sdk/keys.go @@ -3,7 +3,7 @@ package sdk import ( "encoding/json" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/zcncrypto" ) // SplitKeys split keys by private key, return json string of wallet diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index f85635fe5..2b195db8d 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -11,18 +11,18 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" "github.com/pkg/errors" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/core/version" - "github.com/0chain/gosdk/zboxcore/client" - l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/core/version" + "github.com/0chain/gosdk_common/zboxcore/client" + l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk/mobilesdk/zbox" - "github.com/0chain/gosdk/mobilesdk/zboxapi" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/mobilesdk/zboxapi" ) var nonce = int64(0) diff --git a/mobilesdk/sdk/sign.go b/mobilesdk/sdk/sign.go index 0e0a7ef5f..20dc633d3 100644 --- a/mobilesdk/sdk/sign.go +++ b/mobilesdk/sdk/sign.go @@ -3,10 +3,10 @@ package sdk import ( "errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/zcncrypto" - _ "github.com/0chain/gosdk/zboxcore/client" //import it to initialize sys.Sign + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/zcncrypto" + _ "github.com/0chain/gosdk_common/zboxcore/client" //import it to initialize sys.Sign ) var ErrInvalidSignatureScheme = errors.New("invalid_signature_scheme") diff --git a/mobilesdk/zbox/allocation.go b/mobilesdk/zbox/allocation.go index 97f986087..14ea8fc73 100644 --- a/mobilesdk/zbox/allocation.go +++ b/mobilesdk/zbox/allocation.go @@ -6,10 +6,10 @@ import ( "fmt" "time" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/blockchain" ) var ErrInvalidAllocation = errors.New("zbox: invalid allocation") diff --git a/mobilesdk/zboxapi/client.go b/mobilesdk/zboxapi/client.go index b954192da..87a3af8d7 100644 --- a/mobilesdk/zboxapi/client.go +++ b/mobilesdk/zboxapi/client.go @@ -13,9 +13,9 @@ import ( "context" "errors" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/zboxapi" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk_common/zboxcore/client" "go.uber.org/zap" ) diff --git a/sdks/blobber/blobber.go b/sdks/blobber/blobber.go index e13d9016b..89bbf424e 100644 --- a/sdks/blobber/blobber.go +++ b/sdks/blobber/blobber.go @@ -1,7 +1,7 @@ package blobber import ( - "github.com/0chain/gosdk/sdks" + "github.com/0chain/gosdk_common/sdks" ) // Blobber blobber sdk client instance diff --git a/sdks/client.go b/sdks/client.go index d5c4df2ff..6cc6e0445 100644 --- a/sdks/client.go +++ b/sdks/client.go @@ -5,10 +5,10 @@ import ( "net/url" "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/client" ) // Client a client instance of restful api diff --git a/sdks/zbox.go b/sdks/zbox.go index 9e92f0c33..4aa0d4fa4 100644 --- a/sdks/zbox.go +++ b/sdks/zbox.go @@ -9,12 +9,12 @@ import ( "net/url" "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/client" ) // ZBox sdk client instance diff --git a/wasmsdk/README.md b/wasmsdk/README.md index c4b52b221..58365f118 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -3,7 +3,7 @@ # wasmsdk ```go -import "github.com/0chain/gosdk/wasmsdk" +import "github.com/0chain/gosdk_common/wasmsdk" ``` ## Index diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 5ddaf6916..ba62a18ab 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -13,9 +13,9 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/transaction" ) const TOKEN_UNIT int64 = 1e10 diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index cd34f925c..902f35ba3 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,9 +7,9 @@ import ( "fmt" "syscall/js" - "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/sys" ) type AuthCallbackFunc func(msg string) string diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index eb872cc6a..286313880 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -15,19 +15,19 @@ import ( "syscall/js" "time" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/sys" "github.com/hack-pad/safejs" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" ) diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 2e8d914e5..78e92236e 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -9,8 +9,8 @@ import ( "time" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/client" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/client" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/wasmsdk/chunked_upload_progress_storer.go b/wasmsdk/chunked_upload_progress_storer.go index d839d5be0..a3435b4ee 100644 --- a/wasmsdk/chunked_upload_progress_storer.go +++ b/wasmsdk/chunked_upload_progress_storer.go @@ -7,7 +7,7 @@ import ( "sync" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) // chunkedUploadProgressStorer load and save upload progress diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 6c899cdd7..66c426e53 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,8 +7,8 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zcncore" "github.com/uptrace/bunrouter" ) diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index bc2dbc40b..a04097962 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -8,7 +8,7 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // JS does not have int64 so we must take a string instead of int64. diff --git a/wasmsdk/jsbridge/file_reader.go b/wasmsdk/jsbridge/file_reader.go index 17b27a1e7..21b783917 100644 --- a/wasmsdk/jsbridge/file_reader.go +++ b/wasmsdk/jsbridge/file_reader.go @@ -8,7 +8,7 @@ import ( "io" "syscall/js" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/valyala/bytebufferpool" ) diff --git a/wasmsdk/jsbridge/file_writer.go b/wasmsdk/jsbridge/file_writer.go index 81b69a0c6..3cb1cfa85 100644 --- a/wasmsdk/jsbridge/file_writer.go +++ b/wasmsdk/jsbridge/file_writer.go @@ -8,7 +8,7 @@ import ( "io/fs" "syscall/js" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/valyala/bytebufferpool" ) diff --git a/wasmsdk/jsbridge/template_data.go b/wasmsdk/jsbridge/template_data.go index c1723ff18..80d18fd23 100644 --- a/wasmsdk/jsbridge/template_data.go +++ b/wasmsdk/jsbridge/template_data.go @@ -13,7 +13,7 @@ import ( "syscall/js" "text/template" - "github.com/0chain/gosdk/core/version" + "github.com/0chain/gosdk_common/core/version" ) //go:embed zcnworker.js.tpl diff --git a/wasmsdk/player_file.go b/wasmsdk/player_file.go index 82de0d4c8..7d847adb5 100644 --- a/wasmsdk/player_file.go +++ b/wasmsdk/player_file.go @@ -7,8 +7,8 @@ import ( "context" "fmt" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type FilePlayer struct { diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index 51c844e20..8af595d97 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,10 +11,10 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type StreamPlayer struct { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index fcfd25fb7..3f5c7ae73 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -13,13 +13,13 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/version" - "github.com/0chain/gosdk/core/zcncrypto" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/client" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/version" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/client" "github.com/hack-pad/safejs" diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 42c9ccbfb..c194cd061 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -10,12 +10,12 @@ import ( "io" "os" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/imageutil" - "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/imageutil" + "github.com/0chain/gosdk_common/core/logger" ) var CreateObjectURL func(buf []byte, mimeType string) string @@ -152,7 +152,7 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro if err != nil { sdkLogger.Error(fmt.Sprintf("Error parsing JSON: %v", err)) } - b, err := zboxutil.MakeSCRestAPICall(scAddress, relativePath, params, nil) + b, err := client.MakeSCRestAPICall(scAddress, relativePath, params) return string(b), err } diff --git a/wasmsdk/smartcontract.go b/wasmsdk/smartcontract.go index e77cf446b..87f7db20f 100644 --- a/wasmsdk/smartcontract.go +++ b/wasmsdk/smartcontract.go @@ -3,9 +3,9 @@ package main import ( "encoding/json" - "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/transaction" ) func faucet(methodName, input string, token float64) (*transaction.Transaction, error) { diff --git a/wasmsdk/statusbar.go b/wasmsdk/statusbar.go index 526e2e4f7..000cc20fc 100644 --- a/wasmsdk/statusbar.go +++ b/wasmsdk/statusbar.go @@ -7,8 +7,8 @@ import ( "path" "sync" - "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/sys" "gopkg.in/cheggaaa/pb.v1" ) diff --git a/wasmsdk/tokenrate.go b/wasmsdk/tokenrate.go index 66cc05f0d..3d3253715 100644 --- a/wasmsdk/tokenrate.go +++ b/wasmsdk/tokenrate.go @@ -3,7 +3,7 @@ package main import ( "context" - "github.com/0chain/gosdk/core/tokenrate" + "github.com/0chain/gosdk_common/core/tokenrate" ) // getUSDRate gets the USD rate for the given crypto symbol diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index f13020060..2804b8b80 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -10,10 +10,10 @@ import ( "os" "strconv" - "github.com/0chain/gosdk/core/zcncrypto" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/client" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/client" ) func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error { diff --git a/wasmsdk/zbox.go b/wasmsdk/zbox.go index 1d4497eb7..880f5811e 100644 --- a/wasmsdk/zbox.go +++ b/wasmsdk/zbox.go @@ -7,7 +7,7 @@ import ( "context" "errors" - "github.com/0chain/gosdk/zboxapi" + "github.com/0chain/gosdk_common/zboxapi" ) var ( diff --git a/winsdk/allocation.go b/winsdk/allocation.go index f121c2a1f..9a0170773 100644 --- a/winsdk/allocation.go +++ b/winsdk/allocation.go @@ -9,9 +9,9 @@ import ( import ( "encoding/json" - "github.com/0chain/gosdk/zboxapi" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zboxapi" ) // GetAllocation get allocation info diff --git a/winsdk/cache.go b/winsdk/cache.go index b5d4c918f..f3dc5213a 100644 --- a/winsdk/cache.go +++ b/winsdk/cache.go @@ -6,8 +6,8 @@ import ( "errors" "time" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/marker" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/winsdk/helper.go b/winsdk/helper.go index 867ab2677..af594f190 100644 --- a/winsdk/helper.go +++ b/winsdk/helper.go @@ -12,8 +12,8 @@ import ( "os" "path/filepath" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/zboxcore/marker" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/zboxcore/marker" ) func getZcnWorkDir() (string, error) { diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 50820333f..32a47a8bb 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -13,18 +13,18 @@ import ( "os" "path" - "github.com/0chain/gosdk/zboxapi" - "github.com/0chain/gosdk/zboxcore/client" - l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/0chain/gosdk/zcncore" - - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk_common/zboxcore/client" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" + + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/zcncrypto" ) var log logger.Logger diff --git a/winsdk/storage.go b/winsdk/storage.go index d8463c0f0..cdfbaa392 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -14,9 +14,9 @@ import ( "os" "time" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/marker" ) // GetFileStats get file stats of blobbers diff --git a/winsdk/zboxapi.go b/winsdk/zboxapi.go index a98918b42..96684a406 100644 --- a/winsdk/zboxapi.go +++ b/winsdk/zboxapi.go @@ -13,9 +13,9 @@ import ( "encoding/json" "errors" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/zboxapi" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk_common/zboxcore/client" ) var ( diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go index af733d88a..311963a01 100644 --- a/zboxapi/sdk.go +++ b/zboxapi/sdk.go @@ -13,9 +13,9 @@ import ( "github.com/0chain/gosdk/zcncore" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/resty" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/core/resty" ) var log logger.Logger diff --git a/zboxcore/allocationchange/change.go b/zboxcore/allocationchange/change.go index 56fcd9b04..1b2dacb15 100644 --- a/zboxcore/allocationchange/change.go +++ b/zboxcore/allocationchange/change.go @@ -1,7 +1,7 @@ package allocationchange import ( - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/fileref" ) type change struct { diff --git a/zboxcore/allocationchange/copyobject.go b/zboxcore/allocationchange/copyobject.go index 2454cf3b6..fd6b40ed0 100644 --- a/zboxcore/allocationchange/copyobject.go +++ b/zboxcore/allocationchange/copyobject.go @@ -4,10 +4,10 @@ import ( "strings" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/google/uuid" ) diff --git a/zboxcore/allocationchange/createdir.go b/zboxcore/allocationchange/createdir.go index 345e5cbaf..2968702eb 100644 --- a/zboxcore/allocationchange/createdir.go +++ b/zboxcore/allocationchange/createdir.go @@ -5,9 +5,9 @@ import ( "path" "strings" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/google/uuid" ) diff --git a/zboxcore/allocationchange/deletefile.go b/zboxcore/allocationchange/deletefile.go index ae9896c0c..79b99c37b 100644 --- a/zboxcore/allocationchange/deletefile.go +++ b/zboxcore/allocationchange/deletefile.go @@ -4,8 +4,8 @@ import ( "path" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/fileref" ) type DeleteFileChange struct { diff --git a/zboxcore/allocationchange/moveobject.go b/zboxcore/allocationchange/moveobject.go index b913f527b..cc98f8179 100644 --- a/zboxcore/allocationchange/moveobject.go +++ b/zboxcore/allocationchange/moveobject.go @@ -5,10 +5,10 @@ import ( "strings" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/google/uuid" ) diff --git a/zboxcore/allocationchange/newfile.go b/zboxcore/allocationchange/newfile.go index cdc501e4f..559267e3c 100644 --- a/zboxcore/allocationchange/newfile.go +++ b/zboxcore/allocationchange/newfile.go @@ -7,12 +7,12 @@ import ( "strings" zError "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/google/uuid" ) diff --git a/zboxcore/allocationchange/renameobject.go b/zboxcore/allocationchange/renameobject.go index dc5471a65..8f621418e 100644 --- a/zboxcore/allocationchange/renameobject.go +++ b/zboxcore/allocationchange/renameobject.go @@ -4,9 +4,9 @@ import ( "path" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/zboxcore/fileref" ) type RenameFileChange struct { diff --git a/zboxcore/allocationchange/updatefile.go b/zboxcore/allocationchange/updatefile.go index b95b9669f..eb5ac27df 100644 --- a/zboxcore/allocationchange/updatefile.go +++ b/zboxcore/allocationchange/updatefile.go @@ -4,10 +4,10 @@ import ( "fmt" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" ) type UpdateFileChange struct { diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go index 991558be4..fdfed443f 100644 --- a/zboxcore/blockchain/entity.go +++ b/zboxcore/blockchain/entity.go @@ -7,10 +7,10 @@ import ( "sync" "sync/atomic" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/node" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/node" ) var miners []string diff --git a/zboxcore/client/entity.go b/zboxcore/client/entity.go index e429c4feb..91ba522b4 100644 --- a/zboxcore/client/entity.go +++ b/zboxcore/client/entity.go @@ -5,8 +5,8 @@ import ( "encoding/json" "fmt" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/zcncrypto" ) type SignFunc func(hash string) (string, error) diff --git a/zboxcore/encoder/erasurecode.go b/zboxcore/encoder/erasurecode.go index cb22fd151..95aafea94 100644 --- a/zboxcore/encoder/erasurecode.go +++ b/zboxcore/encoder/erasurecode.go @@ -7,7 +7,7 @@ import ( "errors" - l "github.com/0chain/gosdk/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/klauspost/reedsolomon" ) diff --git a/zboxcore/encryption/pre_test.go b/zboxcore/encryption/pre_test.go index d33779308..28dcc91d5 100644 --- a/zboxcore/encryption/pre_test.go +++ b/zboxcore/encryption/pre_test.go @@ -5,7 +5,7 @@ import ( "math/rand" "testing" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/stretchr/testify/require" "go.dedis.ch/kyber/v3/group/edwards25519" ) diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index c4a60fdfa..5aebc9ee4 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -7,8 +7,8 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/zboxcore/fileref/hashnode.go b/zboxcore/fileref/hashnode.go index 7426aa28d..a19b3c742 100644 --- a/zboxcore/fileref/hashnode.go +++ b/zboxcore/fileref/hashnode.go @@ -4,7 +4,7 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" ) // Hashnode ref node in hash tree diff --git a/zboxcore/fileref/hashnode_test.go b/zboxcore/fileref/hashnode_test.go index f1e81c5c0..6d065b57f 100644 --- a/zboxcore/fileref/hashnode_test.go +++ b/zboxcore/fileref/hashnode_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk_common/core/encryption" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/logger/logger.go b/zboxcore/logger/logger.go index 37a89ee44..cf36a3b33 100644 --- a/zboxcore/logger/logger.go +++ b/zboxcore/logger/logger.go @@ -1,7 +1,7 @@ // Proxy for the core logger package. package logger -import "github.com/0chain/gosdk/core/logger" +import "github.com/0chain/gosdk_common/core/logger" var defaultLogLevel = logger.DEBUG diff --git a/zboxcore/marker/authticket.go b/zboxcore/marker/authticket.go index 781c9d899..79fc0ba4f 100644 --- a/zboxcore/marker/authticket.go +++ b/zboxcore/marker/authticket.go @@ -3,8 +3,8 @@ package marker import ( "fmt" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/zboxcore/client" ) // AuthTicket authentication ticket for file sharing. diff --git a/zboxcore/marker/deletetoken.go b/zboxcore/marker/deletetoken.go index 0c8ae945d..2d7615255 100644 --- a/zboxcore/marker/deletetoken.go +++ b/zboxcore/marker/deletetoken.go @@ -3,8 +3,8 @@ package marker import ( "fmt" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/zboxcore/client" ) type DeleteToken struct { diff --git a/zboxcore/marker/readmarker.go b/zboxcore/marker/readmarker.go index dbc771142..da325627d 100644 --- a/zboxcore/marker/readmarker.go +++ b/zboxcore/marker/readmarker.go @@ -4,10 +4,10 @@ import ( "fmt" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/client" ) type ReadMarker struct { diff --git a/zboxcore/marker/versionmarker.go b/zboxcore/marker/versionmarker.go index b150a3446..2d4571842 100644 --- a/zboxcore/marker/versionmarker.go +++ b/zboxcore/marker/versionmarker.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/client" ) type VersionMarker struct { diff --git a/zboxcore/marker/writemarker.go b/zboxcore/marker/writemarker.go index 4e361b4ea..0f59ab295 100644 --- a/zboxcore/marker/writemarker.go +++ b/zboxcore/marker/writemarker.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/client" ) type WriteMarker struct { diff --git a/zboxcore/mocks/AllocationChange.go b/zboxcore/mocks/AllocationChange.go index 383bab66f..ea2c4bec4 100644 --- a/zboxcore/mocks/AllocationChange.go +++ b/zboxcore/mocks/AllocationChange.go @@ -3,7 +3,7 @@ package mocks import ( - fileref "github.com/0chain/gosdk/zboxcore/fileref" + fileref "github.com/0chain/gosdk_common/zboxcore/fileref" mock "github.com/stretchr/testify/mock" ) diff --git a/zboxcore/mocks/EncryptionScheme.go b/zboxcore/mocks/EncryptionScheme.go index 1fb2ed8be..b62dbdef0 100644 --- a/zboxcore/mocks/EncryptionScheme.go +++ b/zboxcore/mocks/EncryptionScheme.go @@ -3,7 +3,7 @@ package mocks import ( - encryption "github.com/0chain/gosdk/zboxcore/encryption" + encryption "github.com/0chain/gosdk_common/zboxcore/encryption" mock "github.com/stretchr/testify/mock" ) diff --git a/zboxcore/mocks/RefEntity.go b/zboxcore/mocks/RefEntity.go index f3479f8c2..1de18edc5 100644 --- a/zboxcore/mocks/RefEntity.go +++ b/zboxcore/mocks/RefEntity.go @@ -3,7 +3,7 @@ package mocks import ( - common "github.com/0chain/gosdk/core/common" + common "github.com/0chain/gosdk_common/core/common" mock "github.com/stretchr/testify/mock" ) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 4b3bfad27..f1fa9d8d0 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -24,16 +24,16 @@ import ( "github.com/0chain/common/core/currency" "github.com/0chain/errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/mitchellh/go-homedir" "go.uber.org/zap" ) diff --git a/zboxcore/sdk/allocation_file_delete_test.go b/zboxcore/sdk/allocation_file_delete_test.go index 2d22ebeac..3ec084d71 100644 --- a/zboxcore/sdk/allocation_file_delete_test.go +++ b/zboxcore/sdk/allocation_file_delete_test.go @@ -8,13 +8,13 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index af0893c43..16fe464eb 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -13,15 +13,14 @@ import ( "testing" "time" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/pathutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/pathutil" "github.com/hitenjain14/fasthttp" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) @@ -650,7 +649,6 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { require.NoError(t, err) } - // func TestAllocation_RepairFile(t *testing.T) { // const ( // mockFileRefName = "mock file ref name" @@ -926,4 +924,3 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // }) // } // } - diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index e98d2c23c..3df48631e 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -17,21 +17,21 @@ import ( "testing" "time" - "github.com/0chain/gosdk/dev/blobber" - "github.com/0chain/gosdk/dev/blobber/model" - "github.com/0chain/gosdk/zboxcore/encryption" + "github.com/0chain/gosdk_common/dev/blobber" + "github.com/0chain/gosdk_common/dev/blobber/model" + "github.com/0chain/gosdk_common/zboxcore/encryption" "golang.org/x/crypto/sha3" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/sys" - - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/sys" + + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/authticket.go b/zboxcore/sdk/authticket.go index 40a71ccb2..f0db33749 100644 --- a/zboxcore/sdk/authticket.go +++ b/zboxcore/sdk/authticket.go @@ -5,8 +5,8 @@ import ( "encoding/json" "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type AuthTicket struct { diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 15af35bf8..e1d158788 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -11,8 +11,8 @@ import ( "strings" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/client" ) // CreateAllocationForOwner creates a new allocation with the given options (txn: `storagesc.new_allocation_request`). diff --git a/zboxcore/sdk/blobber_operations_mobile.go b/zboxcore/sdk/blobber_operations_mobile.go index 2d87f4fb9..e2d22fd62 100644 --- a/zboxcore/sdk/blobber_operations_mobile.go +++ b/zboxcore/sdk/blobber_operations_mobile.go @@ -10,8 +10,8 @@ import ( "strings" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/client" ) // CreateAllocationForOwner creates a new allocation with the given options (txn: `storagesc.new_allocation_request`). diff --git a/zboxcore/sdk/blockdownloadworker.go b/zboxcore/sdk/blockdownloadworker.go index 7dc4d5375..e7663c2d5 100644 --- a/zboxcore/sdk/blockdownloadworker.go +++ b/zboxcore/sdk/blockdownloadworker.go @@ -10,13 +10,13 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - zlogger "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + zlogger "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hitenjain14/fasthttp" "golang.org/x/sync/semaphore" ) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index b6bea2232..ec3a7a14a 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -16,18 +16,18 @@ import ( "errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - coreEncryption "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + coreEncryption "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/google/uuid" "github.com/klauspost/reedsolomon" ) diff --git a/zboxcore/sdk/chunked_upload_bench_test.go b/zboxcore/sdk/chunked_upload_bench_test.go index 19ec6c6b3..156234f12 100644 --- a/zboxcore/sdk/chunked_upload_bench_test.go +++ b/zboxcore/sdk/chunked_upload_bench_test.go @@ -8,10 +8,10 @@ import ( "testing" "testing/fstest" - "github.com/0chain/gosdk/dev" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/dev" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type nopeChunkedUploadProgressStorer struct { diff --git a/zboxcore/sdk/chunked_upload_blobber.go b/zboxcore/sdk/chunked_upload_blobber.go index 96d370b65..58430ff70 100644 --- a/zboxcore/sdk/chunked_upload_blobber.go +++ b/zboxcore/sdk/chunked_upload_blobber.go @@ -14,14 +14,14 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hitenjain14/fasthttp" "github.com/valyala/bytebufferpool" "golang.org/x/sync/errgroup" @@ -239,7 +239,7 @@ func (sb *ChunkedUploadBlobber) processCommit(ctx context.Context, su *ChunkedUp formWriter.Close() - req, err := zboxutil.NewCommitRequest(sb.blobber.Baseurl, su.allocationObj.ID, su.allocationObj.Tx, body) + req, err := zboxutil.NewCommitRequest(sb.blobber.Baseurl, su.allocationObj.ID, su.allocationObj.Tx, body, 0, su.allocationObj.Owner) if err != nil { logger.Logger.Error("Error creating commit req: ", err) return err diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index 9bd5fd223..b4cd8d846 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -7,10 +7,10 @@ import ( "sync" "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/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" "github.com/valyala/bytebufferpool" ) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go b/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go index d1962d869..a6bd3ae45 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go @@ -4,8 +4,8 @@ import ( "bytes" "testing" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" ) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader_test.go b/zboxcore/sdk/chunked_upload_chunk_reader_test.go index 1533b5cea..7d21b4f80 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader_test.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader_test.go @@ -5,8 +5,8 @@ import ( "math" "testing" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/chunked_upload_form_builder.go b/zboxcore/sdk/chunked_upload_form_builder.go index 9aa08781a..643364104 100644 --- a/zboxcore/sdk/chunked_upload_form_builder.go +++ b/zboxcore/sdk/chunked_upload_form_builder.go @@ -7,7 +7,7 @@ import ( "io" "mime/multipart" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/client" "golang.org/x/crypto/sha3" ) diff --git a/zboxcore/sdk/chunked_upload_hasher.go b/zboxcore/sdk/chunked_upload_hasher.go index 9a0c96f99..1467723c0 100644 --- a/zboxcore/sdk/chunked_upload_hasher.go +++ b/zboxcore/sdk/chunked_upload_hasher.go @@ -7,8 +7,8 @@ import ( "sync" "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/util" ) // Hasher interface to gather all hasher related functions. diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index 07afe342b..c03a54505 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -10,11 +10,11 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/google/uuid" "github.com/klauspost/reedsolomon" "golang.org/x/crypto/sha3" diff --git a/zboxcore/sdk/chunked_upload_option.go b/zboxcore/sdk/chunked_upload_option.go index 38eddf491..a26b14ab2 100644 --- a/zboxcore/sdk/chunked_upload_option.go +++ b/zboxcore/sdk/chunked_upload_option.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" ) diff --git a/zboxcore/sdk/chunked_upload_process.go b/zboxcore/sdk/chunked_upload_process.go index 597217612..f91943f72 100644 --- a/zboxcore/sdk/chunked_upload_process.go +++ b/zboxcore/sdk/chunked_upload_process.go @@ -10,7 +10,7 @@ import ( "sync/atomic" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) // createUploadProgress create a new UploadProgress diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index bc8db2ef0..c450bf1f6 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -18,11 +18,11 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" "github.com/hack-pad/safejs" "github.com/hitenjain14/fasthttp" diff --git a/zboxcore/sdk/chunked_upload_progress_storer.go b/zboxcore/sdk/chunked_upload_progress_storer.go index a21bc4a1d..a57d4f9ed 100644 --- a/zboxcore/sdk/chunked_upload_progress_storer.go +++ b/zboxcore/sdk/chunked_upload_progress_storer.go @@ -9,10 +9,10 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) // ChunkedUploadProgressStorer load and save upload progress diff --git a/zboxcore/sdk/chunked_upload_web_streaming.go b/zboxcore/sdk/chunked_upload_web_streaming.go index ea09ae558..c1f4cef21 100644 --- a/zboxcore/sdk/chunked_upload_web_streaming.go +++ b/zboxcore/sdk/chunked_upload_web_streaming.go @@ -11,7 +11,7 @@ import ( "strings" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/logger" ) // Converting the video file to fmp4 format for web streaming diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index 33e1fb664..e5aff6a96 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -16,14 +16,14 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type ReferencePathResult struct { @@ -147,7 +147,7 @@ func (req *CommitRequest) commitBlobber() (err error) { l.Logger.Error("Creating form writer failed: ", err) return } - httpreq, err := zboxutil.NewCommitRequest(req.blobber.Baseurl, req.allocationID, req.allocationTx, body) + httpreq, err := zboxutil.NewCommitRequest(req.blobber.Baseurl, req.allocationID, req.allocationTx, body, 0) if err != nil { l.Logger.Error("Error creating commit req: ", err) return diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 147d86acb..4bcf6df6a 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -13,11 +13,11 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) const alreadyExists = "file already exists" diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 9210e5593..e0dd398ac 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -15,17 +15,17 @@ import ( "github.com/0chain/errors" "github.com/google/uuid" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type CopyRequest struct { diff --git a/zboxcore/sdk/copyworker_test.go b/zboxcore/sdk/copyworker_test.go index da6309a62..d27c2a00f 100644 --- a/zboxcore/sdk/copyworker_test.go +++ b/zboxcore/sdk/copyworker_test.go @@ -15,15 +15,15 @@ import ( "testing" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/dev" - devMock "github.com/0chain/gosdk/dev/mock" - "github.com/0chain/gosdk/sdks/blobber" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/dev" + devMock "github.com/0chain/gosdk_common/dev/mock" + "github.com/0chain/gosdk_common/sdks/blobber" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index 33fa1e8bc..fa9e07d22 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -16,15 +16,15 @@ import ( thrown "github.com/0chain/errors" "github.com/google/uuid" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type DeleteRequest struct { diff --git a/zboxcore/sdk/deleteworker_test.go b/zboxcore/sdk/deleteworker_test.go index c028be551..32cf119f0 100644 --- a/zboxcore/sdk/deleteworker_test.go +++ b/zboxcore/sdk/deleteworker_test.go @@ -14,13 +14,13 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/dirworker.go b/zboxcore/sdk/dirworker.go index 27d2c5f93..3ea0c2dc3 100644 --- a/zboxcore/sdk/dirworker.go +++ b/zboxcore/sdk/dirworker.go @@ -13,15 +13,15 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/google/uuid" ) diff --git a/zboxcore/sdk/download_progress_storer.go b/zboxcore/sdk/download_progress_storer.go index dce3ace95..22b1ac05d 100644 --- a/zboxcore/sdk/download_progress_storer.go +++ b/zboxcore/sdk/download_progress_storer.go @@ -9,7 +9,7 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" ) type DownloadProgressStorer interface { diff --git a/zboxcore/sdk/downloader.go b/zboxcore/sdk/downloader.go index b2aa4062f..13e658c0b 100644 --- a/zboxcore/sdk/downloader.go +++ b/zboxcore/sdk/downloader.go @@ -5,8 +5,8 @@ import ( "errors" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/fileref" ) // Downloader downloader for file, blocks and thumbnail diff --git a/zboxcore/sdk/downloader_option.go b/zboxcore/sdk/downloader_option.go index 0dca50557..4679267f8 100644 --- a/zboxcore/sdk/downloader_option.go +++ b/zboxcore/sdk/downloader_option.go @@ -1,6 +1,6 @@ package sdk -import "github.com/0chain/gosdk/core/sys" +import "github.com/0chain/gosdk_common/core/sys" const DefaultBlocksPerMarker int = 100 diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index e7d4d9c81..c0033aa2a 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -20,16 +20,16 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" "go.dedis.ch/kyber/v3/group/edwards25519" "golang.org/x/sync/errgroup" diff --git a/zboxcore/sdk/downloadworker_test.go b/zboxcore/sdk/downloadworker_test.go index 30df15948..d3bf5c234 100644 --- a/zboxcore/sdk/downloadworker_test.go +++ b/zboxcore/sdk/downloadworker_test.go @@ -6,7 +6,7 @@ import ( "sync" "testing" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/require" "golang.org/x/crypto/sha3" ) diff --git a/zboxcore/sdk/filemetaworker.go b/zboxcore/sdk/filemetaworker.go index 2a8595e2b..3ff148ff1 100644 --- a/zboxcore/sdk/filemetaworker.go +++ b/zboxcore/sdk/filemetaworker.go @@ -11,11 +11,11 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type fileMetaResponse struct { diff --git a/zboxcore/sdk/filemetaworker_test.go b/zboxcore/sdk/filemetaworker_test.go index 2b37c8e95..4a03106f8 100644 --- a/zboxcore/sdk/filemetaworker_test.go +++ b/zboxcore/sdk/filemetaworker_test.go @@ -17,13 +17,13 @@ import ( "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index 473d30788..d0f1be1cd 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -13,11 +13,11 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type ObjectTreeResult struct { diff --git a/zboxcore/sdk/filestatsworker.go b/zboxcore/sdk/filestatsworker.go index 4861322bd..b3659e95d 100644 --- a/zboxcore/sdk/filestatsworker.go +++ b/zboxcore/sdk/filestatsworker.go @@ -11,10 +11,10 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) // FileStats - file stats structure diff --git a/zboxcore/sdk/filestatsworker_test.go b/zboxcore/sdk/filestatsworker_test.go index 60a3e17a0..dc7113c5d 100644 --- a/zboxcore/sdk/filestatsworker_test.go +++ b/zboxcore/sdk/filestatsworker_test.go @@ -14,13 +14,13 @@ import ( "testing" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index f3637c80b..9942a9a50 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -12,12 +12,12 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) const CHUNK_SIZE = 64 * 1024 diff --git a/zboxcore/sdk/listworker_test.go b/zboxcore/sdk/listworker_test.go index eacea00ea..b6c5bf1b0 100644 --- a/zboxcore/sdk/listworker_test.go +++ b/zboxcore/sdk/listworker_test.go @@ -14,13 +14,13 @@ import ( "testing" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/live_upload.go b/zboxcore/sdk/live_upload.go index 37b22a7ca..d5840fa17 100644 --- a/zboxcore/sdk/live_upload.go +++ b/zboxcore/sdk/live_upload.go @@ -1,6 +1,6 @@ package sdk -import "github.com/0chain/gosdk/zboxcore/zboxutil" +import "github.com/0chain/gosdk_common/zboxcore/zboxutil" // LiveUpload live streaming video upload manager type LiveUpload struct { diff --git a/zboxcore/sdk/live_upload_reader.go b/zboxcore/sdk/live_upload_reader.go index 019293018..77827ff4a 100644 --- a/zboxcore/sdk/live_upload_reader.go +++ b/zboxcore/sdk/live_upload_reader.go @@ -9,7 +9,7 @@ import ( "syscall" "time" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" "github.com/h2non/filetype" ) diff --git a/zboxcore/sdk/m3u8.go b/zboxcore/sdk/m3u8.go index 3accec4c1..bcc21d06c 100644 --- a/zboxcore/sdk/m3u8.go +++ b/zboxcore/sdk/m3u8.go @@ -8,7 +8,7 @@ import ( "strconv" "time" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" ) // #EXTM3U diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 28af96d4d..efbdad4a9 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -15,16 +15,16 @@ import ( thrown "github.com/0chain/errors" "github.com/google/uuid" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type MoveRequest struct { diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 32a7f7658..2d2f6c19a 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -13,14 +13,14 @@ import ( "github.com/0chain/errors" "github.com/remeh/sizedwaitgroup" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - l "github.com/0chain/gosdk/zboxcore/logger" - - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" + + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/google/uuid" ) diff --git a/zboxcore/sdk/networkworker.go b/zboxcore/sdk/networkworker.go index 276fca806..0cd8359e6 100644 --- a/zboxcore/sdk/networkworker.go +++ b/zboxcore/sdk/networkworker.go @@ -9,14 +9,14 @@ import ( "strconv" "time" - "github.com/0chain/gosdk/core/node" - l "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk_common/core/node" + l "github.com/0chain/gosdk_common/zboxcore/logger" "go.uber.org/zap" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) const NETWORK_ENDPOINT = "/network" diff --git a/zboxcore/sdk/playlist.go b/zboxcore/sdk/playlist.go index 52c464ff6..edb8fd9c2 100644 --- a/zboxcore/sdk/playlist.go +++ b/zboxcore/sdk/playlist.go @@ -7,13 +7,13 @@ import ( "net/url" "strings" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type PlaylistFile struct { diff --git a/zboxcore/sdk/reader.go b/zboxcore/sdk/reader.go index 711bc9c15..943d6df97 100644 --- a/zboxcore/sdk/reader.go +++ b/zboxcore/sdk/reader.go @@ -10,8 +10,8 @@ import ( "sync" "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) const ( diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index 48deac045..591a9bc2a 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -16,16 +16,16 @@ import ( "github.com/0chain/errors" "github.com/google/uuid" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" - - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" + + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type RenameRequest struct { diff --git a/zboxcore/sdk/renameworker_test.go b/zboxcore/sdk/renameworker_test.go index e43a66d83..7deb124bf 100644 --- a/zboxcore/sdk/renameworker_test.go +++ b/zboxcore/sdk/renameworker_test.go @@ -15,15 +15,15 @@ import ( "testing" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/dev" - devMock "github.com/0chain/gosdk/dev/mock" - "github.com/0chain/gosdk/sdks/blobber" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/dev" + devMock "github.com/0chain/gosdk_common/dev/mock" + "github.com/0chain/gosdk_common/sdks/blobber" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/repairCallback.go b/zboxcore/sdk/repairCallback.go index 1e122e848..0c70c4614 100644 --- a/zboxcore/sdk/repairCallback.go +++ b/zboxcore/sdk/repairCallback.go @@ -3,7 +3,7 @@ package sdk import ( "sync" - l "github.com/0chain/gosdk/zboxcore/logger" + l "github.com/0chain/gosdk_common/zboxcore/logger" ) var ( diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index 8c181b85f..6ce65734a 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -7,11 +7,11 @@ import ( "sync" "time" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "go.uber.org/zap" ) diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 488b113ff..f90de5d33 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -18,11 +18,11 @@ import ( "github.com/0chain/common/core/common" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "go.uber.org/zap" ) diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 0b95eccf6..bba563756 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -12,21 +12,22 @@ import ( "github.com/0chain/common/core/currency" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/node" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/core/node" "gopkg.in/natefinch/lumberjack.v2" - "github.com/0chain/gosdk/core/common" - enc "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/core/version" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/encryption" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/common" + enc "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/core/version" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + zboxclient "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/encryption" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/marker" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) const STORAGE_SCADDRESS = "6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d7" @@ -119,7 +120,7 @@ func InitStorageSDK(walletJSON string, preferredBlobbers []string, nonce int64, fee ...uint64) error { - err := client.PopulateClient(walletJSON, signatureScheme) + err := zboxclient.PopulateClient(walletJSON, signatureScheme) if err != nil { return err } @@ -132,7 +133,7 @@ func InitStorageSDK(walletJSON string, return err } - client.SetClientNonce(nonce) + zboxclient.SetClientNonce(nonce) if len(fee) > 0 { client.SetTxnFee(fee[0]) } @@ -226,12 +227,12 @@ func GetReadPoolInfo(clientID string) (info *ReadPool, err error) { } if clientID == "" { - clientID = client.GetClientID() + clientID = zboxclient.GetClientID() } var b []byte - b, err = zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getReadPoolStat", - map[string]string{"client_id": clientID}, nil) + b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getReadPoolStat", + map[string]string{"client_id": clientID}) if err != nil { return nil, errors.Wrap(err, "error requesting read pool info") } @@ -305,8 +306,8 @@ func GetStakePoolInfo(providerType ProviderType, providerID string) (info *Stake } var b []byte - b, err = zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", - map[string]string{"provider_type": strconv.Itoa(int(providerType)), "provider_id": providerID}, nil) + b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", + map[string]string{"provider_type": strconv.Itoa(int(providerType)), "provider_id": providerID}) if err != nil { return nil, errors.Wrap(err, "error requesting stake pool info:") } @@ -337,7 +338,7 @@ func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUs return nil, sdkNotInitialized } if clientID == "" { - clientID = client.GetClientID() + clientID = zboxclient.GetClientID() } var b []byte @@ -346,8 +347,8 @@ func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUs "offset": strconv.FormatInt(int64(offset), 10), "limit": strconv.FormatInt(int64(limit), 10), } - b, err = zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/getUserStakePoolStat", params, nil) + b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, + "/getUserStakePoolStat", params) if err != nil { return nil, errors.Wrap(err, "error requesting stake pool user info:") } @@ -398,9 +399,8 @@ func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { } var b []byte - b, err = zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/getChallengePoolStat", map[string]string{"allocation_id": allocID}, - nil) + b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, + "/getChallengePoolStat", map[string]string{"allocation_id": allocID}) if err != nil { return nil, errors.Wrap(err, "error requesting challenge pool info:") } @@ -423,10 +423,8 @@ func GetMptData(key string) ([]byte, error) { } var b []byte - b, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/get_mpt_key", map[string]string{"key": key}, - nil, - ) + b, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, + "/get_mpt_key", map[string]string{"key": key}) if err != nil { return nil, errors.Wrap(err, "error requesting mpt key data:") } @@ -452,8 +450,7 @@ func GetStorageSCConfig() (conf *InputMap, err error) { } var b []byte - b, err = zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/storage-config", nil, - nil) + b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/storage-config", nil) if err != nil { return nil, errors.Wrap(err, "error requesting storage SC configs:") } @@ -627,7 +624,7 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe offset, strconv.FormatBool(stakable), ) - b, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, url, nil, nil) + b, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, url, nil) var wrap nodes if err != nil { return nil, errors.Wrap(err, "error requesting blobbers:") @@ -685,11 +682,10 @@ func GetBlobber(blobberID string) (blob *Blobber, err error) { return nil, sdkNotInitialized } var b []byte - b, err = zboxutil.MakeSCRestAPICall( + b, err = client.MakeSCRestAPICall( STORAGE_SCADDRESS, "/getBlobber", - map[string]string{"blobber_id": blobberID}, - nil) + map[string]string{"blobber_id": blobberID}) if err != nil { return nil, errors.Wrap(err, "requesting blobber:") } @@ -710,11 +706,10 @@ func GetValidator(validatorID string) (validator *Validator, err error) { return nil, sdkNotInitialized } var b []byte - b, err = zboxutil.MakeSCRestAPICall( + b, err = client.MakeSCRestAPICall( STORAGE_SCADDRESS, "/get_validator", - map[string]string{"validator_id": validatorID}, - nil) + map[string]string{"validator_id": validatorID}) if err != nil { return nil, errors.Wrap(err, "requesting validator:") } @@ -735,13 +730,12 @@ func GetValidators(stakable bool) (validators []*Validator, err error) { return nil, sdkNotInitialized } var b []byte - b, err = zboxutil.MakeSCRestAPICall( + b, err = client.MakeSCRestAPICall( STORAGE_SCADDRESS, "/validators", map[string]string{ "stakable": strconv.FormatBool(stakable), - }, - nil) + }) if err != nil { return nil, errors.Wrap(err, "requesting validator list") } @@ -799,7 +793,7 @@ func GetAllocation(allocationID string) (*Allocation, error) { } params := make(map[string]string) params["allocation"] = allocationID - allocationBytes, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params, nil) + allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return nil, errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } @@ -831,7 +825,7 @@ func GetAllocationUpdates(allocation *Allocation) error { params := make(map[string]string) params["allocation"] = allocation.ID - allocationBytes, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params, nil) + allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } @@ -876,7 +870,7 @@ func SetNumBlockDownloads(num int) { // // returns the list of allocations and error if any func GetAllocations() ([]*Allocation, error) { - return GetAllocationsForClient(client.GetClientID()) + return GetAllocationsForClient(zboxclient.GetClientID()) } func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, error) { @@ -884,7 +878,7 @@ func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, params["client"] = clientID params["limit"] = fmt.Sprint(limit) params["offset"] = fmt.Sprint(offset) - allocationsBytes, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocations", params, nil) + allocationsBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocations", params) if err != nil { return nil, errors.New("allocations_fetch_error", "Error fetching the allocations."+err.Error()) } @@ -971,8 +965,8 @@ type CreateAllocationOptions struct { func CreateAllocationWith(options CreateAllocationOptions) ( string, int64, *transaction.Transaction, error) { - return CreateAllocationForOwner(client.GetClientID(), - client.GetClientPublicKey(), options.DataShards, options.ParityShards, + return CreateAllocationForOwner(zboxclient.GetClientID(), + zboxclient.GetClientPublicKey(), options.DataShards, options.ParityShards, options.Size, options.ReadPrice, options.WritePrice, options.Lock, options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams) } @@ -1011,7 +1005,7 @@ func GetAllocationBlobbers( params["force"] = strconv.FormatBool(force[0]) } - allocBlobber, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params, nil) + allocBlobber, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params) if err != nil { return nil, err } @@ -1096,7 +1090,7 @@ func GetBlobberIds(blobberUrls []string) ([]string, error) { params := make(map[string]string) params["blobber_urls"] = string(urlsStr) - idsStr, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params, nil) + idsStr, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params) if err != nil { return nil, err } @@ -1121,7 +1115,7 @@ func GetFreeAllocationBlobbers(request map[string]interface{}) ([]string, error) params := make(map[string]string) params["free_allocation_data"] = string(data) - allocBlobber, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params, nil) + allocBlobber, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params) if err != nil { return nil, err } @@ -1502,7 +1496,7 @@ func GetUpdateAllocationMinLock( addBlobberId, removeBlobberId string) (int64, error) { updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = client.GetClientID() + updateAllocationRequest["owner_id"] = zboxclient.GetClientID() updateAllocationRequest["owner_public_key"] = "" updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size @@ -1518,7 +1512,7 @@ func GetUpdateAllocationMinLock( params := make(map[string]string) params["data"] = string(data) - responseBytes, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params, nil) + responseBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params) if err != nil { return 0, errors.Wrap(err, "failed to request allocation update min lock") } diff --git a/zboxcore/sdk/sharerequest.go b/zboxcore/sdk/sharerequest.go index 8ead7d00d..898c6238e 100644 --- a/zboxcore/sdk/sharerequest.go +++ b/zboxcore/sdk/sharerequest.go @@ -6,12 +6,12 @@ import ( "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/marker" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type ShareRequest struct { diff --git a/zboxcore/sdk/sync.go b/zboxcore/sdk/sync.go index 0e40ba150..6942693d7 100644 --- a/zboxcore/sdk/sync.go +++ b/zboxcore/sdk/sync.go @@ -13,10 +13,10 @@ import ( "strings" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" ) // For sync app diff --git a/zboxcore/sdk/transaction.go b/zboxcore/sdk/transaction.go index cbf67a452..3603c9783 100644 --- a/zboxcore/sdk/transaction.go +++ b/zboxcore/sdk/transaction.go @@ -9,9 +9,9 @@ import ( "errors" - "github.com/0chain/gosdk/core/transaction" - l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/transaction" + l "github.com/0chain/gosdk_common/zboxcore/logger" ) type transactionCallback struct { diff --git a/zboxcore/sdk/transaction_mobile.go b/zboxcore/sdk/transaction_mobile.go index 3c28cb62b..cc426f19b 100644 --- a/zboxcore/sdk/transaction_mobile.go +++ b/zboxcore/sdk/transaction_mobile.go @@ -9,9 +9,9 @@ import ( "errors" - "github.com/0chain/gosdk/core/transaction" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/transaction" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zcncore" ) type transactionCallback struct { diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index 582580af0..e76aa6dd8 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -7,12 +7,12 @@ import ( "io" "strings" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/fileref" + l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/google/uuid" "go.uber.org/zap" ) diff --git a/zboxcore/sdk/writemarker_mutex.go b/zboxcore/sdk/writemarker_mutex.go index e29d46a61..401ab90ff 100644 --- a/zboxcore/sdk/writemarker_mutex.go +++ b/zboxcore/sdk/writemarker_mutex.go @@ -10,11 +10,11 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) type WMLockStatus int diff --git a/zboxcore/sdk/writemarker_mutex_test.go b/zboxcore/sdk/writemarker_mutex_test.go index 8d8358970..150f12967 100644 --- a/zboxcore/sdk/writemarker_mutex_test.go +++ b/zboxcore/sdk/writemarker_mutex_test.go @@ -12,10 +12,10 @@ import ( "testing" "time" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/zboxcore/mocks" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/zboxutil/download_buffer.go b/zboxcore/zboxutil/download_buffer.go index ab1e17f70..b51a169c4 100644 --- a/zboxcore/zboxutil/download_buffer.go +++ b/zboxcore/zboxutil/download_buffer.go @@ -5,7 +5,7 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" "github.com/valyala/bytebufferpool" ) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 8299a5bef..ddf6dbd19 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -17,11 +17,11 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/zboxcore/blockchain" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/client" lru "github.com/hashicorp/golang-lru/v2" "github.com/hashicorp/golang-lru/v2/simplelru" "github.com/hitenjain14/fasthttp" diff --git a/zboxcore/zboxutil/util.go b/zboxcore/zboxutil/util.go index b61ed887c..966cc35d3 100644 --- a/zboxcore/zboxutil/util.go +++ b/zboxcore/zboxutil/util.go @@ -19,8 +19,8 @@ import ( "errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/zboxcore/allocationchange" - "github.com/0chain/gosdk/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/h2non/filetype" "github.com/hitenjain14/fasthttp" "github.com/lithammer/shortuuid/v3" diff --git a/zcnbridge/authorizer/proofBurnTicket.go b/zcnbridge/authorizer/proofBurnTicket.go index 84ecdec18..b05b1ac3c 100644 --- a/zcnbridge/authorizer/proofBurnTicket.go +++ b/zcnbridge/authorizer/proofBurnTicket.go @@ -4,14 +4,14 @@ import ( "encoding/json" "fmt" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk/zcnbridge" + "github.com/0chain/gosdk_common/zcnbridge" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/zcnbridge/errors" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/zcnbridge/errors" ) type ProofOfBurn struct { diff --git a/zcnbridge/authorizer/proofBurnTicket_test.go b/zcnbridge/authorizer/proofBurnTicket_test.go index b844cf048..d0d4a2537 100644 --- a/zcnbridge/authorizer/proofBurnTicket_test.go +++ b/zcnbridge/authorizer/proofBurnTicket_test.go @@ -6,8 +6,8 @@ import ( "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk/core/zcncrypto" "github.com/0chain/gosdk/zcnbridge/authorizer" + "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) diff --git a/zcnbridge/authorizers_query.go b/zcnbridge/authorizers_query.go index 43f161a3b..b5e3ad432 100644 --- a/zcnbridge/authorizers_query.go +++ b/zcnbridge/authorizers_query.go @@ -9,7 +9,6 @@ import ( "strings" "sync" - "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zcnbridge/errors" "github.com/0chain/gosdk/zcnbridge/ethereum" h "github.com/0chain/gosdk/zcnbridge/http" @@ -17,6 +16,7 @@ import ( "github.com/0chain/gosdk/zcnbridge/wallet" "github.com/0chain/gosdk/zcnbridge/zcnsc" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/common" "go.uber.org/zap" ) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 3cbf6b866..9e9b1c35e 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -19,13 +19,13 @@ import ( "gopkg.in/natefinch/lumberjack.v2" - "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/zcnbridge/ethereum" "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" "github.com/0chain/gosdk/zcnbridge/ethereum/nftconfig" "github.com/0chain/gosdk/zcnbridge/log" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/0chain/gosdk/zcnbridge/wallet" @@ -155,7 +155,7 @@ func (b *BridgeClient) RemoveEthereumAuthorizer(ctx context.Context, address com } // AddEthereumAuthorizers add bridge authorizers to the Ethereum authorizers contract -// - configDir - configuration directory +// - configDir - configuration directory func (b *BridgeClient) AddEthereumAuthorizers(configDir string) { cfg := viper.New() cfg.AddConfigPath(configDir) diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go index 724b2d4e4..fa35878cb 100644 --- a/zcnbridge/bridge_helper.go +++ b/zcnbridge/bridge_helper.go @@ -5,8 +5,8 @@ import ( "math/big" "time" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zcncore" "github.com/pkg/errors" ) diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 8718baffc..90bd60f55 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -4,8 +4,6 @@ import ( "context" "encoding/hex" "encoding/json" - "github.com/0chain/gosdk/zcnbridge/ethereum/uniswapnetwork" - "github.com/ethereum/go-ethereum/accounts/abi" "log" "math/big" "os" @@ -14,9 +12,11 @@ import ( "testing" "time" + "github.com/0chain/gosdk/zcnbridge/ethereum/uniswapnetwork" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" - sdkcommon "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zcnbridge/ethereum" "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" @@ -26,6 +26,7 @@ import ( "github.com/0chain/gosdk/zcnbridge/wallet" "github.com/0chain/gosdk/zcnbridge/zcnsc" "github.com/0chain/gosdk/zcncore" + sdkcommon "github.com/0chain/gosdk_common/core/common" eth "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/keystore" diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 09bae207a..f30fb1c20 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -8,8 +8,8 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/0chain/gosdk/zcnbridge/log" - "github.com/0chain/gosdk/zcnbridge/transaction" + "github.com/0chain/gosdk_common/zcnbridge/log" + "github.com/0chain/gosdk_common/zcnbridge/transaction" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" diff --git a/zcnbridge/http/client.go b/zcnbridge/http/client.go index 008c4ad3c..a8044cab7 100644 --- a/zcnbridge/http/client.go +++ b/zcnbridge/http/client.go @@ -4,7 +4,6 @@ import ( "net/http" "time" - "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/hashicorp/go-retryablehttp" ) @@ -16,13 +15,13 @@ const ( // NewClient creates default http.Client with timeouts. func NewClient() *http.Client { return &http.Client{ - Transport: zboxutil.DefaultTransport, + Transport: http.DefaultTransport, } } func CleanClient() *http.Client { client := &http.Client{ - Transport: zboxutil.DefaultTransport, + Transport: http.DefaultTransport, } client.Timeout = 250 * time.Second return client @@ -32,7 +31,7 @@ func CleanClient() *http.Client { func NewRetryableClient(verbose bool) *retryablehttp.Client { client := retryablehttp.NewClient() client.HTTPClient = &http.Client{ - Transport: zboxutil.DefaultTransport, + Transport: http.DefaultTransport, } if !verbose { diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go index 87bfee4f9..c335f2de3 100644 --- a/zcnbridge/http/rest.go +++ b/zcnbridge/http/rest.go @@ -13,10 +13,10 @@ import ( "go.uber.org/zap" "gopkg.in/natefinch/lumberjack.v2" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zcnbridge/errors" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/core/util" ) const ( diff --git a/zcnbridge/http/rest_test.go b/zcnbridge/http/rest_test.go index feff0d7cf..0b34363ed 100644 --- a/zcnbridge/http/rest_test.go +++ b/zcnbridge/http/rest_test.go @@ -3,7 +3,7 @@ package http import ( "testing" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" "github.com/stretchr/testify/require" ) diff --git a/zcnbridge/log/handler.go b/zcnbridge/log/handler.go index f99b41730..8c08faa08 100644 --- a/zcnbridge/log/handler.go +++ b/zcnbridge/log/handler.go @@ -5,7 +5,7 @@ import ( "os" "strings" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" ) // HandleFunc returns handle function that writes logs to http.ResponseWriter with provided buffer size. diff --git a/zcnbridge/log/logging.go b/zcnbridge/log/logging.go index d3faac3df..b0317797c 100644 --- a/zcnbridge/log/logging.go +++ b/zcnbridge/log/logging.go @@ -7,7 +7,7 @@ import ( "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" - "github.com/0chain/gosdk/zcnbridge/errors" + "github.com/0chain/gosdk_common/zcnbridge/errors" ) var ( diff --git a/zcnbridge/mocks/Transaction.go b/zcnbridge/mocks/Transaction.go index ae323f12b..f8b3b3576 100644 --- a/zcnbridge/mocks/Transaction.go +++ b/zcnbridge/mocks/Transaction.go @@ -5,10 +5,10 @@ package mocks import ( context "context" - transaction "github.com/0chain/gosdk/zcnbridge/transaction" + transaction "github.com/0chain/gosdk_common/zcnbridge/transaction" mock "github.com/stretchr/testify/mock" - zcncore "github.com/0chain/gosdk/zcncore" + zcncore "github.com/0chain/gosdk_common/zcncore" ) // Transaction is an autogenerated mock type for the Transaction type diff --git a/zcnbridge/mocks/TransactionCallbackAwaitable.go b/zcnbridge/mocks/TransactionCallbackAwaitable.go index 9966f8fba..e0d78c05c 100644 --- a/zcnbridge/mocks/TransactionCallbackAwaitable.go +++ b/zcnbridge/mocks/TransactionCallbackAwaitable.go @@ -7,7 +7,7 @@ import ( mock "github.com/stretchr/testify/mock" - zcncore "github.com/0chain/gosdk/zcncore" + zcncore "github.com/0chain/gosdk_common/zcncore" ) // TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type diff --git a/zcnbridge/mocks/TransactionProvider.go b/zcnbridge/mocks/TransactionProvider.go index 2ca8c875b..bfb7864d3 100644 --- a/zcnbridge/mocks/TransactionProvider.go +++ b/zcnbridge/mocks/TransactionProvider.go @@ -3,7 +3,7 @@ package mocks import ( - transaction "github.com/0chain/gosdk/zcnbridge/transaction" + transaction "github.com/0chain/gosdk_common/zcnbridge/transaction" mock "github.com/stretchr/testify/mock" ) diff --git a/zcnbridge/rest.go b/zcnbridge/rest.go index 866d9beb5..326d976e3 100644 --- a/zcnbridge/rest.go +++ b/zcnbridge/rest.go @@ -3,7 +3,7 @@ package zcnbridge import ( "fmt" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk/zcnbridge/http" "github.com/0chain/gosdk/zcnbridge/wallet" diff --git a/zcnbridge/transaction/functions.go b/zcnbridge/transaction/functions.go index 07d803e36..5022232cd 100644 --- a/zcnbridge/transaction/functions.go +++ b/zcnbridge/transaction/functions.go @@ -5,7 +5,7 @@ package transaction import ( "context" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // AddAuthorizer adds authorizer to the bridge diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go index 9d886f773..629b8bfab 100644 --- a/zcnbridge/transaction/txn.go +++ b/zcnbridge/transaction/txn.go @@ -7,10 +7,10 @@ import ( "strconv" "strings" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/zcnbridge/errors" - ctime "github.com/0chain/gosdk/zcnbridge/time" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zcnbridge/errors" + ctime "github.com/0chain/gosdk_common/zcnbridge/time" + "github.com/0chain/gosdk_common/zcncore" ) var ( diff --git a/zcnbridge/wallet/wallet.go b/zcnbridge/wallet/wallet.go index 74168b313..1f98a571e 100644 --- a/zcnbridge/wallet/wallet.go +++ b/zcnbridge/wallet/wallet.go @@ -1,7 +1,7 @@ package wallet import ( - "github.com/0chain/gosdk/core/logger" + "github.com/0chain/gosdk_common/core/logger" "gopkg.in/natefinch/lumberjack.v2" ) diff --git a/zcnbridge/zcnsc/mint_payload.go b/zcnbridge/zcnsc/mint_payload.go index 921e202b6..2cecac2bf 100644 --- a/zcnbridge/zcnsc/mint_payload.go +++ b/zcnbridge/zcnsc/mint_payload.go @@ -3,7 +3,7 @@ package zcnsc import ( "encoding/json" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" ) // MintPayload Payload to submit to ZCN chain `mint` smart contract diff --git a/zcncore/ethwallet_base.go b/zcncore/ethwallet_base.go index 1a6cbd93b..836ee0b15 100644 --- a/zcncore/ethwallet_base.go +++ b/zcncore/ethwallet_base.go @@ -11,9 +11,9 @@ import ( "regexp" "sync" - "github.com/0chain/gosdk/core/tokenrate" - "github.com/0chain/gosdk/core/zcncrypto" hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" + "github.com/0chain/gosdk_common/core/tokenrate" + "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" diff --git a/zcncore/mocks/TransactionCommon.go b/zcncore/mocks/TransactionCommon.go index ad0236cd7..36734b3cd 100644 --- a/zcncore/mocks/TransactionCommon.go +++ b/zcncore/mocks/TransactionCommon.go @@ -3,7 +3,7 @@ package mocks import ( - transaction "github.com/0chain/gosdk/core/transaction" + transaction "github.com/0chain/gosdk_common/core/transaction" mock "github.com/stretchr/testify/mock" zcncore "github.com/0chain/gosdk/zcncore" diff --git a/zcncore/mocks/TransactionScheme.go b/zcncore/mocks/TransactionScheme.go index eca637f4b..95fb2fbab 100644 --- a/zcncore/mocks/TransactionScheme.go +++ b/zcncore/mocks/TransactionScheme.go @@ -3,7 +3,7 @@ package mocks import ( - transaction "github.com/0chain/gosdk/core/transaction" + transaction "github.com/0chain/gosdk_common/core/transaction" mock "github.com/stretchr/testify/mock" zcncore "github.com/0chain/gosdk/zcncore" diff --git a/zcncore/mswallet.go b/zcncore/mswallet.go index df6f3553e..ad483ba5f 100644 --- a/zcncore/mswallet.go +++ b/zcncore/mswallet.go @@ -8,8 +8,8 @@ import ( "fmt" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/zcncrypto" ) //MSVote -- this should mimic the type Vote defined in MultiSig SC diff --git a/zcncore/mswallet_base.go b/zcncore/mswallet_base.go index c1762cd92..e13191507 100644 --- a/zcncore/mswallet_base.go +++ b/zcncore/mswallet_base.go @@ -9,8 +9,8 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/zcncrypto" ) // MSVoteCallback callback definition multisig Vote function diff --git a/zcncore/mswallet_mobile.go b/zcncore/mswallet_mobile.go index c78e1c66a..97d39bc5a 100644 --- a/zcncore/mswallet_mobile.go +++ b/zcncore/mswallet_mobile.go @@ -9,8 +9,8 @@ import ( "fmt" "strconv" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/zcncrypto" ) type MultisigSCWallet interface { diff --git a/zcncore/networkworker.go b/zcncore/networkworker.go index 2ce4943cb..23fd7d991 100644 --- a/zcncore/networkworker.go +++ b/zcncore/networkworker.go @@ -11,9 +11,9 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/node" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/util" "go.uber.org/zap" ) diff --git a/zcncore/networkworker_mobile.go b/zcncore/networkworker_mobile.go index 92be91f0c..d1bed08fd 100644 --- a/zcncore/networkworker_mobile.go +++ b/zcncore/networkworker_mobile.go @@ -10,9 +10,9 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/node" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/util" "go.uber.org/zap" ) diff --git a/zcncore/transaction.go b/zcncore/transaction.go index 8a7b01972..5047a92b1 100644 --- a/zcncore/transaction.go +++ b/zcncore/transaction.go @@ -13,13 +13,13 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/block" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/node" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/block" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/core/zcncrypto" ) // Provider represents the type of provider. diff --git a/zcncore/transaction_base.go b/zcncore/transaction_base.go index a863b11c8..505e9d818 100644 --- a/zcncore/transaction_base.go +++ b/zcncore/transaction_base.go @@ -10,18 +10,17 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/node" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/fileref" - - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/core/version" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/fileref" + + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/core/version" + "github.com/0chain/gosdk_common/core/zcncrypto" ) var ( @@ -767,7 +766,7 @@ func VerifyContentHash(metaTxnDataJSON string) (bool, error) { return false, errors.New("metaTxnData_decode_error", "Unable to decode metaTxnData json") } - t, err := transaction.VerifyTransaction(metaTxnData.TxnID, blockchain.GetSharders()) + t, err := transaction.VerifyTransaction(metaTxnData.TxnID) if err != nil { return false, errors.New("fetch_txm_details", "Unable to fetch txn details") } diff --git a/zcncore/transaction_mobile.go b/zcncore/transaction_mobile.go index 0454d6fdd..643a82da1 100644 --- a/zcncore/transaction_mobile.go +++ b/zcncore/transaction_mobile.go @@ -13,13 +13,13 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/block" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/node" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/block" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/core/zcncrypto" ) const ( diff --git a/zcncore/transaction_query.go b/zcncore/transaction_query.go index 044d477fc..31520c4aa 100644 --- a/zcncore/transaction_query.go +++ b/zcncore/transaction_query.go @@ -15,8 +15,8 @@ import ( "time" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/util" ) var ( diff --git a/zcncore/transaction_query_mobile.go b/zcncore/transaction_query_mobile.go index 5756b586e..cd9e80399 100644 --- a/zcncore/transaction_query_mobile.go +++ b/zcncore/transaction_query_mobile.go @@ -15,8 +15,8 @@ import ( "time" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/resty" + "github.com/0chain/gosdk_common/core/util" ) var ( diff --git a/zcncore/transactionauth.go b/zcncore/transactionauth.go index 631be73b7..74ff88278 100644 --- a/zcncore/transactionauth.go +++ b/zcncore/transactionauth.go @@ -10,7 +10,7 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk_common/core/transaction" ) func newTransactionWithAuth(cb TransactionCallback, txnFee uint64, nonce int64) (*TransactionWithAuth, error) { diff --git a/zcncore/transactionauth_base.go b/zcncore/transactionauth_base.go index 1217445b4..ad41c099f 100644 --- a/zcncore/transactionauth_base.go +++ b/zcncore/transactionauth_base.go @@ -4,11 +4,11 @@ import ( "encoding/json" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/node" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/client" ) type TransactionWithAuth struct { diff --git a/zcncore/transactionauth_mobile.go b/zcncore/transactionauth_mobile.go index 046ed314c..54de85427 100644 --- a/zcncore/transactionauth_mobile.go +++ b/zcncore/transactionauth_mobile.go @@ -8,7 +8,7 @@ import ( "time" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk_common/core/transaction" ) func newTransactionWithAuth(cb TransactionCallback, txnFee string, nonce int64) (*TransactionWithAuth, error) { diff --git a/zcncore/wallet.go b/zcncore/wallet.go index 90c0b8b7c..7f2b15e3d 100644 --- a/zcncore/wallet.go +++ b/zcncore/wallet.go @@ -4,8 +4,8 @@ package zcncore import ( - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/zcncrypto" ) // GetWallet get a wallet object from a wallet string diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index b756bd3dd..5b89e7fd5 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -16,15 +16,15 @@ import ( stdErrors "errors" "github.com/0chain/errors" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/tokenrate" - "github.com/0chain/gosdk/core/util" - "github.com/0chain/gosdk/core/version" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/encryption" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/core/tokenrate" + "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/core/version" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/encryption" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" openssl "github.com/Luzifer/go-openssl/v3" "gopkg.in/natefinch/lumberjack.v2" ) diff --git a/zcncore/wallet_callback.go b/zcncore/wallet_callback.go index 74447ecc8..7b468f13e 100644 --- a/zcncore/wallet_callback.go +++ b/zcncore/wallet_callback.go @@ -3,7 +3,7 @@ package zcncore import ( "sync" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" ) type walletCallback struct { diff --git a/zcncore/wallet_mobile.go b/zcncore/wallet_mobile.go index 3eae952e8..79526e7d3 100644 --- a/zcncore/wallet_mobile.go +++ b/zcncore/wallet_mobile.go @@ -4,7 +4,7 @@ package zcncore import ( - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk_common/core/zcncrypto" ) // Wallet interface to gather all wallet related functions diff --git a/zcncore/zauth.go b/zcncore/zauth.go index 82e790055..a6e811a27 100644 --- a/zcncore/zauth.go +++ b/zcncore/zauth.go @@ -7,8 +7,8 @@ import ( "io" "net/http" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/zboxcore/client" "github.com/pkg/errors" ) diff --git a/zmagmacore/crypto/keys.go b/zmagmacore/crypto/keys.go index ec8422937..a7393f88a 100644 --- a/zmagmacore/crypto/keys.go +++ b/zmagmacore/crypto/keys.go @@ -6,8 +6,8 @@ import ( "io" "os" - "github.com/0chain/gosdk/core/zcncrypto" "github.com/0chain/gosdk/zmagmacore/errors" + "github.com/0chain/gosdk_common/core/zcncrypto" ) // ReadKeysFile reads file existing in keysFile dir and parses public and private keys from file. diff --git a/zmagmacore/http/sc-api.go b/zmagmacore/http/sc-api.go index c97ff8629..df8e1833d 100644 --- a/zmagmacore/http/sc-api.go +++ b/zmagmacore/http/sc-api.go @@ -9,9 +9,9 @@ import ( "net/http" "net/url" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk/zmagmacore/errors" + "github.com/0chain/gosdk_common/core/util" ) // MakeSCRestAPICall calls smart contract with provided address diff --git a/zmagmacore/log/handler.go b/zmagmacore/log/handler.go index acafcf141..6b4775446 100644 --- a/zmagmacore/log/handler.go +++ b/zmagmacore/log/handler.go @@ -6,7 +6,7 @@ import ( "os" "strings" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" ) // HandleFunc returns handle function that writes logs to http.ResponseWriter with provided buffer size. diff --git a/zmagmacore/magmasc/acknowledgment.go b/zmagmacore/magmasc/acknowledgment.go index bef901ccf..89431e34c 100644 --- a/zmagmacore/magmasc/acknowledgment.go +++ b/zmagmacore/magmasc/acknowledgment.go @@ -4,9 +4,9 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/storage" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/billing.go b/zmagmacore/magmasc/billing.go index f28daf85f..49b0b2bc1 100644 --- a/zmagmacore/magmasc/billing.go +++ b/zmagmacore/magmasc/billing.go @@ -3,9 +3,9 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/time" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/consumer.go b/zmagmacore/magmasc/consumer.go index 988ac715d..7433a9b13 100644 --- a/zmagmacore/magmasc/consumer.go +++ b/zmagmacore/magmasc/consumer.go @@ -3,10 +3,10 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zmagmacore/config" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/node" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/datausage.go b/zmagmacore/magmasc/datausage.go index 6e33daf0a..66d5a995d 100644 --- a/zmagmacore/magmasc/datausage.go +++ b/zmagmacore/magmasc/datausage.go @@ -3,8 +3,8 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zmagmacore/errors" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/mocks_test.go b/zmagmacore/magmasc/mocks_test.go index 5c0245fa2..b9939beb0 100644 --- a/zmagmacore/magmasc/mocks_test.go +++ b/zmagmacore/magmasc/mocks_test.go @@ -51,9 +51,9 @@ func mockDataUsage() DataUsage { func mockProvider() *Provider { now := time.Now().Format(time.RFC3339Nano) return &Provider{ - ID: "id:provider:" + now, - ExtID: "id:provider:external:" + now, - Host: "localhost:8020", + ID: "id:provider:" + now, + ExtID: "id:provider:external:" + now, + Host: "localhost:8020", MinStake: billion, } } diff --git a/zmagmacore/magmasc/provider.go b/zmagmacore/magmasc/provider.go index 20581af6d..16adc1066 100644 --- a/zmagmacore/magmasc/provider.go +++ b/zmagmacore/magmasc/provider.go @@ -3,10 +3,10 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zmagmacore/config" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/node" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/provider_terms.go b/zmagmacore/magmasc/provider_terms.go index 7896a46dc..edf647092 100644 --- a/zmagmacore/magmasc/provider_terms.go +++ b/zmagmacore/magmasc/provider_terms.go @@ -5,9 +5,9 @@ import ( magma "github.com/magma/augmented-networks/accounting/protos" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/time" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/tokenpool.go b/zmagmacore/magmasc/tokenpool.go index a0c695186..5f64ab0b6 100644 --- a/zmagmacore/magmasc/tokenpool.go +++ b/zmagmacore/magmasc/tokenpool.go @@ -3,7 +3,7 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/magmasc/tokenpool_transfer.go b/zmagmacore/magmasc/tokenpool_transfer.go index f2c419a8e..e75aeffe8 100644 --- a/zmagmacore/magmasc/tokenpool_transfer.go +++ b/zmagmacore/magmasc/tokenpool_transfer.go @@ -3,7 +3,7 @@ package magmasc import ( "encoding/json" - "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/registration/node.go b/zmagmacore/registration/node.go index b6f3a2184..3e239dc8a 100644 --- a/zmagmacore/registration/node.go +++ b/zmagmacore/registration/node.go @@ -8,12 +8,12 @@ import ( "go.uber.org/zap" - "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/http" "github.com/0chain/gosdk/zmagmacore/log" "github.com/0chain/gosdk/zmagmacore/magmasc" "github.com/0chain/gosdk/zmagmacore/transaction" + "github.com/0chain/gosdk_common/core/sys" ) // RegisterOrUpdateWithRetries registers bandwidth-marketplace Node in blockchain diff --git a/zmagmacore/transaction/txn.go b/zmagmacore/transaction/txn.go index 528d34320..9750c4b10 100644 --- a/zmagmacore/transaction/txn.go +++ b/zmagmacore/transaction/txn.go @@ -5,12 +5,12 @@ import ( "encoding/json" "fmt" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk/zmagmacore/chain" "github.com/0chain/gosdk/zmagmacore/errors" "github.com/0chain/gosdk/zmagmacore/node" ctime "github.com/0chain/gosdk/zmagmacore/time" + "github.com/0chain/gosdk_common/core/util" ) type ( diff --git a/zmagmacore/wallet/setup.go b/zmagmacore/wallet/setup.go index 24cbf845e..4cb105a2e 100644 --- a/zmagmacore/wallet/setup.go +++ b/zmagmacore/wallet/setup.go @@ -1,8 +1,8 @@ package wallet import ( - "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/logger" ) // SetupZCNSDK runs zcncore.SetLogFile, zcncore.SetLogLevel and zcncore.InitZCNSDK using provided Config. diff --git a/zmagmacore/wallet/wallet.go b/zmagmacore/wallet/wallet.go index 348902f71..55c501c28 100644 --- a/zmagmacore/wallet/wallet.go +++ b/zmagmacore/wallet/wallet.go @@ -4,8 +4,8 @@ import ( "encoding/hex" "encoding/json" - "github.com/0chain/gosdk/core/zcncrypto" "github.com/0chain/gosdk/zmagmacore/crypto" + "github.com/0chain/gosdk_common/core/zcncrypto" ) type ( diff --git a/znft/README.MD b/znft/README.MD index 78750d679..bd2f07db7 100644 --- a/znft/README.MD +++ b/znft/README.MD @@ -3,7 +3,7 @@ # znft ```go -import "github.com/0chain/gosdk/znft" +import "github.com/0chain/gosdk_common/znft" ``` ## Index diff --git a/znft/example/main.go b/znft/example/main.go index 1b0f1d890..182b2b5c8 100644 --- a/znft/example/main.go +++ b/znft/example/main.go @@ -11,7 +11,7 @@ import ( "math/big" "os" - "github.com/0chain/gosdk/znft" + "github.com/0chain/gosdk_common/znft" ) var mnemonic string diff --git a/znft/factoryerc721.go b/znft/factoryerc721.go index 5fe26fd02..d62d440ce 100644 --- a/znft/factoryerc721.go +++ b/znft/factoryerc721.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" - factory "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721/binding" + factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721/binding" ) // Solidity functions diff --git a/znft/factoryerc721fixed.go b/znft/factoryerc721fixed.go index 9ba0bac09..fe2d7832c 100644 --- a/znft/factoryerc721fixed.go +++ b/znft/factoryerc721fixed.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" - factory "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721fixed/binding" + factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721fixed/binding" ) // Solidity functions diff --git a/znft/factoryerc721pack.go b/znft/factoryerc721pack.go index 6965c0e67..304324526 100644 --- a/znft/factoryerc721pack.go +++ b/znft/factoryerc721pack.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" - factory "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721pack/binding" + factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721pack/binding" ) // Solidity functions diff --git a/znft/factoryerc721random.go b/znft/factoryerc721random.go index 7d1412290..c06f5abb4 100644 --- a/znft/factoryerc721random.go +++ b/znft/factoryerc721random.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" - factory "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721random/binding" + factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721random/binding" ) // Solidity functions diff --git a/znft/storageerc721.go b/znft/storageerc721.go index e43bccfc6..59ffd6f01 100644 --- a/znft/storageerc721.go +++ b/znft/storageerc721.go @@ -4,7 +4,7 @@ import ( "context" "math/big" - storageerc721 "github.com/0chain/gosdk/znft/contracts/dstorageerc721/binding" + storageerc721 "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721/binding" "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" diff --git a/znft/storageerc721fixed.go b/znft/storageerc721fixed.go index faae1fe58..80ce95a25 100644 --- a/znft/storageerc721fixed.go +++ b/znft/storageerc721fixed.go @@ -4,7 +4,7 @@ import ( "context" "math/big" - storageerc721fixed "github.com/0chain/gosdk/znft/contracts/dstorageerc721fixed/binding" + storageerc721fixed "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721fixed/binding" "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" diff --git a/znft/storageerc721pack.go b/znft/storageerc721pack.go index d1837258e..2d7b9b498 100644 --- a/znft/storageerc721pack.go +++ b/znft/storageerc721pack.go @@ -4,7 +4,7 @@ import ( "context" "math/big" - storageerc721pack "github.com/0chain/gosdk/znft/contracts/dstorageerc721pack/binding" + storageerc721pack "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721pack/binding" "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" diff --git a/znft/storageerc721random.go b/znft/storageerc721random.go index e64b6457c..71b295723 100644 --- a/znft/storageerc721random.go +++ b/znft/storageerc721random.go @@ -8,7 +8,7 @@ import ( "github.com/pkg/errors" - storageerc721random "github.com/0chain/gosdk/znft/contracts/dstorageerc721random/binding" + storageerc721random "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721random/binding" ) // Solidity Functions diff --git a/znft/znft.go b/znft/znft.go index f580ce7c6..62323a8aa 100644 --- a/znft/znft.go +++ b/znft/znft.go @@ -5,17 +5,17 @@ import ( "fmt" "os" - "github.com/0chain/gosdk/core/logger" + "github.com/0chain/gosdk_common/core/logger" - storageerc721 "github.com/0chain/gosdk/znft/contracts/dstorageerc721/binding" - storageerc721fixed "github.com/0chain/gosdk/znft/contracts/dstorageerc721fixed/binding" - storageerc721pack "github.com/0chain/gosdk/znft/contracts/dstorageerc721pack/binding" - storageerc721random "github.com/0chain/gosdk/znft/contracts/dstorageerc721random/binding" + storageerc721 "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721/binding" + storageerc721fixed "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721fixed/binding" + storageerc721pack "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721pack/binding" + storageerc721random "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721random/binding" - factoryerc721 "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721/binding" - factoryerc721fixed "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721fixed/binding" - factoryerc721pack "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721pack/binding" - factoryerc721random "github.com/0chain/gosdk/znft/contracts/factorymoduleerc721random/binding" + factoryerc721 "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721/binding" + factoryerc721fixed "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721fixed/binding" + factoryerc721pack "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721pack/binding" + factoryerc721random "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721random/binding" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" From dacfe336ae6f6a8424d86008b8449915744cbde0 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Wed, 8 Jan 2025 16:13:50 +0530 Subject: [PATCH 061/107] refactoring 2 --- wasmsdk/demo/main.go | 4 ++-- wasmsdk/ethwallet.go | 3 ++- zboxcore/sdk/transaction_mobile.go | 2 +- zcnbridge/authorizer/proofBurnTicket.go | 6 +++--- zcnbridge/bridge_helper.go | 2 +- zcnbridge/config.go | 4 ++-- zcnbridge/http/rest_test.go | 2 +- zcnbridge/log/logging.go | 2 +- zcnbridge/mocks/Transaction.go | 4 ++-- zcnbridge/mocks/TransactionCallbackAwaitable.go | 2 +- zcnbridge/mocks/TransactionProvider.go | 2 +- zcnbridge/transaction/functions.go | 2 +- zcnbridge/transaction/txn.go | 6 +++--- 13 files changed, 21 insertions(+), 20 deletions(-) diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 66c426e53..c8e988db4 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,15 +7,15 @@ import ( "net/http" "sync" + "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zcncore" "github.com/uptrace/bunrouter" ) func main() { zcncore.InitSignatureScheme("bls0chain") - + ctx, cf := context.WithCancel(context.Background()) router := bunrouter.New() diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index a04097962..ade2924f7 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -1,3 +1,4 @@ +//go:build js && wasm // +build js,wasm package main @@ -8,7 +9,7 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) // JS does not have int64 so we must take a string instead of int64. diff --git a/zboxcore/sdk/transaction_mobile.go b/zboxcore/sdk/transaction_mobile.go index cc426f19b..6993242f6 100644 --- a/zboxcore/sdk/transaction_mobile.go +++ b/zboxcore/sdk/transaction_mobile.go @@ -9,9 +9,9 @@ import ( "errors" + "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/transaction" l "github.com/0chain/gosdk_common/zboxcore/logger" - "github.com/0chain/gosdk_common/zcncore" ) type transactionCallback struct { diff --git a/zcnbridge/authorizer/proofBurnTicket.go b/zcnbridge/authorizer/proofBurnTicket.go index b05b1ac3c..10d05053a 100644 --- a/zcnbridge/authorizer/proofBurnTicket.go +++ b/zcnbridge/authorizer/proofBurnTicket.go @@ -4,14 +4,14 @@ import ( "encoding/json" "fmt" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/zcnbridge" + "github.com/0chain/gosdk/zcnbridge" + "github.com/0chain/gosdk/zcnbridge/errors" "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/zcnbridge/errors" ) type ProofOfBurn struct { diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go index fa35878cb..5af563264 100644 --- a/zcnbridge/bridge_helper.go +++ b/zcnbridge/bridge_helper.go @@ -5,8 +5,8 @@ import ( "math/big" "time" + "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zcncore" "github.com/pkg/errors" ) diff --git a/zcnbridge/config.go b/zcnbridge/config.go index f30fb1c20..09bae207a 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -8,8 +8,8 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/0chain/gosdk_common/zcnbridge/log" - "github.com/0chain/gosdk_common/zcnbridge/transaction" + "github.com/0chain/gosdk/zcnbridge/log" + "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" diff --git a/zcnbridge/http/rest_test.go b/zcnbridge/http/rest_test.go index 0b34363ed..feff0d7cf 100644 --- a/zcnbridge/http/rest_test.go +++ b/zcnbridge/http/rest_test.go @@ -3,7 +3,7 @@ package http import ( "testing" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" "github.com/stretchr/testify/require" ) diff --git a/zcnbridge/log/logging.go b/zcnbridge/log/logging.go index b0317797c..d3faac3df 100644 --- a/zcnbridge/log/logging.go +++ b/zcnbridge/log/logging.go @@ -7,7 +7,7 @@ import ( "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" - "github.com/0chain/gosdk_common/zcnbridge/errors" + "github.com/0chain/gosdk/zcnbridge/errors" ) var ( diff --git a/zcnbridge/mocks/Transaction.go b/zcnbridge/mocks/Transaction.go index f8b3b3576..ae323f12b 100644 --- a/zcnbridge/mocks/Transaction.go +++ b/zcnbridge/mocks/Transaction.go @@ -5,10 +5,10 @@ package mocks import ( context "context" - transaction "github.com/0chain/gosdk_common/zcnbridge/transaction" + transaction "github.com/0chain/gosdk/zcnbridge/transaction" mock "github.com/stretchr/testify/mock" - zcncore "github.com/0chain/gosdk_common/zcncore" + zcncore "github.com/0chain/gosdk/zcncore" ) // Transaction is an autogenerated mock type for the Transaction type diff --git a/zcnbridge/mocks/TransactionCallbackAwaitable.go b/zcnbridge/mocks/TransactionCallbackAwaitable.go index e0d78c05c..9966f8fba 100644 --- a/zcnbridge/mocks/TransactionCallbackAwaitable.go +++ b/zcnbridge/mocks/TransactionCallbackAwaitable.go @@ -7,7 +7,7 @@ import ( mock "github.com/stretchr/testify/mock" - zcncore "github.com/0chain/gosdk_common/zcncore" + zcncore "github.com/0chain/gosdk/zcncore" ) // TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type diff --git a/zcnbridge/mocks/TransactionProvider.go b/zcnbridge/mocks/TransactionProvider.go index bfb7864d3..2ca8c875b 100644 --- a/zcnbridge/mocks/TransactionProvider.go +++ b/zcnbridge/mocks/TransactionProvider.go @@ -3,7 +3,7 @@ package mocks import ( - transaction "github.com/0chain/gosdk_common/zcnbridge/transaction" + transaction "github.com/0chain/gosdk/zcnbridge/transaction" mock "github.com/stretchr/testify/mock" ) diff --git a/zcnbridge/transaction/functions.go b/zcnbridge/transaction/functions.go index 5022232cd..07d803e36 100644 --- a/zcnbridge/transaction/functions.go +++ b/zcnbridge/transaction/functions.go @@ -5,7 +5,7 @@ package transaction import ( "context" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) // AddAuthorizer adds authorizer to the bridge diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go index 629b8bfab..ab0a1c654 100644 --- a/zcnbridge/transaction/txn.go +++ b/zcnbridge/transaction/txn.go @@ -7,10 +7,10 @@ import ( "strconv" "strings" + "github.com/0chain/gosdk/zcnbridge/errors" + ctime "github.com/0chain/gosdk/zcnbridge/time" + "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zcnbridge/errors" - ctime "github.com/0chain/gosdk_common/zcnbridge/time" - "github.com/0chain/gosdk_common/zcncore" ) var ( From f7ec7e6727c67fbf50cb85827a58ef4cb1dcb845 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 9 Jan 2025 00:09:39 +0530 Subject: [PATCH 062/107] fix --- core/conf/vars.go | 22 +++++++++++----------- wasmsdk/wallet.go | 3 +++ 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/core/conf/vars.go b/core/conf/vars.go index 5b96b690f..211c23c05 100644 --- a/core/conf/vars.go +++ b/core/conf/vars.go @@ -38,17 +38,17 @@ func GetClientConfig() (*Config, error) { return cfg, nil } - // InitClientConfig set global client SDK config - func InitClientConfig(c *Config) { - onceCfg.Do(func() { - sharderConsensous := c.SharderConsensous - if sharderConsensous < 1 { - sharderConsensous = DefaultSharderConsensous - } - cfg = c - cfg.SharderConsensous = sharderConsensous - }) - } +// InitClientConfig set global client SDK config +func InitClientConfig(c *Config) { + onceCfg.Do(func() { + sharderConsensous := c.SharderConsensous + if sharderConsensous < 1 { + sharderConsensous = DefaultSharderConsensous + } + cfg = c + cfg.SharderConsensous = sharderConsensous + }) +} // InitChainNetwork set global chain network for the SDK given its configuration func InitChainNetwork(n *Network) { diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index 2804b8b80..8b088e9e4 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -12,6 +12,7 @@ import ( "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zcncore" + coreClient "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/client" ) @@ -45,6 +46,8 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon Keys: keys, IsSplit: isSplit, } + coreClient.SetWallet(*w) + fmt.Println("set Wallet, is split:", isSplit) err := zcncore.SetWallet(*w, isSplit) if err != nil { From 295d20da26508813277f09124eb1985df7307e4d Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 9 Jan 2025 00:48:35 +0530 Subject: [PATCH 063/107] fix 2 --- zboxcore/sdk/allocation_file_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index 16fe464eb..c5934a3c3 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -17,8 +17,8 @@ import ( "github.com/0chain/gosdk_common/core/pathutil" "github.com/hitenjain14/fasthttp" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" From e07625b8d46ccaed0bc1d3024c5fdd626f2e1525 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 16 Jan 2025 18:17:28 +0530 Subject: [PATCH 064/107] refactor --- .github/workflows/build-sdks.yml | 24 +- README.md | 2 +- constants/context_key.go | 27 - constants/errors.go | 37 - constants/files.go | 24 - core/block/block.go | 94 - core/block/magic_block_entity.go | 71 - core/build.go | 2 - core/common/math.go | 33 - core/common/math_test.go | 77 - core/common/misc.go | 259 --- core/common/misc_test.go | 135 -- core/common/time.go | 80 - core/common/time_test.go | 77 - core/common/utils.go | 26 - core/conf/config.go | 187 -- core/conf/config_test.go | 195 -- core/conf/mocks/Reader.go | 54 - core/conf/mocks/doc.go | 2 - core/conf/network.go | 58 - core/conf/reader.go | 99 - core/conf/reader_test.go | 67 - core/conf/vars.go | 82 - core/encryption/hash.go | 86 - core/imageutil/thumbnailer.go | 75 - core/logger/logger.go | 121 -- core/node/cache.go | 53 - core/node/node.go | 443 ----- core/node/node_test.go | 56 - core/pathutil/path.go | 64 - core/pathutil/path_test.go | 73 - core/resty/client.go | 21 - core/resty/client_wasm.go | 34 - core/resty/doc.go | 2 - core/resty/mocks/Client.go | 37 - core/resty/mocks/doc.go | 2 - core/resty/mocks/timeout.go | 21 - core/resty/option.go | 48 - core/resty/resty.go | 305 --- core/resty/resty_test.go | 165 -- core/resty/result.go | 11 - core/resty/transport.go | 29 - core/resty/transport_wasm.go | 27 - core/resty/vars.go | 14 - core/sys/doc.go | 2 - core/sys/fs.go | 63 - core/sys/fs_disk.go | 90 - core/sys/fs_mem.go | 217 --- core/sys/sign.go | 16 - core/sys/util.go | 272 --- core/sys/vars.go | 38 - core/tokenrate/bancor.go | 143 -- core/tokenrate/bancor_test.go | 44 - core/tokenrate/coingecko.go | 83 - core/tokenrate/coinmarketcap.go | 186 -- core/tokenrate/doc.go | 2 - core/tokenrate/mockresponses/bancor.json | 25 - core/tokenrate/mockresponses/coingecko.json | 21 - .../mockresponses/coinmarketcap.json | 87 - core/tokenrate/tokenrate.go | 54 - core/tokenrate/tokenrate_test.go | 242 --- core/tokenrate/uniswap.go | 100 - core/transaction/entity.go | 464 ----- core/transaction/entity_test.go | 28 - core/transaction/transaction.go | 24 - core/transaction/transaction_mobile.go | 82 - core/transaction/transport.go | 20 - core/transaction/transport_wasm.go | 15 - core/transaction/type.go | 15 - core/transaction/utils.go | 435 ----- core/transaction/vars.go | 19 - core/util/doc.go | 2 - core/util/fixed_merkle_tree.go | 271 --- core/util/fixed_merkle_tree_test.go | 71 - core/util/http_consensus_maps.go | 93 - core/util/httpnet.go | 178 -- core/util/merkle_tree.go | 148 -- core/util/merkle_tree_interface.go | 83 - core/util/rand.go | 115 -- core/util/rand_test.go | 59 - core/util/secure_value.go | 72 - core/util/transport.go | 27 - core/util/transport_wasm.go | 20 - core/util/uint64.go | 19 - core/util/uuid.go | 24 - core/util/validation_tree.go | 342 ---- core/util/validation_tree_test.go | 331 ---- core/version/.emptydir | 0 core/version/doc.go | 3 - core/version/version.go | 5 - core/zcncrypto/bls.go | 66 - core/zcncrypto/bls0chain_herumi.go | 310 --- core/zcncrypto/bls0chain_herumi_test.go | 189 -- core/zcncrypto/bls0chain_test.go | 65 - core/zcncrypto/bls0chain_wasm.go | 109 -- core/zcncrypto/bls_herumi.go | 210 -- core/zcncrypto/ed255190chain.go | 179 -- core/zcncrypto/ed25519_test.go | 86 - core/zcncrypto/factory.go | 114 -- core/zcncrypto/factory_wasm.go | 65 - core/zcncrypto/signature_scheme.go | 112 -- dev/blobber/handlers.go | 98 - dev/blobber/init.go | 29 - dev/blobber/model/commit_result.go | 10 - dev/blobber/model/ref.go | 179 -- dev/blobber/model/reference_path.go | 7 - dev/blobber/model/reference_path_result.go | 35 - dev/blobber/model/upload_form_data.go | 38 - dev/blobber/model/upload_result.go | 8 - dev/blobber/model/write_marker.go | 22 - dev/blobber/ref.go | 23 - dev/mock/response.go | 34 - dev/server.go | 36 - go.mod | 2 +- go.sum | 2 + mobilesdk/sdk/sdk.go | 58 +- mobilesdk/sdk/sign.go | 2 +- mobilesdk/zbox/m3u8.go | 26 +- mobilesdk/zbox/util.go | 93 - mobilesdk/zboxapi/client.go | 13 +- mobilesdk/zcn/readpool.go | 27 - mobilesdk/zcn/smartcontract.go | 96 - mobilesdk/zcn/transaction_query.go | 2 +- mobilesdk/zcn/writepool.go | 19 +- sdks/blobber/blobber.go | 23 - sdks/blobber/doc.go | 2 - sdks/blobber/endpoints.go | 12 - sdks/client.go | 51 - sdks/doc.go | 2 - sdks/request.go | 21 - sdks/zbox.go | 146 -- wasmsdk/allocation.go | 28 +- wasmsdk/auth_txn.go | 4 +- wasmsdk/bridge.go | 70 +- wasmsdk/cache.go | 4 +- wasmsdk/common.go | 2 +- wasmsdk/demo/main.go | 11 +- wasmsdk/ethwallet.go | 4 +- wasmsdk/jsbridge/async.go | 148 -- wasmsdk/jsbridge/bytes.go | 40 - wasmsdk/jsbridge/doc.go | 3 - wasmsdk/jsbridge/error.go | 23 - wasmsdk/jsbridge/file_reader.go | 124 -- wasmsdk/jsbridge/file_writer.go | 241 --- wasmsdk/jsbridge/func.go | 171 -- wasmsdk/jsbridge/func_test.go | 88 - wasmsdk/jsbridge/input.go | 285 --- wasmsdk/jsbridge/input_test.go | 105 - wasmsdk/jsbridge/object.go | 74 - wasmsdk/jsbridge/output.go | 100 - wasmsdk/jsbridge/self.go | 24 - wasmsdk/jsbridge/sync.go | 103 - wasmsdk/jsbridge/template_data.go | 92 - wasmsdk/jsbridge/timer.go | 50 - wasmsdk/jsbridge/vars.go | 26 - wasmsdk/jsbridge/webworker.go | 320 --- wasmsdk/jsbridge/zcnworker.js.tpl | 101 - wasmsdk/player_stream.go | 2 +- wasmsdk/proxy.go | 24 +- wasmsdk/sdk.go | 29 +- wasmsdk/smartcontract.go | 27 - wasmsdk/tokenrate.go | 2 +- wasmsdk/updateImage.go | 3 +- wasmsdk/wallet.go | 20 +- wasmsdk/wallet_base.go | 4 +- wasmsdk/zcn.go | 22 +- winsdk/allocation.go | 2 +- winsdk/sdk.go | 42 +- winsdk/wallet.go | 5 +- winsdk/zboxapi.go | 9 +- zboxapi/doc.go | 2 - zboxapi/response.go | 106 - zboxapi/sdk.go | 374 ---- zboxapi/sdk_test.go | 31 - zboxcore/sdk/chunked_upload_process_js.go | 2 +- zboxcore/sdk/transaction.go | 2 +- zboxcore/sdk/transaction_mobile.go | 2 +- zcnbridge/README.MD | 970 ---------- zcnbridge/authorizer/doc.go | 3 - zcnbridge/authorizer/proofBurnTicket.go | 83 - zcnbridge/authorizer/proofBurnTicket_test.go | 70 - zcnbridge/authorizer_response.go | 124 -- zcnbridge/authorizers_query.go | 351 ---- zcnbridge/bridge.go | 1189 ------------ zcnbridge/bridge_helper.go | 105 - zcnbridge/bridge_test.go | 657 ------- zcnbridge/config.go | 174 -- zcnbridge/crypto/hash.go | 46 - zcnbridge/doc.go | 4 - zcnbridge/errors/errors.go | 109 -- zcnbridge/errors/errors_test.go | 243 --- zcnbridge/ethereum/authorizers/authorizers.go | 639 ------ zcnbridge/ethereum/bridge/bridge.go | 1032 ---------- zcnbridge/ethereum/doc.go | 3 - zcnbridge/ethereum/mint_payload.go | 29 - zcnbridge/ethereum/nftconfig/nftconfig.go | 656 ------- .../ethereum/uniswapnetwork/uniswapnetwork.go | 536 ----- .../ethereum/uniswaprouter/uniswaprouter.go | 777 -------- zcnbridge/ethereum/zcntoken/zcntoken.go | 1336 ------------- zcnbridge/http/client.go | 42 - zcnbridge/http/doc.go | 2 - zcnbridge/http/rest.go | 186 -- zcnbridge/http/rest_test.go | 26 - zcnbridge/keystore.go | 202 -- zcnbridge/log/doc.go | 2 - zcnbridge/log/handler.go | 57 - zcnbridge/log/logging.go | 93 - zcnbridge/mocks/EthereumClient.go | 332 ---- zcnbridge/mocks/JobResult.go | 74 - zcnbridge/mocks/KeyStore.go | 112 -- zcnbridge/mocks/Transaction.go | 135 -- .../mocks/TransactionCallbackAwaitable.go | 74 - zcnbridge/mocks/TransactionProvider.go | 54 - zcnbridge/mocks/doc.go | 2 - zcnbridge/rest.go | 119 -- zcnbridge/time/doc.go | 2 - zcnbridge/time/time.go | 34 - zcnbridge/transaction/callback.go | 89 - zcnbridge/transaction/const.go | 62 - zcnbridge/transaction/doc.go | 2 - zcnbridge/transaction/functions.go | 63 - zcnbridge/transaction/mocks/Transaction.go | 135 -- .../mocks/TransactionCallbackAwaitable.go | 74 - .../transaction/mocks/TransactionProvider.go | 54 - zcnbridge/transaction/mocks/doc.go | 2 - zcnbridge/transaction/txn.go | 210 -- zcnbridge/utils/convert.go | 18 - zcnbridge/wallet/doc.go | 2 - zcnbridge/wallet/status.go | 189 -- zcnbridge/wallet/wallet.go | 33 - zcnbridge/wallets/README.md | 1 - ...--d8c9156e782c68ee671c09b6b92de76c97948432 | 1 - zcnbridge/zcnsc/burn_event.go | 6 - zcnbridge/zcnsc/burn_payload.go | 18 - zcnbridge/zcnsc/burn_ticket.go | 7 - zcnbridge/zcnsc/doc.go | 2 - zcnbridge/zcnsc/mint_payload.go | 26 - zcncore/doc.go | 2 - zcncore/ethhdwallet/hdwallet.go | 558 ------ zcncore/ethhdwallet/hdwallet_test.go | 344 ---- zcncore/ethwallet.go | 10 - zcncore/ethwallet_base.go | 315 --- zcncore/ethwallet_base_test.go | 294 --- zcncore/mocks/AuthCallback.go | 30 - zcncore/mocks/FeeOption.go | 33 - zcncore/mocks/GetBalanceCallback.go | 30 - zcncore/mocks/GetInfoCallback.go | 30 - zcncore/mocks/GetNonceCallback.go | 30 - zcncore/mocks/MSVoteCallback.go | 30 - zcncore/mocks/QueryResultHandle.go | 42 - zcncore/mocks/TransactionCallback.go | 43 - zcncore/mocks/TransactionCommon.go | 595 ------ zcncore/mocks/TransactionScheme.go | 835 -------- zcncore/mocks/WalletCallback.go | 30 - zcncore/mocks/doc.go | 2 - zcncore/mswallet.go | 207 -- zcncore/mswallet_base.go | 132 -- zcncore/mswallet_mobile.go | 282 --- zcncore/networkworker.go | 157 -- zcncore/networkworker_mobile.go | 172 -- zcncore/sample/0Wallet.go | 257 --- zcncore/sample/snapshot_test.go | 118 -- zcncore/transaction.go | 1719 ----------------- zcncore/transaction_base.go | 786 -------- zcncore/transaction_mobile.go | 1686 ---------------- zcncore/transaction_query.go | 599 ------ zcncore/transaction_query_base.go | 81 - zcncore/transaction_query_mobile.go | 491 ----- zcncore/transaction_query_test.go | 250 --- zcncore/transactionauth.go | 663 ------- zcncore/transactionauth_base.go | 206 -- zcncore/transactionauth_mobile.go | 522 ----- zcncore/wallet.go | 29 - zcncore/wallet_base.go | 1449 -------------- zcncore/wallet_base_test.go | 37 - zcncore/wallet_callback.go | 28 - zcncore/wallet_mobile.go | 38 - zcncore/zauth.go | 598 ------ zmagmacore/build/info.go | 7 - zmagmacore/chain/entity.go | 45 - zmagmacore/config/chain.go | 12 - zmagmacore/config/consumer.go | 29 - zmagmacore/config/handler.go | 14 - zmagmacore/config/provider.go | 30 - zmagmacore/config/workers.go | 9 - zmagmacore/crypto/hash.go | 46 - zmagmacore/crypto/keys.go | 64 - zmagmacore/doc.go | 2 - zmagmacore/errors/errors.go | 91 - zmagmacore/errors/errors_test.go | 243 --- zmagmacore/http/client.go | 45 - zmagmacore/http/sc-api.go | 102 - zmagmacore/http/server.go | 81 - zmagmacore/limiter/limiter.go | 49 - zmagmacore/log/handler.go | 58 - zmagmacore/log/logging.go | 93 - zmagmacore/magmasc/acknowledgment.go | 123 -- zmagmacore/magmasc/acknowledgment_test.go | 173 -- zmagmacore/magmasc/actions.go | 284 --- zmagmacore/magmasc/api.go | 180 -- zmagmacore/magmasc/billing.go | 79 - zmagmacore/magmasc/billing_test.go | 221 --- zmagmacore/magmasc/const.go | 111 -- zmagmacore/magmasc/consumer.go | 75 - zmagmacore/magmasc/consumer_test.go | 146 -- zmagmacore/magmasc/datausage.go | 60 - zmagmacore/magmasc/datausage_test.go | 134 -- zmagmacore/magmasc/errors.go | 36 - zmagmacore/magmasc/interfaces.go | 51 - zmagmacore/magmasc/mocks_test.go | 115 -- zmagmacore/magmasc/provider.go | 81 - zmagmacore/magmasc/provider_terms.go | 200 -- zmagmacore/magmasc/provider_test.go | 154 -- zmagmacore/magmasc/tokenpool.go | 47 - zmagmacore/magmasc/tokenpool_configurator.go | 21 - zmagmacore/magmasc/tokenpool_test.go | 86 - zmagmacore/magmasc/tokenpool_transfer.go | 35 - zmagmacore/magmasc/tokenpool_transfer_test.go | 86 - zmagmacore/node/self.go | 80 - zmagmacore/registration/node.go | 119 -- zmagmacore/registration/types.go | 38 - zmagmacore/shutdown/shutdown.go | 55 - zmagmacore/storage/interface.go | 126 -- zmagmacore/time/time.go | 35 - zmagmacore/transaction/callback.go | 96 - zmagmacore/transaction/const.go | 62 - zmagmacore/transaction/http.go | 22 - zmagmacore/transaction/txn.go | 140 -- zmagmacore/wallet/balance.go | 52 - zmagmacore/wallet/callback.go | 18 - zmagmacore/wallet/setup.go | 37 - zmagmacore/wallet/types.go | 18 - zmagmacore/wallet/wallet.go | 63 - znft/keystore.go | 2 +- 334 files changed, 192 insertions(+), 43348 deletions(-) delete mode 100644 constants/context_key.go delete mode 100644 constants/errors.go delete mode 100644 constants/files.go delete mode 100644 core/block/block.go delete mode 100644 core/block/magic_block_entity.go delete mode 100644 core/build.go delete mode 100644 core/common/math.go delete mode 100644 core/common/math_test.go delete mode 100644 core/common/misc.go delete mode 100644 core/common/misc_test.go delete mode 100644 core/common/time.go delete mode 100644 core/common/time_test.go delete mode 100644 core/common/utils.go delete mode 100644 core/conf/config.go delete mode 100644 core/conf/config_test.go delete mode 100644 core/conf/mocks/Reader.go delete mode 100644 core/conf/mocks/doc.go delete mode 100644 core/conf/network.go delete mode 100644 core/conf/reader.go delete mode 100644 core/conf/reader_test.go delete mode 100644 core/conf/vars.go delete mode 100644 core/encryption/hash.go delete mode 100644 core/imageutil/thumbnailer.go delete mode 100644 core/logger/logger.go delete mode 100644 core/node/cache.go delete mode 100644 core/node/node.go delete mode 100644 core/node/node_test.go delete mode 100644 core/pathutil/path.go delete mode 100644 core/pathutil/path_test.go delete mode 100644 core/resty/client.go delete mode 100644 core/resty/client_wasm.go delete mode 100644 core/resty/doc.go delete mode 100644 core/resty/mocks/Client.go delete mode 100644 core/resty/mocks/doc.go delete mode 100644 core/resty/mocks/timeout.go delete mode 100644 core/resty/option.go delete mode 100644 core/resty/resty.go delete mode 100644 core/resty/resty_test.go delete mode 100644 core/resty/result.go delete mode 100644 core/resty/transport.go delete mode 100644 core/resty/transport_wasm.go delete mode 100644 core/resty/vars.go delete mode 100644 core/sys/doc.go delete mode 100644 core/sys/fs.go delete mode 100644 core/sys/fs_disk.go delete mode 100644 core/sys/fs_mem.go delete mode 100644 core/sys/sign.go delete mode 100644 core/sys/util.go delete mode 100644 core/sys/vars.go delete mode 100644 core/tokenrate/bancor.go delete mode 100644 core/tokenrate/bancor_test.go delete mode 100644 core/tokenrate/coingecko.go delete mode 100644 core/tokenrate/coinmarketcap.go delete mode 100644 core/tokenrate/doc.go delete mode 100644 core/tokenrate/mockresponses/bancor.json delete mode 100644 core/tokenrate/mockresponses/coingecko.json delete mode 100644 core/tokenrate/mockresponses/coinmarketcap.json delete mode 100644 core/tokenrate/tokenrate.go delete mode 100644 core/tokenrate/tokenrate_test.go delete mode 100644 core/tokenrate/uniswap.go delete mode 100644 core/transaction/entity.go delete mode 100644 core/transaction/entity_test.go delete mode 100644 core/transaction/transaction.go delete mode 100644 core/transaction/transaction_mobile.go delete mode 100644 core/transaction/transport.go delete mode 100644 core/transaction/transport_wasm.go delete mode 100644 core/transaction/type.go delete mode 100644 core/transaction/utils.go delete mode 100644 core/transaction/vars.go delete mode 100644 core/util/doc.go delete mode 100644 core/util/fixed_merkle_tree.go delete mode 100644 core/util/fixed_merkle_tree_test.go delete mode 100644 core/util/http_consensus_maps.go delete mode 100644 core/util/httpnet.go delete mode 100644 core/util/merkle_tree.go delete mode 100644 core/util/merkle_tree_interface.go delete mode 100644 core/util/rand.go delete mode 100644 core/util/rand_test.go delete mode 100644 core/util/secure_value.go delete mode 100644 core/util/transport.go delete mode 100644 core/util/transport_wasm.go delete mode 100644 core/util/uint64.go delete mode 100644 core/util/uuid.go delete mode 100644 core/util/validation_tree.go delete mode 100644 core/util/validation_tree_test.go delete mode 100644 core/version/.emptydir delete mode 100644 core/version/doc.go delete mode 100644 core/version/version.go delete mode 100644 core/zcncrypto/bls.go delete mode 100644 core/zcncrypto/bls0chain_herumi.go delete mode 100644 core/zcncrypto/bls0chain_herumi_test.go delete mode 100644 core/zcncrypto/bls0chain_test.go delete mode 100644 core/zcncrypto/bls0chain_wasm.go delete mode 100644 core/zcncrypto/bls_herumi.go delete mode 100644 core/zcncrypto/ed255190chain.go delete mode 100644 core/zcncrypto/ed25519_test.go delete mode 100644 core/zcncrypto/factory.go delete mode 100644 core/zcncrypto/factory_wasm.go delete mode 100644 core/zcncrypto/signature_scheme.go delete mode 100644 dev/blobber/handlers.go delete mode 100644 dev/blobber/init.go delete mode 100644 dev/blobber/model/commit_result.go delete mode 100644 dev/blobber/model/ref.go delete mode 100644 dev/blobber/model/reference_path.go delete mode 100644 dev/blobber/model/reference_path_result.go delete mode 100644 dev/blobber/model/upload_form_data.go delete mode 100644 dev/blobber/model/upload_result.go delete mode 100644 dev/blobber/model/write_marker.go delete mode 100644 dev/blobber/ref.go delete mode 100644 dev/mock/response.go delete mode 100644 dev/server.go delete mode 100644 mobilesdk/zcn/readpool.go delete mode 100644 mobilesdk/zcn/smartcontract.go delete mode 100644 sdks/blobber/blobber.go delete mode 100644 sdks/blobber/doc.go delete mode 100644 sdks/blobber/endpoints.go delete mode 100644 sdks/client.go delete mode 100644 sdks/doc.go delete mode 100644 sdks/request.go delete mode 100644 sdks/zbox.go delete mode 100644 wasmsdk/jsbridge/async.go delete mode 100644 wasmsdk/jsbridge/bytes.go delete mode 100644 wasmsdk/jsbridge/doc.go delete mode 100644 wasmsdk/jsbridge/error.go delete mode 100644 wasmsdk/jsbridge/file_reader.go delete mode 100644 wasmsdk/jsbridge/file_writer.go delete mode 100644 wasmsdk/jsbridge/func.go delete mode 100644 wasmsdk/jsbridge/func_test.go delete mode 100644 wasmsdk/jsbridge/input.go delete mode 100644 wasmsdk/jsbridge/input_test.go delete mode 100644 wasmsdk/jsbridge/object.go delete mode 100644 wasmsdk/jsbridge/output.go delete mode 100644 wasmsdk/jsbridge/self.go delete mode 100644 wasmsdk/jsbridge/sync.go delete mode 100644 wasmsdk/jsbridge/template_data.go delete mode 100644 wasmsdk/jsbridge/timer.go delete mode 100644 wasmsdk/jsbridge/vars.go delete mode 100644 wasmsdk/jsbridge/webworker.go delete mode 100644 wasmsdk/jsbridge/zcnworker.js.tpl delete mode 100644 wasmsdk/smartcontract.go delete mode 100644 zboxapi/doc.go delete mode 100644 zboxapi/response.go delete mode 100644 zboxapi/sdk.go delete mode 100644 zboxapi/sdk_test.go delete mode 100644 zcnbridge/README.MD delete mode 100644 zcnbridge/authorizer/doc.go delete mode 100644 zcnbridge/authorizer/proofBurnTicket.go delete mode 100644 zcnbridge/authorizer/proofBurnTicket_test.go delete mode 100644 zcnbridge/authorizer_response.go delete mode 100644 zcnbridge/authorizers_query.go delete mode 100644 zcnbridge/bridge.go delete mode 100644 zcnbridge/bridge_helper.go delete mode 100644 zcnbridge/bridge_test.go delete mode 100644 zcnbridge/config.go delete mode 100644 zcnbridge/crypto/hash.go delete mode 100644 zcnbridge/doc.go delete mode 100644 zcnbridge/errors/errors.go delete mode 100644 zcnbridge/errors/errors_test.go delete mode 100644 zcnbridge/ethereum/authorizers/authorizers.go delete mode 100644 zcnbridge/ethereum/bridge/bridge.go delete mode 100644 zcnbridge/ethereum/doc.go delete mode 100644 zcnbridge/ethereum/mint_payload.go delete mode 100644 zcnbridge/ethereum/nftconfig/nftconfig.go delete mode 100644 zcnbridge/ethereum/uniswapnetwork/uniswapnetwork.go delete mode 100644 zcnbridge/ethereum/uniswaprouter/uniswaprouter.go delete mode 100644 zcnbridge/ethereum/zcntoken/zcntoken.go delete mode 100644 zcnbridge/http/client.go delete mode 100644 zcnbridge/http/doc.go delete mode 100644 zcnbridge/http/rest.go delete mode 100644 zcnbridge/http/rest_test.go delete mode 100644 zcnbridge/keystore.go delete mode 100644 zcnbridge/log/doc.go delete mode 100644 zcnbridge/log/handler.go delete mode 100644 zcnbridge/log/logging.go delete mode 100644 zcnbridge/mocks/EthereumClient.go delete mode 100644 zcnbridge/mocks/JobResult.go delete mode 100644 zcnbridge/mocks/KeyStore.go delete mode 100644 zcnbridge/mocks/Transaction.go delete mode 100644 zcnbridge/mocks/TransactionCallbackAwaitable.go delete mode 100644 zcnbridge/mocks/TransactionProvider.go delete mode 100644 zcnbridge/mocks/doc.go delete mode 100644 zcnbridge/rest.go delete mode 100644 zcnbridge/time/doc.go delete mode 100644 zcnbridge/time/time.go delete mode 100644 zcnbridge/transaction/callback.go delete mode 100644 zcnbridge/transaction/const.go delete mode 100644 zcnbridge/transaction/doc.go delete mode 100644 zcnbridge/transaction/functions.go delete mode 100644 zcnbridge/transaction/mocks/Transaction.go delete mode 100644 zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go delete mode 100644 zcnbridge/transaction/mocks/TransactionProvider.go delete mode 100644 zcnbridge/transaction/mocks/doc.go delete mode 100644 zcnbridge/transaction/txn.go delete mode 100644 zcnbridge/utils/convert.go delete mode 100644 zcnbridge/wallet/doc.go delete mode 100644 zcnbridge/wallet/status.go delete mode 100644 zcnbridge/wallet/wallet.go delete mode 100644 zcnbridge/wallets/README.md delete mode 100644 zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 delete mode 100644 zcnbridge/zcnsc/burn_event.go delete mode 100644 zcnbridge/zcnsc/burn_payload.go delete mode 100644 zcnbridge/zcnsc/burn_ticket.go delete mode 100644 zcnbridge/zcnsc/doc.go delete mode 100644 zcnbridge/zcnsc/mint_payload.go delete mode 100644 zcncore/doc.go delete mode 100644 zcncore/ethhdwallet/hdwallet.go delete mode 100644 zcncore/ethhdwallet/hdwallet_test.go delete mode 100644 zcncore/ethwallet.go delete mode 100644 zcncore/ethwallet_base.go delete mode 100644 zcncore/ethwallet_base_test.go delete mode 100644 zcncore/mocks/AuthCallback.go delete mode 100644 zcncore/mocks/FeeOption.go delete mode 100644 zcncore/mocks/GetBalanceCallback.go delete mode 100644 zcncore/mocks/GetInfoCallback.go delete mode 100644 zcncore/mocks/GetNonceCallback.go delete mode 100644 zcncore/mocks/MSVoteCallback.go delete mode 100644 zcncore/mocks/QueryResultHandle.go delete mode 100644 zcncore/mocks/TransactionCallback.go delete mode 100644 zcncore/mocks/TransactionCommon.go delete mode 100644 zcncore/mocks/TransactionScheme.go delete mode 100644 zcncore/mocks/WalletCallback.go delete mode 100644 zcncore/mocks/doc.go delete mode 100644 zcncore/mswallet.go delete mode 100644 zcncore/mswallet_base.go delete mode 100644 zcncore/mswallet_mobile.go delete mode 100644 zcncore/networkworker.go delete mode 100644 zcncore/networkworker_mobile.go delete mode 100644 zcncore/sample/0Wallet.go delete mode 100644 zcncore/sample/snapshot_test.go delete mode 100644 zcncore/transaction.go delete mode 100644 zcncore/transaction_base.go delete mode 100644 zcncore/transaction_mobile.go delete mode 100644 zcncore/transaction_query.go delete mode 100644 zcncore/transaction_query_base.go delete mode 100644 zcncore/transaction_query_mobile.go delete mode 100644 zcncore/transaction_query_test.go delete mode 100644 zcncore/transactionauth.go delete mode 100644 zcncore/transactionauth_base.go delete mode 100644 zcncore/transactionauth_mobile.go delete mode 100644 zcncore/wallet.go delete mode 100644 zcncore/wallet_base.go delete mode 100644 zcncore/wallet_base_test.go delete mode 100644 zcncore/wallet_callback.go delete mode 100644 zcncore/wallet_mobile.go delete mode 100644 zcncore/zauth.go delete mode 100644 zmagmacore/build/info.go delete mode 100644 zmagmacore/chain/entity.go delete mode 100644 zmagmacore/config/chain.go delete mode 100644 zmagmacore/config/consumer.go delete mode 100644 zmagmacore/config/handler.go delete mode 100644 zmagmacore/config/provider.go delete mode 100644 zmagmacore/config/workers.go delete mode 100644 zmagmacore/crypto/hash.go delete mode 100644 zmagmacore/crypto/keys.go delete mode 100644 zmagmacore/doc.go delete mode 100644 zmagmacore/errors/errors.go delete mode 100644 zmagmacore/errors/errors_test.go delete mode 100644 zmagmacore/http/client.go delete mode 100644 zmagmacore/http/sc-api.go delete mode 100644 zmagmacore/http/server.go delete mode 100644 zmagmacore/limiter/limiter.go delete mode 100644 zmagmacore/log/handler.go delete mode 100644 zmagmacore/log/logging.go delete mode 100644 zmagmacore/magmasc/acknowledgment.go delete mode 100644 zmagmacore/magmasc/acknowledgment_test.go delete mode 100644 zmagmacore/magmasc/actions.go delete mode 100644 zmagmacore/magmasc/api.go delete mode 100644 zmagmacore/magmasc/billing.go delete mode 100644 zmagmacore/magmasc/billing_test.go delete mode 100644 zmagmacore/magmasc/const.go delete mode 100644 zmagmacore/magmasc/consumer.go delete mode 100644 zmagmacore/magmasc/consumer_test.go delete mode 100644 zmagmacore/magmasc/datausage.go delete mode 100644 zmagmacore/magmasc/datausage_test.go delete mode 100644 zmagmacore/magmasc/errors.go delete mode 100644 zmagmacore/magmasc/interfaces.go delete mode 100644 zmagmacore/magmasc/mocks_test.go delete mode 100644 zmagmacore/magmasc/provider.go delete mode 100644 zmagmacore/magmasc/provider_terms.go delete mode 100644 zmagmacore/magmasc/provider_test.go delete mode 100644 zmagmacore/magmasc/tokenpool.go delete mode 100644 zmagmacore/magmasc/tokenpool_configurator.go delete mode 100644 zmagmacore/magmasc/tokenpool_test.go delete mode 100644 zmagmacore/magmasc/tokenpool_transfer.go delete mode 100644 zmagmacore/magmasc/tokenpool_transfer_test.go delete mode 100644 zmagmacore/node/self.go delete mode 100644 zmagmacore/registration/node.go delete mode 100644 zmagmacore/registration/types.go delete mode 100644 zmagmacore/shutdown/shutdown.go delete mode 100644 zmagmacore/storage/interface.go delete mode 100644 zmagmacore/time/time.go delete mode 100644 zmagmacore/transaction/callback.go delete mode 100644 zmagmacore/transaction/const.go delete mode 100644 zmagmacore/transaction/http.go delete mode 100644 zmagmacore/transaction/txn.go delete mode 100644 zmagmacore/wallet/balance.go delete mode 100644 zmagmacore/wallet/callback.go delete mode 100644 zmagmacore/wallet/setup.go delete mode 100644 zmagmacore/wallet/types.go delete mode 100644 zmagmacore/wallet/wallet.go diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index 0014df5db..500847b96 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -24,10 +24,10 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.22 + - name: Set up Go 1.23 uses: actions/setup-go@v3 with: - go-version: 1.22.5 + go-version: 1.23 - name: Clean build run: make clean-mobilesdk @@ -96,10 +96,10 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.22 + - name: Set up Go 1.23 uses: actions/setup-go@v3 with: - go-version: 1.22.5 + go-version: 1.23 - name: Install deps run: | @@ -199,10 +199,10 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.22 + - name: Set up Go 1.23 uses: actions/setup-go@v3 with: - go-version: 1.22.5 + go-version: 1.23 - name: Clean build run: make clean-mobilesdk @@ -271,10 +271,10 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.22 + - name: Set up Go 1.23 uses: actions/setup-go@v3 with: - go-version: 1.22.5 + go-version: 1.23 - name: Install deps run: | @@ -335,13 +335,13 @@ jobs: name: Build-wasm runs-on: [self-hosted, arc-runner] steps: - - name: Set up Go 1.x + - name: Set up Go 1.23 uses: actions/setup-go@v3 with: - go-version: 1.22.5 + go-version: 1.23 - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install dependencies run: | @@ -349,7 +349,7 @@ jobs: sudo apt-get -y install build-essential nghttp2 libnghttp2-dev libssl-dev wget - name: Build - run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.22.5 make wasm-build + run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.23 make wasm-build - name: 'Upload Artifact' uses: actions/upload-artifact@v3 diff --git a/README.md b/README.md index 369499924..8bbe1af8f 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ This repository currently supports the following platforms: import ( "fmt" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) func main() { diff --git a/constants/context_key.go b/constants/context_key.go deleted file mode 100644 index 8ac44740a..000000000 --- a/constants/context_key.go +++ /dev/null @@ -1,27 +0,0 @@ -package constants - -// ContextKey type for key used to store values into context -type ContextKey string - -const ( - // ContextKeyAllocation represents key for context value for allocation - ContextKeyAllocation ContextKey = "allocation" - - // ContextKeyAllocationObject represents key for context value for allocation object - ContextKeyAllocationObject ContextKey = "allocation_object" - - // ContextKeyClient represents key for context value for client - ContextKeyClient ContextKey = "client" - - // 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 deleted file mode 100644 index 703259889..000000000 --- a/constants/errors.go +++ /dev/null @@ -1,37 +0,0 @@ -// 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" - -var ( - // ErrInvalidParameter parameter is not specified or invalid - ErrInvalidParameter = errors.New("invalid parameter") - - // ErrUnableHash failed to hash with unknown exception - ErrUnableHash = errors.New("unable to hash") - - // ErrUnableWriteFile failed to write bytes to file - ErrUnableWriteFile = errors.New("unable to write file") - - // ErrNotImplemented feature/method is not implemented yet - ErrNotImplemented = errors.New("Not Implemented") - - // ErrNotLockedWritMarker failed to lock WriteMarker - ErrNotLockedWritMarker = errors.New("failed to lock WriteMarker") - - // ErrNotUnlockedWritMarker failed to unlock WriteMarker - ErrNotUnlockedWritMarker = errors.New("failed to unlock WriteMarker") - - // ErrInvalidHashnode invalid hashnode - ErrInvalidHashnode = errors.New("invalid hashnode") - - // ErrBadRequest bad request - ErrBadRequest = errors.New("bad request") - - // ErrNotFound ref not found - ErrNotFound = errors.New("ref not found") - - // ErrFileOptionNotPermitted requested operation is not allowed on this allocation (file_options) - ErrFileOptionNotPermitted = errors.New("this options for this file is not permitted for this allocation") -) diff --git a/constants/files.go b/constants/files.go deleted file mode 100644 index 0051a1404..000000000 --- a/constants/files.go +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 24e38f9ee..000000000 --- a/core/block/block.go +++ /dev/null @@ -1,94 +0,0 @@ -// 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 ( - "fmt" - - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/transaction" -) - -type Key []byte - -type Header struct { - Version string `json:"version,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - Hash string `json:"hash,omitempty"` - MinerID string `json:"miner_id,omitempty"` - Round int64 `json:"round,omitempty"` - RoundRandomSeed int64 `json:"round_random_seed,omitempty"` - MerkleTreeRoot string `json:"merkle_tree_root,omitempty"` - StateHash string `json:"state_hash,omitempty"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root,omitempty"` - 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, - h.ReceiptMerkleTreeRoot) - return encryption.Hash(data) == h.Hash -} - -/*Block - data structure that holds the block data */ -type Block struct { - Header *Header `json:"-"` - - MinerID common.Key `json:"miner_id"` - Round int64 `json:"round"` - RoundRandomSeed int64 `json:"round_random_seed"` - RoundTimeoutCount int `json:"round_timeout_count"` - - Hash common.Key `json:"hash"` - Signature string `json:"signature"` - ChainID common.Key `json:"chain_id"` - ChainWeight float64 `json:"chain_weight"` - RunningTxnCount int64 `json:"running_txn_count"` - - Version string `json:"version"` - CreationDate common.Timestamp `json:"creation_date"` - - MagicBlockHash string `json:"magic_block_hash"` - PrevHash string `json:"prev_hash"` - - ClientStateHash Key `json:"state_hash"` - Txns []*transaction.Transaction `json:"transactions,omitempty"` - - // muted - - // VerificationTickets []*VerificationTicket `json:"verification_tickets,omitempty"` - // PrevBlockVerificationTickets []*VerificationTicket `json:"prev_verification_tickets,omitempty"` -} - -type ChainStats struct { - BlockSize int `json:"block_size"` - Count int `json:"count"` - CurrentRound int `json:"current_round"` - Delta int `json:"delta"` - LatestFinalizedRound int `json:"latest_finalized_round"` - Max float64 `json:"max"` - Mean float64 `json:"mean"` - Min float64 `json:"min"` - Percentile50 float64 `json:"percentile_50"` - Percentile90 float64 `json:"percentile_90"` - Percentile95 float64 `json:"percentile_95"` - Percentile99 float64 `json:"percentile_99"` - Rate15Min float64 `json:"rate_15_min"` - Rate1Min float64 `json:"rate_1_min"` - Rate5Min float64 `json:"rate_5_min"` - RateMean float64 `json:"rate_mean"` - StdDev float64 `json:"std_dev"` - TotalTxns int `json:"total_txns"` -} - -type FeeStats struct { - MaxFees common.Balance `json:"max_fees"` - MinFees common.Balance `json:"min_fees"` - MeanFees common.Balance `json:"mean_fees"` -} diff --git a/core/block/magic_block_entity.go b/core/block/magic_block_entity.go deleted file mode 100644 index fdf06adaa..000000000 --- a/core/block/magic_block_entity.go +++ /dev/null @@ -1,71 +0,0 @@ -package block - -import "time" - -type Node struct { - ID string `yaml:"id" json:"id"` - Version string `yaml:"version" json:"version"` - CreationDate int64 `json:"creation_date"` - PublicKey string `yaml:"public_key" json:"public_key"` - PrivateKey string `yaml:"private_key" json:"-"` - N2NHost string `yaml:"n2n_ip" json:"n2n_host"` - Host string `yaml:"public_ip" json:"host"` - Port int `yaml:"port" json:"port"` - Path string `yaml:"path" json:"path"` - Type int `json:"type"` - Description string `yaml:"description" json:"description"` - SetIndex int `yaml:"set_index" json:"set_index"` - Status int `json:"status"` - Info Info `json:"info"` -} - -type Info struct { - BuildTag string `json:"build_tag"` - StateMissingNodes int64 `json:"state_missing_nodes"` - MinersMedianNetworkTime time.Duration `json:"miners_median_network_time"` - AvgBlockTxns int `json:"avg_block_txns"` -} - -type NodePool struct { - Type int `json:"type"` - Nodes map[string]Node `json:"nodes"` -} - -type GroupSharesOrSigns struct { - Shares map[string]*ShareOrSigns `json:"shares"` -} - -type ShareOrSigns struct { - ID string `json:"id"` - ShareOrSigns map[string]*DKGKeyShare `json:"share_or_sign"` -} - -type DKGKeyShare struct { - ID string `json:"id"` - Message string `json:"message"` - Share string `json:"share"` - Sign string `json:"sign"` -} - -type Mpks struct { - Mpks map[string]*MPK -} - -type MPK struct { - ID string - Mpk []string -} - -type MagicBlock struct { - Hash string `json:"hash"` - PreviousMagicBlockHash string `json:"previous_hash"` - MagicBlockNumber int64 `json:"magic_block_number"` - StartingRound int64 `json:"starting_round"` - Miners *NodePool `json:"miners"` //this is the pool of miners participating in the blockchain - Sharders *NodePool `json:"sharders"` //this is the pool of sharders participaing in the blockchain - ShareOrSigns *GroupSharesOrSigns `json:"share_or_signs"` - Mpks *Mpks `json:"mpks"` - T int `json:"t"` - K int `json:"k"` - N int `json:"n"` -} diff --git a/core/build.go b/core/build.go deleted file mode 100644 index 97e341d61..000000000 --- a/core/build.go +++ /dev/null @@ -1,2 +0,0 @@ -// Provides some low-level functions and types that are used by the SDK. -package core diff --git a/core/common/math.go b/core/common/math.go deleted file mode 100644 index 0b9bbf59e..000000000 --- a/core/common/math.go +++ /dev/null @@ -1,33 +0,0 @@ -package common - -import ( - "errors" - "math" -) - -func TryAddInt(a, b int) (int, error) { - if a > 0 && b > 0 { - if math.MaxInt-a < b { - return 0, errors.New("math: integer overflow") - } - - } - - if a < 0 && b < 0 { - if math.MinInt-a > b { - return 0, errors.New("math: integer underflow") - } - - } - - return a + b, nil -} - -func MustAddInt(a, b int) int { - i, err := TryAddInt(a, b) - if err != nil { - panic(err.Error()) - } - - return i -} diff --git a/core/common/math_test.go b/core/common/math_test.go deleted file mode 100644 index 0959f05b5..000000000 --- a/core/common/math_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package common - -import ( - "math" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestMathAddInt(t *testing.T) { - a := math.MaxInt - b := 1 - - _, err := TryAddInt(a, b) - require.NotNil(t, err) - - tests := []struct { - name string - a int - b int - result int - wantErr bool - }{ - { - name: "greater than MaxInt must be overflow", - a: math.MaxInt, - b: 1, - wantErr: true, - }, - { - name: "equal to MaxInt must not be overflow", - a: math.MaxInt - 1, - b: 1, - result: math.MaxInt, - }, - { - name: "less than MaxInt must not be overflow", - a: math.MaxInt - 2, - b: 1, - result: math.MaxInt - 1, - }, - { - name: "greater than MinInt must not be underflow", - a: math.MinInt, - b: 1, - result: math.MinInt + 1, - }, - { - name: "equal to MinInt should not be underflow", - a: math.MinInt + 1, - b: -1, - result: math.MinInt, - }, - { - name: "less than MinInt must be underflow", - a: math.MinInt, - b: -1, - wantErr: true, - }, - } - - for _, test := range tests { - - t.Run(test.name, func(t *testing.T) { - - i, err := TryAddInt(test.a, test.b) - if test.wantErr { - require.NotNil(t, err) - } - - require.Equal(t, test.result, i) - - }) - - } - -} diff --git a/core/common/misc.go b/core/common/misc.go deleted file mode 100644 index e8377e04a..000000000 --- a/core/common/misc.go +++ /dev/null @@ -1,259 +0,0 @@ -package common - -import ( - "errors" - "fmt" - "math" - "regexp" - "strconv" - - "github.com/shopspring/decimal" -) - -const ( - ZCNExponent = 10 - // TokenUnit represents the minimum token unit (sas) - TokenUnit = 1e10 -) - -var ( - // ErrNegativeValue is returned if a float value is a negative number - ErrNegativeValue = errors.New("negative coin value") - // ErrTooManyDecimals is returned if a value has more than 10 decimal places - ErrTooManyDecimals = errors.New("too many decimal places") - // ErrTooLarge is returned if a value is greater than math.MaxInt64 - ErrTooLarge = errors.New("value is too large") - // ErrUint64OverflowsFloat64 is returned if when converting a uint64 to a float64 overflow float64 - ErrUint64OverflowsFloat64 = errors.New("uint64 overflows float64") - // ErrUint64AddOverflow is returned if when adding uint64 values overflow uint64 - ErrUint64AddOverflow = errors.New("uint64 addition overflow") -) - -// A Key represents an identifier. It can be a pool ID, client ID, smart -// contract address, etc. -type Key string - -// A Size represents a size in bytes. -type Size int64 - -func byteCountIEC(b int64) string { - const unit = 1024 - if b < unit { - return fmt.Sprintf("%d B", b) - } - div, exp := int64(unit), 0 - for n := b / unit; n >= unit; n /= unit { - div *= unit - exp++ - } - return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp]) -} - -// String implements fmt.Stringer interface -func (s Size) String() string { - return byteCountIEC(int64(s)) -} - -/* Balance */ - -// 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 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 - } - - f, _ := decimal.New(int64(b), -ZCNExponent).Float64() - return f, nil -} - -// String implements fmt.Stringer interface. -func (b Balance) String() string { - if val, err := b.AutoFormat(); err == nil { - return val - } - 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 { - return "", ErrUint64OverflowsFloat64 - } - switch unit { - case SAS: - return fmt.Sprintf("%d %v", b, unit), nil - case UZCN: - v /= 1e4 - case MZCN: - v /= 1e7 - case ZCN: - v /= 1e10 - default: - return "", fmt.Errorf("undefined balance unit: %d", unit) - } - 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: - return b.Format(ZCN) - case b/1e7 > 0: - return b.Format(MZCN) - case b/1e4 > 0: - return b.Format(UZCN) - } - return b.Format(SAS) -} - -// 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 { - return 0, ErrNegativeValue - } - - // ZCN have a maximum of 10 decimal places - if d.Exponent() < -ZCNExponent { - return 0, ErrTooManyDecimals - } - - // Multiply the coin balance by 1e10 to obtain coin amount - e := d.Shift(ZCNExponent) - - // Check that there are no decimal places remaining. This error should not - // occur, because of the earlier check of ZCNExponent() - if e.Exponent() < 0 { - return 0, ErrTooManyDecimals - } - - maxDecimal := decimal.NewFromInt(math.MaxInt64) - // Values greater than math.MaxInt64 will overflow after conversion to int64 - if e.GreaterThan(maxDecimal) { - return 0, ErrTooLarge - } - - return Balance(e.IntPart()), nil -} - -// AddBalance adds c and b, returning an error if the values overflow -func AddBalance(c, b Balance) (Balance, error) { - sum := c + b - if sum < c || sum < b { - return 0, ErrUint64AddOverflow - } - 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() -} - -func ParseBalance(str string) (Balance, error) { - - matches := reParseToken.FindAllStringSubmatch(str, -1) - - if len(matches) != 1 || len(matches[0]) != 3 { - return 0, fmt.Errorf("invalid input: %s", str) - } - - b, err := strconv.ParseFloat(matches[0][1], 64) - if err != nil { - return 0, err - } - - var unit BalanceUnit - - err = unit.Parse(matches[0][2]) - if err != nil { - return 0, err - } - - switch unit { - case UZCN: - b *= 1e4 - case MZCN: - b *= 1e7 - case ZCN: - b *= 1e10 - } - - return Balance(b), nil -} - -const ( - SAS BalanceUnit = iota - UZCN - MZCN - ZCN -) - -type BalanceUnit byte - -func (unit BalanceUnit) String() string { - switch unit { - case SAS: - return "SAS" - case MZCN: - return "mZCN" - case UZCN: - return "uZCN" - case ZCN: - return "ZCN" - } - return "" -} - -func (unit *BalanceUnit) Parse(s string) error { - switch s { - case "SAS", "sas": - *unit = SAS - case "uZCN", "uzcn": - *unit = UZCN - case "mZCN", "mzcn": - *unit = MZCN - case "ZCN", "zcn": - *unit = ZCN - default: - return errors.New("undefined balance unit: " + s) - } - return nil -} - -func ParseBalanceStatic(str string) (int64, error) { - bal, err := ParseBalance(str) - return int64(bal), err -} - -func FormatStatic(amount int64, unit string) (string, error) { - token := Balance(amount) - - var unitB BalanceUnit - err := unitB.Parse(unit) - if err != nil { - return "", err - } - - return token.Format(unitB) -} - -func AutoFormatStatic(amount int64) (string, error) { - token := Balance(amount) - return token.AutoFormat() -} diff --git a/core/common/misc_test.go b/core/common/misc_test.go deleted file mode 100644 index 1a585c483..000000000 --- a/core/common/misc_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package common - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFormat(t *testing.T) { - token := Balance(129382129321) - formattedToken, err := token.Format(ZCN) - require.Equal(t, "12.938 ZCN", formattedToken) - require.NoError(t, err) - - formattedToken, err = token.Format(MZCN) - require.Equal(t, "12938.213 mZCN", formattedToken) - require.NoError(t, err) - - formattedToken, err = token.Format(UZCN) - require.Equal(t, "12938212.932 uZCN", formattedToken) - require.NoError(t, err) - - formattedToken, err = token.Format(SAS) - require.Equal(t, "129382129321 SAS", formattedToken) - require.NoError(t, err) - - _, err = token.Format(5) - require.EqualError(t, err, "undefined balance unit: 5") -} - -func TestFormatStatic(t *testing.T) { - amount := int64(129382129321) - zcnAmount, err := FormatStatic(amount, "ZCN") - require.Equal(t, "12.938 ZCN", zcnAmount) - require.NoError(t, err) - - mZCNAmount, err := FormatStatic(amount, "mZCN") - require.Equal(t, "12938.213 mZCN", mZCNAmount) - require.NoError(t, err) - - uZCN, err := FormatStatic(amount, "uZCN") - require.Equal(t, "12938212.932 uZCN", uZCN) - require.NoError(t, err) - - sas, err := FormatStatic(amount, "SAS") - require.Equal(t, "129382129321 SAS", sas) - require.NoError(t, err) -} - -func TestAutoFormat(t *testing.T) { - autoFormatValue, err := AutoFormatStatic(239) - require.Equal(t, "239 SAS", autoFormatValue) - require.NoError(t, err) - - autoFormatValue, err = AutoFormatStatic(27361) - require.Equal(t, "2.736 uZCN", autoFormatValue) - require.NoError(t, err) - - autoFormatValue, err = AutoFormatStatic(23872013) - require.Equal(t, "2.387 mZCN", autoFormatValue) - require.NoError(t, err) - - autoFormatValue, err = AutoFormatStatic(203827162834) - require.Equal(t, "20.383 ZCN", autoFormatValue) - require.NoError(t, err) -} - -func TestAutoFormatStatic(t *testing.T) { - autoFormatValue, err := Balance(239).AutoFormat() - require.Equal(t, "239 SAS", autoFormatValue) - require.NoError(t, err) - - autoFormatValue, err = Balance(27361).AutoFormat() - require.Equal(t, "2.736 uZCN", autoFormatValue) - require.NoError(t, err) - - autoFormatValue, err = Balance(23872013).AutoFormat() - require.Equal(t, "2.387 mZCN", autoFormatValue) - require.NoError(t, err) - - autoFormatValue, err = Balance(203827162834).AutoFormat() - require.Equal(t, "20.383 ZCN", autoFormatValue) - require.NoError(t, err) -} - -func TestParseBalance(t *testing.T) { - b, err := ParseBalance("12.938 ZCN") - require.NoError(t, err) - require.Equal(t, Balance(12.938*1e10), b) - - b, err = ParseBalance("12.938 mzcn") - require.NoError(t, err) - require.Equal(t, Balance(12.938*1e7), b) - - b, err = ParseBalance("12.938 uZCN") - require.NoError(t, err) - require.Equal(t, Balance(12.938*1e4), b) - - b, err = ParseBalance("122389 sas") - require.NoError(t, err) - require.Equal(t, Balance(122389*1e0), b) - - _, err = ParseBalance("10 ") - require.EqualError(t, err, "invalid input: 10 ") - - _, err = ParseBalance("10 zwe") - require.EqualError(t, err, "invalid input: 10 zwe") - - _, err = ParseBalance(" 10 zcn ") - require.EqualError(t, err, "invalid input: 10 zcn ") -} - -func TestToBalance(t *testing.T) { - expectedBalance := Balance(20100000000) - balance, err := ToBalance(2.01) - require.Equal(t, expectedBalance, balance) - require.NoError(t, err) - - expectedBalance = Balance(30099999999) - balance, err = ToBalance(3.0099999999) - require.Equal(t, expectedBalance, balance) - require.NoError(t, err) -} - -func TestToToken(t *testing.T) { - b := Balance(12.938 * 1e12) - token, err := b.ToToken() - require.Equal(t, 1293.8, token) - require.NoError(t, err) - - b = Balance(12.938 * 1e5) - token, err = b.ToToken() - require.Equal(t, 0.00012938, token) - require.NoError(t, err) -} diff --git a/core/common/time.go b/core/common/time.go deleted file mode 100644 index dbad4a2e4..000000000 --- a/core/common/time.go +++ /dev/null @@ -1,80 +0,0 @@ -package common - -import ( - "errors" - "strconv" - "strings" - "time" -) - -// Timestamp represents Unix time (e.g. in seconds) -type Timestamp int64 - -// Now current datetime -func Now() Timestamp { - return Timestamp(time.Now().Unix()) -} - -// Within ensures a given timestamp is within certain number of seconds -func (t Timestamp) Within(seconds Timestamp) bool { - var now = Now() - return now > t-seconds && now < t+seconds -} - -// ToTime converts the Timestamp to standard time.Time -func (t Timestamp) ToTime() time.Time { - return time.Unix(int64(t), 0) -} - -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 -// -// 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 { - return nil, ErrInvalidTime - } - - if input[0] == '+' { - val := strings.TrimLeft(input, "+") - s, err := strconv.Atoi(val) - // +3900 : now (local timezone) +3900s - if err == nil { - now = now.Add(time.Duration(s) * time.Second) - return &now, nil - } - - d, err := time.ParseDuration(val) - // +1h5m : now (local timezone) + 1h5m - if err == nil { - now = now.Add(d) - return &now, nil - } - - return nil, ErrInvalidTime - } - - s, err := strconv.ParseInt(input, 10, 64) - if err == nil { - now = time.Unix(s, 0) - return &now, nil - } - - // 2022-03-21 10:21:38 : parse UTC date string with YYYY-MM-dd HH:mm:ss - t, err := time.Parse("2006-01-02 15:04:05 -0700", input+" +0000") - if err == nil { - return &t, nil - } - - return nil, ErrInvalidTime - -} diff --git a/core/common/time_test.go b/core/common/time_test.go deleted file mode 100644 index 0a4d5ca2f..000000000 --- a/core/common/time_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package common - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestParseTime(t *testing.T) { - - now := time.Date(2022, 3, 22, 0, 0, 0, 0, time.Now().UTC().Location()) - null := time.Now() - - tests := []struct { - name string - input string - exceptedTime time.Time - exceptedErr error - }{ - { - name: "duration", - input: "+1h30m", - exceptedTime: now.Add(90 * time.Minute), - }, - { - name: "seconds", - input: "+30", - exceptedTime: now.Add(30 * time.Second), - }, - { - name: "Unix timestamp", - input: "1647858200", - exceptedTime: time.Unix(1647858200, 0), - }, - { - name: "YYYY-MM-dd HH:mm:ss", - input: "1647858200", - exceptedTime: time.Unix(1647858200, 0), - }, - { - name: "empty input", - input: "", - exceptedTime: null, - exceptedErr: ErrInvalidTime, - }, - { - name: "invaid input", - input: "s", - exceptedTime: null, - exceptedErr: ErrInvalidTime, - }, - } - - for _, test := range tests { - - t.Run(test.name, func(t *testing.T) { - - v, err := ParseTime(now, test.input) - - if test.exceptedTime.Equal(null) { - require.Nil(t, v) - } else { - require.NotNil(t, v) - require.True(t, v.Equal(test.exceptedTime)) - } - - if test.exceptedErr == nil { - require.Nil(t, err) - } else { - require.True(t, errors.Is(err, test.exceptedErr)) - } - }) - } - -} diff --git a/core/common/utils.go b/core/common/utils.go deleted file mode 100644 index c88159ba3..000000000 --- a/core/common/utils.go +++ /dev/null @@ -1,26 +0,0 @@ -// Provides the data structures and methods to work with the common data structures. -package common - -import ( - "fmt" - "path" - "strings" - - "github.com/valyala/bytebufferpool" -) - -var MemPool bytebufferpool.Pool - -func GetPathFields(p string) ([]string, error) { - if p == "" || p == "/" { - return nil, nil - } - - if !path.IsAbs(p) { - return nil, fmt.Errorf("path %s is not absolute", p) - } - - p = path.Clean(p) - fields := strings.Split(p, "/") - return fields[1:], nil -} diff --git a/core/conf/config.go b/core/conf/config.go deleted file mode 100644 index 083272521..000000000 --- a/core/conf/config.go +++ /dev/null @@ -1,187 +0,0 @@ -// 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 ( - "errors" - "net/url" - "os" - "strings" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/sys" - "github.com/spf13/viper" -) - -const ( - // DefaultMinSubmit default value for min_submit - DefaultMinSubmit = 10 - // DefaultMinConfirmation default value for min_confirmation - DefaultMinConfirmation = 10 - // DefaultMaxTxnQuery default value for max_txn_query - DefaultMaxTxnQuery = 5 - // DefaultConfirmationChainLength default value for confirmation_chain_length - DefaultConfirmationChainLength = 3 - // DefaultQuerySleepTime default value for query_sleep_time - DefaultQuerySleepTime = 5 - // DefaultSharderConsensous default consensous to take make SCRestAPI calls - DefaultSharderConsensous = 3 -) - -// 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 -type Config struct { - // BlockWorker the url of 0dns's network api - BlockWorker string `json:"block_worker,omitempty"` - - // MinSubmit mininal submit from blobber - MinSubmit int `json:"min_submit,omitempty"` - // MinConfirmation mininal confirmation from sharders - MinConfirmation int `json:"min_confirmation,omitempty"` - // CconfirmationChainLength minial confirmation chain length - ConfirmationChainLength int `json:"confirmation_chain_length,omitempty"` - - // additional settings depending network latency - // MaxTxnQuery maximum transcation query from sharders - MaxTxnQuery int `json:"max_txn_query,omitempty"` - // QuerySleepTime sleep time before transcation query - QuerySleepTime int `json:"query_sleep_time,omitempty"` - - // SignatureScheme signature scheme - SignatureScheme string `json:"signature_scheme,omitempty"` - // ChainID which blockchain it is working - ChainID string `json:"chain_id,omitempty"` - - VerifyOptimistic bool - - // Ethereum node: "https://ropsten.infura.io/v3/xxxxxxxxxxxxxxx" - EthereumNode string `json:"ethereum_node,omitempty"` - - // ZboxHost 0box api host host: "https://0box.dev.0chain.net" - ZboxHost string `json:"zbox_host"` - // ZboxAppType app type name - ZboxAppType string `json:"zbox_app_type"` - // SharderConsensous is consensous for when quering for SCRestAPI calls - SharderConsensous int `json:"sharder_consensous"` - ZauthServer string `json:"zauth_server"` - V *viper.Viper `json:"-"` -} - -// LoadConfigFile load and parse SDK Config from file -// - file: config file path (full path) -func LoadConfigFile(file string) (Config, error) { - - var cfg Config - var err error - - _, err = sys.Files.Stat(file) - - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return cfg, thrown.Throw(ErrMssingConfig, file) - } - return cfg, err - } - - v := viper.New() - - v.SetConfigFile(file) - - if err := v.ReadInConfig(); err != nil { - return cfg, thrown.Throw(ErrBadParsing, err.Error()) - } - - cfg, err = LoadConfig(v) - if err != nil { - return cfg, err - } - - cfg.V = v - - return cfg, nil -} - -// LoadConfig load and parse config -func LoadConfig(v Reader) (Config, error) { - - var cfg Config - - blockWorker := strings.TrimSpace(v.GetString("block_worker")) - - if !isURL(blockWorker) { - return cfg, thrown.Throw(ErrInvalidValue, "block_worker="+blockWorker) - } - - minSubmit := v.GetInt("min_submit") - if minSubmit < 1 { - minSubmit = DefaultMinSubmit - } else if minSubmit > 100 { - minSubmit = 100 - } - - minCfm := v.GetInt("min_confirmation") - - if minCfm < 1 { - minCfm = DefaultMinConfirmation - } else if minCfm > 100 { - minCfm = 100 - } - - CfmChainLength := v.GetInt("confirmation_chain_length") - - if CfmChainLength < 1 { - CfmChainLength = DefaultConfirmationChainLength - } - - // additional settings depending network latency - maxTxnQuery := v.GetInt("max_txn_query") - if maxTxnQuery < 1 { - maxTxnQuery = DefaultMaxTxnQuery - } - - querySleepTime := v.GetInt("query_sleep_time") - if querySleepTime < 1 { - querySleepTime = DefaultQuerySleepTime - } - VerifyOptimisticString := v.GetString("verify_optimistic") - if VerifyOptimisticString == "true" { - cfg.VerifyOptimistic = true - } - - sharderConsensous := v.GetInt("sharder_consensous") - if sharderConsensous < 1 { - sharderConsensous = DefaultSharderConsensous - } - - cfg.BlockWorker = blockWorker - cfg.MinSubmit = minSubmit - cfg.MinConfirmation = minCfm - cfg.ConfirmationChainLength = CfmChainLength - cfg.MaxTxnQuery = maxTxnQuery - cfg.QuerySleepTime = querySleepTime - cfg.SharderConsensous = sharderConsensous - - cfg.SignatureScheme = v.GetString("signature_scheme") - cfg.ChainID = v.GetString("chain_id") - cfg.ZauthServer = v.GetString("zauth_server") - - return cfg, nil -} - -func isURL(s string) bool { - u, err := url.Parse(s) - return err == nil && u.Scheme != "" && u.Host != "" -} diff --git a/core/conf/config_test.go b/core/conf/config_test.go deleted file mode 100644 index 9bb7f7c68..000000000 --- a/core/conf/config_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package conf - -import ( - "testing" - - "github.com/0chain/gosdk_common/core/conf/mocks" - "github.com/stretchr/testify/require" -) - -func TestLoadConfig(t *testing.T) { - - var mockDefaultReader = func() Reader { - reader := &mocks.Reader{} - reader.On("GetString", "block_worker").Return("http://127.0.0.1:9091/dns") - reader.On("GetString", "zauth.server").Return("http://127.0.0.1:8090/") - reader.On("GetInt", "min_submit").Return(0) - reader.On("GetInt", "min_confirmation").Return(0) - reader.On("GetInt", "max_txn_query").Return(0) - reader.On("GetInt", "query_sleep_time").Return(0) - reader.On("GetInt", "confirmation_chain_length").Return(0) - reader.On("GetStringSlice", "preferred_blobbers").Return(nil) - reader.On("GetString", "signature_scheme").Return("") - reader.On("GetString", "chain_id").Return("") - reader.On("GetString", "verify_optimistic").Return("true") - reader.On("GetInt", "sharder_consensous").Return(0) - - return reader - - } - - tests := []struct { - name string - exceptedErr error - - setup func(*testing.T) Reader - run func(*require.Assertions, Config) - }{ - { - name: "Test_Config_Invalid_BlockWorker", - exceptedErr: ErrInvalidValue, - setup: func(t *testing.T) Reader { - - reader := &mocks.Reader{} - reader.On("GetString", "block_worker").Return("") - reader.On("GetString", "zauth.server").Return("") - reader.On("GetInt", "min_submit").Return(0) - reader.On("GetInt", "min_confirmation").Return(0) - reader.On("GetInt", "max_txn_query").Return(0) - reader.On("GetInt", "query_sleep_time").Return(0) - reader.On("GetInt", "confirmation_chain_length").Return(0) - reader.On("GetStringSlice", "preferred_blobbers").Return(nil) - reader.On("GetString", "signature_scheme").Return("") - reader.On("GetString", "chain_id").Return("") - reader.On("GetString", "verify_optimistic").Return("true") - reader.On("GetInt", "sharder_consensous").Return(0) - - return reader - }, - run: func(r *require.Assertions, cfg Config) { - - }, - }, - { - name: "Test_Config_BlockWorker", - - setup: func(t *testing.T) Reader { - return mockDefaultReader() - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal("http://127.0.0.1:9091/dns", cfg.BlockWorker) - }, - }, - { - name: "Test_Config_Min_Submit_Less_Than_1", - - setup: func(t *testing.T) Reader { - return mockDefaultReader() - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(10, cfg.MinSubmit) - }, - }, - { - name: "Test_Config_Min_Submit_Greater_Than_100", - - setup: func(t *testing.T) Reader { - - reader := &mocks.Reader{} - reader.On("GetString", "block_worker").Return("https://127.0.0.1:9091/dns") - reader.On("GetString", "zauth.server").Return("http://127.0.0.1:8090/") - reader.On("GetInt", "min_submit").Return(101) - reader.On("GetInt", "min_confirmation").Return(0) - reader.On("GetInt", "max_txn_query").Return(0) - reader.On("GetInt", "query_sleep_time").Return(0) - reader.On("GetInt", "confirmation_chain_length").Return(0) - reader.On("GetStringSlice", "preferred_blobbers").Return(nil) - reader.On("GetString", "signature_scheme").Return("") - reader.On("GetString", "chain_id").Return("") - reader.On("GetString", "verify_optimistic").Return("true") - reader.On("GetInt", "sharder_consensous").Return(0) - - return reader - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(100, cfg.MinSubmit) - }, - }, - { - name: "Test_Config_Min_Confirmation_Less_Than_1", - - setup: func(t *testing.T) Reader { - return mockDefaultReader() - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(10, cfg.MinConfirmation) - }, - }, - { - name: "Test_Config_Min_Confirmation_Greater_100", - - setup: func(t *testing.T) Reader { - - reader := &mocks.Reader{} - reader.On("GetString", "block_worker").Return("https://127.0.0.1:9091/dns") - reader.On("GetString", "zauth.server").Return("http://127.0.0.1:8090/") - reader.On("GetInt", "min_submit").Return(0) - reader.On("GetInt", "min_confirmation").Return(101) - reader.On("GetInt", "max_txn_query").Return(0) - reader.On("GetInt", "query_sleep_time").Return(0) - reader.On("GetInt", "confirmation_chain_length").Return(0) - reader.On("GetStringSlice", "preferred_blobbers").Return(nil) - reader.On("GetString", "signature_scheme").Return("") - reader.On("GetString", "chain_id").Return("") - reader.On("GetString", "verify_optimistic").Return("false") - reader.On("GetInt", "sharder_consensous").Return(0) - - return reader - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(100, cfg.MinConfirmation) - }, - }, { - name: "Test_Config_Nax_Txn_Query_Less_Than_1", - - setup: func(t *testing.T) Reader { - - return mockDefaultReader() - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(5, cfg.QuerySleepTime) - }, - }, { - name: "Test_Config_Max_Txn_Query_Less_Than_1", - - setup: func(t *testing.T) Reader { - - return mockDefaultReader() - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(5, cfg.MaxTxnQuery) - }, - }, { - name: "Test_Config_Confirmation_Chain_Length_Less_Than_1", - - setup: func(t *testing.T) Reader { - return mockDefaultReader() - }, - run: func(r *require.Assertions, cfg Config) { - r.Equal(3, cfg.ConfirmationChainLength) - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - - require := require.New(t) - - reader := tt.setup(t) - - cfg, err := LoadConfig(reader) - - // test it by predefined error variable instead of error message - if tt.exceptedErr != nil { - require.ErrorIs(err, tt.exceptedErr) - } else { - require.Equal(nil, err) - } - - if tt.run != nil { - tt.run(require, cfg) - } - - }) - } -} diff --git a/core/conf/mocks/Reader.go b/core/conf/mocks/Reader.go deleted file mode 100644 index 9bb859362..000000000 --- a/core/conf/mocks/Reader.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by mockery 2.9.0. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// Reader is an autogenerated mock type for the Reader type -type Reader struct { - mock.Mock -} - -// GetInt provides a mock function with given fields: key -func (_m *Reader) GetInt(key string) int { - ret := _m.Called(key) - - var r0 int - if rf, ok := ret.Get(0).(func(string) int); ok { - r0 = rf(key) - } else { - r0 = ret.Get(0).(int) - } - - return r0 -} - -// GetString provides a mock function with given fields: key -func (_m *Reader) GetString(key string) string { - ret := _m.Called(key) - - var r0 string - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(key) - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetStringSlice provides a mock function with given fields: key -func (_m *Reader) GetStringSlice(key string) []string { - ret := _m.Called(key) - - var r0 []string - if rf, ok := ret.Get(0).(func(string) []string); ok { - r0 = rf(key) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]string) - } - } - - return r0 -} diff --git a/core/conf/mocks/doc.go b/core/conf/mocks/doc.go deleted file mode 100644 index d5f5048fa..000000000 --- a/core/conf/mocks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// AUTOGENERATED! Do not use. -package mocks \ No newline at end of file diff --git a/core/conf/network.go b/core/conf/network.go deleted file mode 100644 index 72dc2ae06..000000000 --- a/core/conf/network.go +++ /dev/null @@ -1,58 +0,0 @@ -package conf - -import ( - "errors" - "os" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/sys" - "github.com/spf13/viper" -) - -// Network settings from ~/.zcn/network.yaml -type Network struct { - // Sharders sharder list of blockchain - Sharders []string - // Miners miner list of blockchain - Miners []string -} - -// IsValid check network if it has miners and sharders -func (n *Network) IsValid() bool { - return n != nil && len(n.Miners) > 0 && len(n.Sharders) > 0 -} - -// 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 - var err error - - _, err = sys.Files.Stat(file) - - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return network, thrown.Throw(ErrMssingConfig, file) - } - return network, err - } - - v := viper.New() - - v.SetConfigFile(file) - - if err := v.ReadInConfig(); err != nil { - return network, thrown.Throw(ErrBadParsing, err.Error()) - } - - return LoadNetwork(v), nil -} - -// LoadNetwork load and parse network -func LoadNetwork(v Reader) Network { - return Network{ - Sharders: v.GetStringSlice("sharders"), - Miners: v.GetStringSlice("miners"), - } -} diff --git a/core/conf/reader.go b/core/conf/reader.go deleted file mode 100644 index 75df8a940..000000000 --- a/core/conf/reader.go +++ /dev/null @@ -1,99 +0,0 @@ -// pakcage conf provide config helpers for ~/.zcn/config.yaml, ~/.zcn/network.yaml and ~/.zcn/wallet.json - -package conf - -import ( - "encoding/json" -) - -// Reader a config reader -type Reader interface { - GetString(key string) string - GetInt(key string) int - GetStringSlice(key string) []string -} - -// JSONReader read config from json -type JSONReader struct { - items map[string]json.RawMessage -} - -func (r *JSONReader) getRawMessage(key string) (json.RawMessage, bool) { - if r == nil || r.items == nil { - return nil, false - } - v, ok := r.items[key] - if !ok { - return nil, false - } - - return v, true - -} - -// GetString read string from key -func (r *JSONReader) GetString(key string) string { - v, ok := r.getRawMessage(key) - if !ok { - return "" - } - - var s string - err := json.Unmarshal(v, &s) - if err != nil { - return "" - } - - return s -} - -// GetInt read int from key -func (r *JSONReader) GetInt(key string) int { - v, ok := r.getRawMessage(key) - if !ok { - return 0 - } - - var i int - - err := json.Unmarshal(v, &i) - if err != nil { - return 0 - } - - return i -} - -// GetStringSlice get string slice from key -func (r *JSONReader) GetStringSlice(key string) []string { - - v, ok := r.getRawMessage(key) - if !ok { - return nil - } - - var list []string - - err := json.Unmarshal(v, &list) - if err != nil { - return nil - } - - return list -} - -// NewReaderFromJSON create a JSONReader from json string -func NewReaderFromJSON(data string) (Reader, error) { - - var items map[string]json.RawMessage - - err := json.Unmarshal([]byte(data), &items) - - if err != nil { - return nil, err - } - - return &JSONReader{ - items: items, - }, nil -} diff --git a/core/conf/reader_test.go b/core/conf/reader_test.go deleted file mode 100644 index ecc03e934..000000000 --- a/core/conf/reader_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package conf - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestJSONReader(t *testing.T) { - - reader, _ := NewReaderFromJSON(`{ - "chain_id":"chain_id", - "signature_scheme" : "bls0chain", - "block_worker" : "http://localhost/dns", - "min_submit" : -20, - "min_confirmation" : 10, - "confirmation_chain_length" : 0, - "preferred_blobbers":["http://localhost:31051", - "http://localhost:31052", - "http://localhost:31053" - ] -}`) - - tests := []struct { - name string - run func(*require.Assertions) - }{ - { - name: "Test_JSONReader_GetString", - run: func(r *require.Assertions) { - r.Equal("chain_id", reader.GetString("chain_id")) - r.Equal("bls0chain", reader.GetString("signature_scheme")) - r.Equal("http://localhost/dns", reader.GetString("block_worker")) - }, - }, - { - name: "Test_JSONReader_GetInt", - - run: func(r *require.Assertions) { - r.Equal(-20, reader.GetInt("min_submit")) - r.Equal(10, reader.GetInt("min_confirmation")) - r.Equal(0, reader.GetInt("confirmation_chain_length")) - }, - }, - { - name: "Test_JSONReader_GetStringSlice", - run: func(r *require.Assertions) { - - preferredBlobbers := reader.GetStringSlice("preferred_blobbers") - - r.Equal(3, len(preferredBlobbers)) - r.Equal(preferredBlobbers[0], "http://localhost:31051") - r.Equal(preferredBlobbers[1], "http://localhost:31052") - r.Equal(preferredBlobbers[2], "http://localhost:31053") - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - - require := require.New(t) - - tt.run(require) - - }) - } -} diff --git a/core/conf/vars.go b/core/conf/vars.go deleted file mode 100644 index 211c23c05..000000000 --- a/core/conf/vars.go +++ /dev/null @@ -1,82 +0,0 @@ -package conf - -import ( - "errors" - "strings" - "sync" -) - -var ( - // global client config - cfg *Config - onceCfg sync.Once - // global sharders and miners - network *Network -) - -var ( - //ErrNilConfig config is nil - ErrNilConfig = errors.New("[conf]config is nil") - - // ErrMssingConfig config file is missing - ErrMssingConfig = errors.New("[conf]missing config file") - // ErrInvalidValue invalid value in config - ErrInvalidValue = errors.New("[conf]invalid value") - // ErrBadParsing fail to parse config via spf13/viper - ErrBadParsing = errors.New("[conf]bad parsing") - - // ErrConfigNotInitialized config is not initialized - ErrConfigNotInitialized = errors.New("[conf]conf.cfg is not initialized. please initialize it by conf.InitClientConfig") -) - -// GetClientConfig get global client config from the SDK configuration -func GetClientConfig() (*Config, error) { - if cfg == nil { - return nil, ErrConfigNotInitialized - } - - return cfg, nil -} - -// InitClientConfig set global client SDK config -func InitClientConfig(c *Config) { - onceCfg.Do(func() { - sharderConsensous := c.SharderConsensous - if sharderConsensous < 1 { - sharderConsensous = DefaultSharderConsensous - } - cfg = c - cfg.SharderConsensous = sharderConsensous - }) -} - -// InitChainNetwork set global chain network for the SDK given its configuration -func InitChainNetwork(n *Network) { - if n == nil { - return - } - - normalizeURLs(n) - - if network == nil { - network = n - return - } - - network.Sharders = n.Sharders - network.Miners = n.Miners -} - -func normalizeURLs(network *Network) { - if network == nil { - return - } - - for i := 0; i < len(network.Miners); i++ { - network.Miners[i] = strings.TrimSuffix(network.Miners[i], "/") - } - - for i := 0; i < len(network.Sharders); i++ { - network.Sharders[i] = strings.TrimSuffix(network.Sharders[i], "/") - } -} diff --git a/core/encryption/hash.go b/core/encryption/hash.go deleted file mode 100644 index 310c9bb2d..000000000 --- a/core/encryption/hash.go +++ /dev/null @@ -1,86 +0,0 @@ -// Provides the data structures and methods used in encryption. -package encryption - -import ( - "crypto/sha1" - "encoding/hex" - - "github.com/minio/sha256-simd" - "golang.org/x/crypto/sha3" -) - -const HASH_LENGTH = 32 - -// HashBytes hash bytes -type HashBytes [HASH_LENGTH]byte - -// 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 -// - data is the data to hash -func RawHash(data interface{}) []byte { - var databuf []byte - switch dataImpl := data.(type) { - case []byte: - databuf = dataImpl - case HashBytes: - databuf = dataImpl[:] - case string: - databuf = []byte(dataImpl) - default: - panic("unknown type") - } - hash := sha3.New256() - hash.Write(databuf) - var buf []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) { - case []byte: - databuf = dataImpl - case HashBytes: - databuf = dataImpl[:] - case string: - databuf = []byte(dataImpl) - default: - panic("unknown type") - } - hash := sha256.New() - _, _ = hash.Write(databuf) - return hash.Sum(nil) -} - -// 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 -// - data is the data to hash -func RawFastHash(data interface{}) []byte { - var databuf []byte - switch dataImpl := data.(type) { - case []byte: - databuf = dataImpl - case HashBytes: - databuf = dataImpl[:] - case string: - databuf = []byte(dataImpl) - default: - panic("unknown type") - } - hash := sha1.New() - hash.Write(databuf) - var buf []byte - return hash.Sum(buf) -} diff --git a/core/imageutil/thumbnailer.go b/core/imageutil/thumbnailer.go deleted file mode 100644 index 4d9dae350..000000000 --- a/core/imageutil/thumbnailer.go +++ /dev/null @@ -1,75 +0,0 @@ -// Provides helper methods and data structures to work with images. -package imageutil - -import ( - "bytes" - "fmt" - "image" - _ "image/gif" - _ "image/jpeg" - "image/png" - _ "image/png" - - _ "golang.org/x/image/bmp" - _ "golang.org/x/image/ccitt" - _ "golang.org/x/image/riff" - _ "golang.org/x/image/tiff" - _ "golang.org/x/image/vector" - _ "golang.org/x/image/vp8" - _ "golang.org/x/image/vp8l" - _ "golang.org/x/image/webp" -) - -type SubImager interface { - SubImage(r image.Rectangle) image.Image -} - -// CreateThumbnail create thumbnail of an image buffer. It supports -// - png -// - jpeg -// - gif -// - bmp -// - ccitt -// - riff -// - tiff -// - vector -// - vp8 -// - vp8l -// - webp -func CreateThumbnail(buf []byte, width, height int) ([]byte, error) { - // image.Decode requires that you import the right image package. - // Ignored return value is image format name. - img, _, err := image.Decode(bytes.NewReader(buf)) - if err != nil { - return nil, err - } - - // I've hard-coded a crop rectangle, start (0,0), end (100, 100). - img, err = cropImage(img, image.Rect(0, 0, width, height)) - if err != nil { - return nil, err - } - - fd := &bytes.Buffer{} - - err = png.Encode(fd, img) - if err != nil { - return nil, err - } - - return fd.Bytes(), nil -} - -// cropImage takes an image and crops it to the specified rectangle. -func cropImage(img image.Image, crop image.Rectangle) (image.Image, error) { - - // img is an Image interface. This checks if the underlying value has a - // method called SubImage. If it does, then we can use SubImage to crop the - // image. - simg, ok := img.(SubImager) - if !ok { - return nil, fmt.Errorf("image does not support cropping") - } - - return simg.SubImage(crop), nil -} diff --git a/core/logger/logger.go b/core/logger/logger.go deleted file mode 100644 index 69b361956..000000000 --- a/core/logger/logger.go +++ /dev/null @@ -1,121 +0,0 @@ -// Provides a simple logger for the SDK. -package logger - -import ( - "fmt" - "io" - "log" - "os" -) - -const ( - NONE = 0 - FATAL = 1 - ERROR = 2 - INFO = 3 - DEBUG = 4 -) - -const cRed = "\u001b[31m" -const cReset = "\u001b[0m" - -const ( - strFATAL = cRed + "[FATAL] " - strERROR = cRed + "[ERROR] " - strINFO = "[INFO] " - strDEBUG = "[DEBUG] " -) - -type Logger struct { - lvl int - prefix string - logDebug *log.Logger - logInfo *log.Logger - logError *log.Logger - logFatal *log.Logger - fWriter io.Writer -} - -// Init - Initialize logging -func (l *Logger) Init(lvl int, prefix string) { - l.SetLevel(lvl) - l.prefix = prefix - l.logDebug = log.New(os.Stderr, prefix+": "+strDEBUG, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) - l.logInfo = log.New(os.Stderr, prefix+": "+strINFO, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) - l.logError = log.New(os.Stderr, prefix+": "+strERROR, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) - l.logFatal = log.New(os.Stderr, prefix+": "+strFATAL, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) -} - -// SetLevel - Configures the log level. Higher the number more verbose. -func (l *Logger) SetLevel(lvl int) { - l.lvl = lvl -} - -// syncPrefixes - syncs the logger prefixes -func syncPrefixes(maxPrefixLen int, loggers []*Logger) { - for _, lgr := range loggers { - if maxPrefixLen-len(lgr.prefix) > 0 { - lgr.prefix = fmt.Sprintf("%-*s", maxPrefixLen, lgr.prefix) - } - } -} - -// SyncLoggers syncs the loggers prefixes -// - loggers is the list of loggers to sync -func SyncLoggers(loggers []*Logger) { - maxPrefixLen := 0 - for _, lgr := range loggers { - if len(lgr.prefix) > maxPrefixLen { - maxPrefixLen = len(lgr.prefix) - } - } - syncPrefixes(maxPrefixLen, loggers) -} - -// SetLogFile - Writes log to the file. set verbose false disables log to os.Stderr -func (l *Logger) SetLogFile(logFile io.Writer, verbose bool) { - dLogs := []io.Writer{logFile} - iLogs := []io.Writer{logFile} - eLogs := []io.Writer{logFile} - fLogs := []io.Writer{logFile} - if verbose { - dLogs = append(dLogs, os.Stderr) - iLogs = append(iLogs, os.Stderr) - eLogs = append(eLogs, os.Stderr) - fLogs = append(fLogs, os.Stderr) - } - l.logDebug = log.New(io.MultiWriter(dLogs...), l.prefix+" "+strDEBUG, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) - l.logInfo = log.New(io.MultiWriter(iLogs...), l.prefix+" "+strINFO, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) - l.logError = log.New(io.MultiWriter(eLogs...), l.prefix+" "+strERROR, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) - l.logFatal = log.New(io.MultiWriter(fLogs...), l.prefix+" "+strFATAL, log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile) -} - -func (l *Logger) Debug(v ...interface{}) { - if l.lvl >= DEBUG { - l.logDebug.Output(2, fmt.Sprint(v...)) - } -} - -func (l *Logger) Info(v ...interface{}) { - if l.lvl >= INFO { - l.logInfo.Output(2, fmt.Sprint(v...)) - } -} - -func (l *Logger) Error(v ...interface{}) { - if l.lvl >= ERROR { - l.logError.Output(2, fmt.Sprint(v...)+cReset) - } -} - -func (l *Logger) Fatal(v ...interface{}) { - if l.lvl >= FATAL { - l.logFatal.Output(2, fmt.Sprint(v...)+cReset) - } -} - -func (l *Logger) Close() { - if c, ok := l.fWriter.(io.Closer); ok && c != nil { - c.Close() - } -} diff --git a/core/node/cache.go b/core/node/cache.go deleted file mode 100644 index 3e19d424d..000000000 --- a/core/node/cache.go +++ /dev/null @@ -1,53 +0,0 @@ -package node - -import ( - "sync" -) - -var Cache *NonceCache -var once sync.Once - -type NonceCache struct { - cache map[string]int64 - guard sync.Mutex - sharders *NodeHolder -} - -func InitCache(sharders *NodeHolder) { - Cache.sharders = sharders -} - -func init() { - once.Do(func() { - Cache = &NonceCache{ - cache: make(map[string]int64), - } - }) -} - -func (nc *NonceCache) GetNextNonce(clientId string) int64 { - nc.guard.Lock() - defer nc.guard.Unlock() - if _, ok := nc.cache[clientId]; !ok { - nonce, _, err := nc.sharders.GetNonceFromSharders(clientId) - if err != nil { - nonce = 0 - } - nc.cache[clientId] = nonce - } - - nc.cache[clientId] += 1 - return nc.cache[clientId] -} - -func (nc *NonceCache) Set(clientId string, nonce int64) { - nc.guard.Lock() - defer nc.guard.Unlock() - nc.cache[clientId] = nonce -} - -func (nc *NonceCache) Evict(clientId string) { - nc.guard.Lock() - defer nc.guard.Unlock() - delete(nc.cache, clientId) -} diff --git a/core/node/node.go b/core/node/node.go deleted file mode 100644 index e5c0e3023..000000000 --- a/core/node/node.go +++ /dev/null @@ -1,443 +0,0 @@ -// Provides functions and data structures to interact with the system nodes in the context of the blockchain network. -package node - -import ( - "context" - "encoding/json" - stdErrors "errors" - "fmt" - "net/http" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/block" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zboxcore/logger" - "github.com/ethereum/go-ethereum/common/math" -) - -const statSize = 20 -const defaultTimeout = 5 * time.Second - -type NodeHolder struct { - consensus int - guard sync.Mutex - stats map[string]*Node - nodes []string -} - -type Node struct { - id string - weight int64 - stats []int -} - -func NewHolder(nodes []string, consensus int) *NodeHolder { - if len(nodes) < consensus { - panic("consensus is not correct") - } - holder := NodeHolder{consensus: consensus, stats: make(map[string]*Node)} - - for _, n := range nodes { - holder.nodes = append(holder.nodes, n) - holder.stats[n] = NewNode(n) - } - return &holder -} - -func NewNode(id string) *Node { - return &Node{ - id: id, - weight: 1, - stats: []int{1}, - } -} - -func (h *NodeHolder) Success(id string) { - h.guard.Lock() - defer h.guard.Unlock() - h.adjustNode(id, 1) -} - -func (h *NodeHolder) Fail(id string) { - h.guard.Lock() - defer h.guard.Unlock() - h.adjustNode(id, -1) -} - -func (h *NodeHolder) adjustNode(id string, res int) { - n := NewNode(id) - nodes := h.nodes - if node, ok := h.stats[id]; ok { - for i, v := range nodes { - if v == id { - nodes = append(nodes[:i], nodes[i+1:]...) - break - } - } - - sourceStats := node.stats - sourceStats = append(sourceStats, res) - if len(sourceStats) > statSize { - sourceStats = sourceStats[1:] - } - node.stats = sourceStats - - w := int64(0) - for i, s := range sourceStats { - w += int64(i+1) * int64(s) - } - node.weight = w - - n = node - } - - i := sort.Search(len(nodes), func(i int) bool { - return h.stats[nodes[i]].weight < n.weight - }) - h.nodes = append(nodes[:i], append([]string{n.id}, nodes[i:]...)...) -} - -func (h *NodeHolder) Healthy() (res []string) { - h.guard.Lock() - defer h.guard.Unlock() - - return h.nodes[:h.consensus] -} - -func (h *NodeHolder) All() (res []string) { - h.guard.Lock() - defer h.guard.Unlock() - - return h.nodes -} - -const consensusThresh = 25 -const ( - GET_BALANCE = `/v1/client/get/balance?client_id=` - CURRENT_ROUND = "/v1/current-round" - GET_BLOCK_INFO = `/v1/block/get?` - GET_HARDFORK_ROUND = `/v1/screst/6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d9/hardfork?name=` -) - -func (h *NodeHolder) GetNonceFromSharders(clientID string) (int64, string, error) { - return h.GetBalanceFieldFromSharders(clientID, "nonce") -} - -func (h *NodeHolder) GetBalanceFieldFromSharders(clientID, name string) (int64, string, error) { - result := make(chan *util.GetResponse) - defer close(result) - // getMinShardersVerify - numSharders := len(h.Healthy()) - h.QueryFromSharders(numSharders, fmt.Sprintf("%v%v", GET_BALANCE, clientID), result) - - consensusMaps := util.NewHttpConsensusMaps(consensusThresh) - - for i := 0; i < numSharders; i++ { - rsp := <-result - if rsp == nil { - logger.Logger.Error("nil response") - continue - } - - logger.Logger.Debug(rsp.Url, rsp.Status) - if rsp.StatusCode != http.StatusOK { - logger.Logger.Error(rsp.Body) - - } else { - logger.Logger.Debug(rsp.Body) - } - - if err := consensusMaps.Add(rsp.StatusCode, rsp.Body); err != nil { - logger.Logger.Error(rsp.Body) - } - } - - rate := consensusMaps.MaxConsensus * 100 / numSharders - if rate < consensusThresh { - if strings.TrimSpace(consensusMaps.WinError) == `{"error":"value not present"}` { - return 0, consensusMaps.WinError, nil - } - return 0, consensusMaps.WinError, errors.New("", "get balance failed. consensus not reached") - } - - winValue, ok := consensusMaps.GetValue(name) - if ok { - winBalance, err := strconv.ParseInt(string(winValue), 10, 64) - if err != nil { - return 0, "", fmt.Errorf("get balance failed. %w", err) - } - - return winBalance, consensusMaps.WinInfo, nil - } - - return 0, consensusMaps.WinInfo, errors.New("", "get balance failed. balance field is missed") -} - -func (h *NodeHolder) QueryFromSharders(numSharders int, query string, - result chan *util.GetResponse) { - - h.QueryFromShardersContext(context.Background(), numSharders, query, result) -} - -func (h *NodeHolder) QueryFromShardersContext(ctx context.Context, numSharders int, - query string, result chan *util.GetResponse) { - - sharders := h.Healthy() - - for _, sharder := range util.Shuffle(sharders)[:numSharders] { - go func(sharderurl string) { - logger.Logger.Info("Query from ", sharderurl+query) - url := fmt.Sprintf("%v%v", sharderurl, query) - timeout, cancelFunc := context.WithTimeout(ctx, defaultTimeout) - defer cancelFunc() - - req, err := util.NewHTTPGetRequestContext(timeout, url) - if err != nil { - logger.Logger.Error(sharderurl, " new get request failed. ", err.Error()) - h.Fail(sharderurl) - result <- nil - return - } - res, err := req.Get() - if err != nil { - logger.Logger.Error(sharderurl, " get error. ", err.Error()) - } - - if res.StatusCode > http.StatusBadRequest { - h.Fail(sharderurl) - } else { - h.Success(sharderurl) - } - - result <- res - }(sharder) - } -} - -func (h *NodeHolder) GetBlockByRound(ctx context.Context, numSharders int, round int64) (b *block.Block, err error) { - - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - numSharders = len(h.Healthy()) // overwrite, use all - h.QueryFromShardersContext(ctx, numSharders, - fmt.Sprintf("%sround=%d&content=full,header", GET_BLOCK_INFO, round), - result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - type respObj struct { - Block *block.Block `json:"block"` - Header *block.Header `json:"header"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logger.Logger.Error("nil response") - continue - } - logger.Logger.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logger.Logger.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logger.Logger.Error("block parse error: ", err) - err = nil - continue - } - - if respo.Block == nil { - logger.Logger.Debug(rsp.Url, "no block in response:", rsp.Body) - continue - } - - if respo.Header == nil { - logger.Logger.Debug(rsp.Url, "no block header in response:", rsp.Body) - continue - } - - if respo.Header.Hash != string(respo.Block.Hash) { - logger.Logger.Debug(rsp.Url, "header and block hash mismatch:", rsp.Body) - continue - } - - b = respo.Block - b.Header = respo.Header - - var h = encryption.FastHash([]byte(b.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "round info not found") - } - - return -} - -func (h *NodeHolder) GetRoundFromSharders() (int64, error) { - - sharders := h.Healthy() - if len(sharders) == 0 { - return 0, stdErrors.New("get round failed. no sharders") - } - - result := make(chan *util.GetResponse, len(sharders)) - - var numSharders = len(sharders) - // use 5 sharders to get round - if numSharders > 5 { - numSharders = 5 - } - - h.QueryFromSharders(numSharders, fmt.Sprintf("%v", CURRENT_ROUND), result) - - const consensusThresh = float32(25.0) - - var rounds []int64 - - consensus := int64(0) - roundMap := make(map[int64]int64) - - round := int64(0) - - waitTimeC := time.After(10 * time.Second) - for i := 0; i < numSharders; i++ { - select { - case <-waitTimeC: - return 0, stdErrors.New("get round failed. consensus not reached") - case rsp := <-result: - if rsp == nil { - logger.Logger.Error("nil response") - continue - } - if rsp.StatusCode != http.StatusOK { - continue - } - - var respRound int64 - err := json.Unmarshal([]byte(rsp.Body), &respRound) - - if err != nil { - continue - } - - rounds = append(rounds, respRound) - - sort.Slice(rounds, func(i, j int) bool { - return false - }) - - medianRound := rounds[len(rounds)/2] - - roundMap[medianRound]++ - - if roundMap[medianRound] > consensus { - - consensus = roundMap[medianRound] - round = medianRound - rate := consensus * 100 / int64(numSharders) - - if rate >= int64(consensusThresh) { - return round, nil - } - } - } - } - - return round, nil -} - -func (h *NodeHolder) GetHardForkRound(hardFork string) (int64, error) { - sharders := h.Healthy() - if len(sharders) == 0 { - return 0, stdErrors.New("get round failed. no sharders") - } - - result := make(chan *util.GetResponse, len(sharders)) - - var numSharders = len(sharders) - // use 5 sharders to get round - if numSharders > 5 { - numSharders = 5 - } - - h.QueryFromSharders(numSharders, fmt.Sprintf("%s%s", GET_HARDFORK_ROUND, hardFork), result) - - const consensusThresh = float32(25.0) - - var rounds []int64 - - consensus := int64(0) - roundMap := make(map[int64]int64) - // If error then set it to max int64 - round := int64(math.MaxInt64) - - waitTimeC := time.After(10 * time.Second) - for i := 0; i < numSharders; i++ { - select { - case <-waitTimeC: - return 0, stdErrors.New("get round failed. consensus not reached") - case rsp := <-result: - if rsp == nil { - logger.Logger.Error("nil response") - continue - } - if rsp.StatusCode != http.StatusOK { - continue - } - - var respRound int64 - var objmap map[string]string - err := json.Unmarshal([]byte(rsp.Body), &objmap) - if err != nil { - continue - } - - str := string(objmap["round"]) - respRound, err = strconv.ParseInt(str, 10, 64) - if err != nil { - continue - } - - rounds = append(rounds, respRound) - - sort.Slice(rounds, func(i, j int) bool { - return false - }) - - medianRound := rounds[len(rounds)/2] - - roundMap[medianRound]++ - - if roundMap[medianRound] > consensus { - - consensus = roundMap[medianRound] - round = medianRound - rate := consensus * 100 / int64(numSharders) - - if rate >= int64(consensusThresh) { - return round, nil - } - } - } - } - - return round, nil -} diff --git a/core/node/node_test.go b/core/node/node_test.go deleted file mode 100644 index e880b5bf9..000000000 --- a/core/node/node_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package node - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNodeHolder_Success(t *testing.T) { - type fields struct { - nodes []string - consensus int - } - type args struct { - id string - } - type res struct { - res []string - } - tests := []struct { - name string - fields fields - args args - res res - }{ - {name: "init", fields: struct { - nodes []string - consensus int - }{nodes: []string{"1", "2", "3", "4", "5"}, consensus: 5}, args: struct{ id string }{id: "1"}, - res: struct{ res []string }{res: []string{"1", "2", "3", "4", "5"}}}, - {name: "pull up", fields: struct { - nodes []string - consensus int - }{nodes: []string{"1", "2", "3", "4", "5"}, consensus: 5}, args: struct{ id string }{id: "5"}, - res: struct{ res []string }{res: []string{"5", "1", "2", "3", "4"}}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h := NewHolder(tt.fields.nodes, tt.fields.consensus) - h.Success(tt.args.id) - - assert.Equal(t, tt.res.res, h.Healthy()) - }) - } -} - -//func TestNodeHolder_GetHardForkRound(t *testing.T) { -// holder := NewHolder([]string{"https://dev2.zus.network/sharder01", -// "https://dev3.zus.network/sharder01", "https://dev1.zus.network/sharder01"}, 2) -// round, err := holder.GetHardForkRound("apollo") -// if err != nil { -// t.Error(err) -// } -// -// assert.Equal(t, 206000, round) -//} diff --git a/core/pathutil/path.go b/core/pathutil/path.go deleted file mode 100644 index 91b36d967..000000000 --- a/core/pathutil/path.go +++ /dev/null @@ -1,64 +0,0 @@ -// Provides utility functions for working with file paths. -package pathutil - -import ( - "strings" -) - -// Split splits path immediately following the final Separator, -// separating it into a directory and file name component. -// 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 "", "" - } - - if path == "/" { - return "/", "" - } - - i := strings.LastIndex(path, "/") - - if i == -1 { - return "", path - } - - return string(path[:i]), string(path[i+1:]) -} - -// 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) - - return dir -} - -// Join joins any number of path elements into a single path, -// separating them with slash. Empty elements are ignored. -// The result is Cleaned. However, if the argument -// list is empty or all its elements are empty, Join returns -// an empty string. -func Join(elem ...string) string { - var items []string - var hasElements bool - for _, e := range elem { - if e != "" { - hasElements = true - for _, it := range strings.Split(e, "/") { - if it != "" { - items = append(items, it) - } - } - } - } - if !hasElements { - return "" - } - - return "/" + strings.Join(items, "/") - -} diff --git a/core/pathutil/path_test.go b/core/pathutil/path_test.go deleted file mode 100644 index 6e9a6e94b..000000000 --- a/core/pathutil/path_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package pathutil - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSplit(t *testing.T) { - - tests := []struct { - name string - path string - dir string - file string - }{ - { - name: "empty", - path: "", - dir: "", - file: "", - }, - { - name: "only file", - path: "file", - dir: "", - file: "file", - }, - { - name: "only dir", - path: "/dir/", - dir: "/dir", - file: "", - }, - { - name: "only root", - path: "/", - dir: "/", - file: "", - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - dir, file := Split(test.path) - require.Equal(t, test.dir, dir) - require.Equal(t, test.file, file) - }) - } -} - -func TestJoin(t *testing.T) { - tests := []struct { - name string - elem []string - path string - }{ - {name: "empty", elem: []string{"", ""}, path: ""}, - {name: "only slash", elem: []string{"/", "/"}, path: "/"}, - {name: "multiple slashes", elem: []string{"/", "/images"}, path: "/images"}, - {name: "one path without slash", elem: []string{"only_path"}, path: "/only_path"}, - {name: "multiple paths without slash", elem: []string{"path1", "path2"}, path: "/path1/path2"}, - {name: "multiple paths", elem: []string{"path1", "path2", "/path3", "path4/"}, path: "/path1/path2/path3/path4"}, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - path := Join(test.elem...) - - require.Equal(t, test.path, path) - }) - } -} diff --git a/core/resty/client.go b/core/resty/client.go deleted file mode 100644 index 784c99f7a..000000000 --- a/core/resty/client.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package resty - -import ( - "net/http" - "time" -) - -// CreateClient a function that create a client instance -var CreateClient = func(t *http.Transport, timeout time.Duration) Client { - client := &http.Client{ - Transport: t, - } - if timeout > 0 { - client.Timeout = timeout - } - - return client -} diff --git a/core/resty/client_wasm.go b/core/resty/client_wasm.go deleted file mode 100644 index 451983933..000000000 --- a/core/resty/client_wasm.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package resty - -import ( - "net/http" - "time" -) - -// CreateClient a function that create a client instance -var CreateClient = func(t *http.Transport, timeout time.Duration) Client { - c := &WasmClient{ - Client: &http.Client{ - Transport: t, - }, - } - - if timeout > 0 { - c.Client.Timeout = timeout - } - - return c -} - -type WasmClient struct { - *http.Client -} - -func (c *WasmClient) Do(req *http.Request) (*http.Response, error) { - req.Header.Set("js.fetch:mode", "cors") - - return c.Client.Do(req) -} diff --git a/core/resty/doc.go b/core/resty/doc.go deleted file mode 100644 index 1f3a8c885..000000000 --- a/core/resty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// HTTP and REST client library with parallel feature. -package resty \ No newline at end of file diff --git a/core/resty/mocks/Client.go b/core/resty/mocks/Client.go deleted file mode 100644 index db64565a0..000000000 --- a/core/resty/mocks/Client.go +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by mockery 2.9.0. DO NOT EDIT. - -package mocks - -import ( - http "net/http" - - mock "github.com/stretchr/testify/mock" -) - -// Client is an autogenerated mock type for the Client type -type Client struct { - mock.Mock -} - -// Do provides a mock function with given fields: req -func (_m *Client) Do(req *http.Request) (*http.Response, error) { - ret := _m.Called(req) - - var r0 *http.Response - if rf, ok := ret.Get(0).(func(*http.Request) *http.Response); ok { - r0 = rf(req) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*http.Response) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*http.Request) error); ok { - r1 = rf(req) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/core/resty/mocks/doc.go b/core/resty/mocks/doc.go deleted file mode 100644 index d5f5048fa..000000000 --- a/core/resty/mocks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// AUTOGENERATED! Do not use. -package mocks \ No newline at end of file diff --git a/core/resty/mocks/timeout.go b/core/resty/mocks/timeout.go deleted file mode 100644 index a14f100a3..000000000 --- a/core/resty/mocks/timeout.go +++ /dev/null @@ -1,21 +0,0 @@ -package mocks - -import ( - "context" - http "net/http" - "time" -) - -// Timeout mock any request with timeout -type Timeout struct { - Timeout time.Duration -} - -// Do provides a mock function with given fields: req -func (t *Timeout) Do(req *http.Request) (*http.Response, error) { - time.Sleep(t.Timeout) - - time.Sleep(1 * time.Second) - - return nil, context.DeadlineExceeded -} diff --git a/core/resty/option.go b/core/resty/option.go deleted file mode 100644 index 2c8b708a0..000000000 --- a/core/resty/option.go +++ /dev/null @@ -1,48 +0,0 @@ -package resty - -import ( - "net/http" -) - -// WithRetry set retry times if request is failure with 5xx status code. retry is ingore if it is less than 1. -func WithRetry(retry int) Option { - return func(r *Resty) { - if retry > 0 { - r.retry = retry - } - } -} - -// WithHeader set header for http request -func WithHeader(header map[string]string) Option { - return func(r *Resty) { - if r.header == nil { - r.header = make(map[string]string) - } - - for k, v := range header { - r.header[k] = v - } - } -} - -// WithRequestInterceptor intercept request -func WithRequestInterceptor(interceptor func(req *http.Request) error) Option { - return func(r *Resty) { - r.requestInterceptor = interceptor - } -} - -// WithTransport set transport -func WithTransport(transport *http.Transport) Option { - return func(r *Resty) { - r.transport = transport - } -} - -// WithClient set client -func WithClient(c Client) Option { - return func(r *Resty) { - r.client = c - } -} diff --git a/core/resty/resty.go b/core/resty/resty.go deleted file mode 100644 index a1442285f..000000000 --- a/core/resty/resty.go +++ /dev/null @@ -1,305 +0,0 @@ -package resty - -import ( - "context" - "io" - "io/ioutil" - "net" - "net/http" - "sync" - "time" - - "github.com/0chain/gosdk_common/core/sys" -) - -func clone(m map[string]string) map[string]string { - cl := make(map[string]string, len(m)) - for k, v := range m { - cl[k] = v - } - - return cl -} - -// New create a Resty instance. -func New(opts ...Option) *Resty { - r := &Resty{ - // Default timeout to use for HTTP requests when either the parent context doesn't have a timeout set - // or the context's timeout is longer than DefaultRequestTimeout. - timeout: DefaultRequestTimeout, - retry: DefaultRetry, - header: clone(DefaultHeader), - } - - for _, option := range opts { - option(r) - } - - if r.transport == nil { - if DefaultTransport == nil { - DefaultTransport = &http.Transport{ - Dial: (&net.Dialer{ - Timeout: DefaultDialTimeout, - }).Dial, - TLSHandshakeTimeout: DefaultDialTimeout, - } - } - r.transport = DefaultTransport - } - - if r.client == nil { - r.client = CreateClient(r.transport, r.timeout) - } - - return r -} - -// Client http client -type Client interface { - Do(req *http.Request) (*http.Response, error) -} - -// Handle handler of http response -type Handle func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error - -// Option set restry option -type Option func(*Resty) - -// Resty HTTP and REST client library with parallel feature -type Resty struct { - ctx context.Context - cancelFunc context.CancelFunc - qty int - done chan Result - - transport *http.Transport - client Client - handle Handle - requestInterceptor func(req *http.Request) error - - timeout time.Duration - retry int - header map[string]string -} - -// Then is used to call the handle function when the request has completed processing -func (r *Resty) Then(fn Handle) *Resty { - if r == nil { - return r - } - r.handle = fn - return r -} - -// DoGet executes http requests with GET method in parallel -func (r *Resty) DoGet(ctx context.Context, urls ...string) *Resty { - return r.Do(ctx, http.MethodGet, nil, urls...) -} - -// DoPost executes http requests with POST method in parallel -func (r *Resty) DoPost(ctx context.Context, body io.Reader, urls ...string) *Resty { - return r.Do(ctx, http.MethodPost, body, urls...) -} - -// DoPut executes http requests with PUT method in parallel -func (r *Resty) DoPut(ctx context.Context, body io.Reader, urls ...string) *Resty { - return r.Do(ctx, http.MethodPut, body, urls...) -} - -// DoDelete executes http requests with DELETE method in parallel -func (r *Resty) DoDelete(ctx context.Context, urls ...string) *Resty { - return r.Do(ctx, http.MethodDelete, nil, urls...) -} - -func (r *Resty) Do(ctx context.Context, method string, body io.Reader, urls ...string) *Resty { - r.ctx, r.cancelFunc = context.WithCancel(ctx) - - r.qty = len(urls) - r.done = make(chan Result, r.qty) - - bodyReader := body - - for _, url := range urls { - go func(url string) { - req, err := http.NewRequest(method, url, bodyReader) - if err != nil { - r.done <- Result{Request: req, Response: nil, Err: err} - return - } - for key, value := range r.header { - req.Header.Set(key, value) - } - // re-use http connection if it is possible - req.Header.Set("Connection", "keep-alive") - - if r.requestInterceptor != nil { - if err := r.requestInterceptor(req); err != nil { - r.done <- Result{Request: req, Response: nil, Err: err} - return - } - } - r.httpDo(req.WithContext(r.ctx)) - }(url) - } - return r -} - -func (r *Resty) httpDo(req *http.Request) { - wg := &sync.WaitGroup{} - wg.Add(1) - - go func(request *http.Request) { - defer wg.Done() - var resp *http.Response - var err error - if r.retry > 0 { - for i := 1; ; i++ { - var bodyCopy io.ReadCloser - if (request.Method == http.MethodPost || request.Method == http.MethodPut) && request.Body != nil { - // clone io.ReadCloser to fix retry issue https://github.com/golang/go/issues/36095 - bodyCopy, _ = request.GetBody() //nolint: errcheck - } - - resp, err = r.client.Do(request) - //success: 200,201,202,204 - if resp != nil && (resp.StatusCode == http.StatusOK || - resp.StatusCode == http.StatusCreated || - resp.StatusCode == http.StatusAccepted || - resp.StatusCode == http.StatusNoContent) { - break - } - // close body ReadClose to release resource before retrying it - if resp != nil && resp.Body != nil { - // don't close it if it is latest retry - if i < r.retry { - resp.Body.Close() - } - } - - if i == r.retry { - break - } - - if resp != nil && resp.StatusCode == http.StatusTooManyRequests { - sys.Sleep(1 * time.Second) - } - - if (request.Method == http.MethodPost || request.Method == http.MethodPut) && request.Body != nil { - request.Body = bodyCopy - } - } - } else { - resp, err = r.client.Do(request.WithContext(r.ctx)) - } - - result := Result{Request: request, Response: resp, Err: err} - if resp != nil { - // read and close body to reuse http connection - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - result.Err = err - } else { - resp.Body.Close() //nolint: errcheck - result.ResponseBody = buf - } - } - r.done <- result - }(req) - wg.Wait() -} - -// Wait waits for all the requests to be completed -func (r *Resty) Wait() []error { - defer func() { - // call cancelFunc, to avoid to memory leaks - if r.cancelFunc != nil { - r.cancelFunc() - } - }() - errs := make([]error, 0, r.qty) - done := 0 - - // no urls - if r.qty == 0 { - return errs - } - for { - select { - case <-r.ctx.Done(): - if r.ctx.Err() == context.DeadlineExceeded { - return []error{r.ctx.Err()} - } - return errs - - case result := <-r.done: - if r.handle != nil { - err := r.handle(result.Request, result.Response, result.ResponseBody, r.cancelFunc, result.Err) - if err != nil { - errs = append(errs, err) - } else if result.Err != nil { - // if r.handle doesn't return any error, then append result.Err if it is not nil - errs = append(errs, result.Err) - } - } else { - if result.Err != nil { - errs = append(errs, result.Err) - } - } - } - done++ - if done >= r.qty { - return errs - } - } -} - -// First successful result or errors -func (r *Resty) First() []error { - defer func() { - // call cancelFunc, avoid to memory leak issue - if r.cancelFunc != nil { - r.cancelFunc() - } - }() - - errs := make([]error, 0, r.qty) - done := 0 - - // no urls - if r.qty == 0 { - return errs - } - - for { - select { - case <-r.ctx.Done(): - return errs - - case result := <-r.done: - - if r.handle != nil { - err := r.handle(result.Request, result.Response, result.ResponseBody, r.cancelFunc, result.Err) - - if err != nil { - errs = append(errs, err) - } else { - return nil - } - } else { - if result.Err != nil { - errs = append(errs, result.Err) - } else { - return nil - } - - } - } - - done++ - - if done >= r.qty { - return errs - } - - } -} diff --git a/core/resty/resty_test.go b/core/resty/resty_test.go deleted file mode 100644 index 6f347cd5b..000000000 --- a/core/resty/resty_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package resty - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "strings" - "testing" - "time" - - "github.com/0chain/gosdk_common/core/resty/mocks" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -func TestResty(t *testing.T) { - - tests := []struct { - name string - urls []string - - statusCode int - expectedErr error - setup func(a *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) - }{ - { - name: "Test_Resty_Cancel_With_Timeout", - expectedErr: context.DeadlineExceeded, - urls: []string{"Test_Resty_Timeout_1", "Test_Resty_Timeout_2", "Test_Resty_Timeout_3"}, - setup: getSetupFuncForCtxDeadlineExtendedTest(), - }, - { - name: "Test_Resty_All_Success", - statusCode: 200, - expectedErr: nil, - urls: []string{"http://Test_Resty_Success_1", "http://Test_Resty_Success_2"}, - setup: getSetupFuncForAllSuccessTest(), - }, - { - name: "Test_Resty_Failed_Due_To_Handler_Failing", - expectedErr: fmt.Errorf("handler returned error"), - urls: []string{"http://Test_Resty_Failure_1", "http://Test_Resty_Failure_2"}, - setup: getSetupFuncForHandlerErrorTest(), - }, - { - name: "Test_Resty_Failed_Due_To_Interceptor_Error", - expectedErr: fmt.Errorf("interceptor returned with error"), - urls: []string{"http://Test_Resty_Failure_1", "http://Test_Resty_Failure_2"}, - setup: getSetupFuncForInterceptorErrorTest(), - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := require.New(t) - ctx, resty := tt.setup(r, tt.name, tt.statusCode, tt.urls) - resty.DoGet(ctx, tt.urls...) - errs := resty.Wait() - if tt.expectedErr != nil && tt.expectedErr != context.DeadlineExceeded && len(errs) == 0 { - t.Fatalf("expected err: %v, got: %v", tt.expectedErr, errs) - } - for _, err := range errs { - // test it by predefined error variable instead of error message - if tt.expectedErr != nil { - r.Errorf(err, tt.expectedErr.Error()) - } else { - r.Equal(nil, err) - } - } - }) - } -} - -func getSetupFuncForCtxDeadlineExtendedTest() func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - return func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - r := New() - r.client = &mocks.Timeout{ - Timeout: 1 * time.Second, - } - ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second) - go func() { - <-ctx.Done() - cancel() - }() - return ctx, r - } -} - -func getSetupFuncForAllSuccessTest() func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - return func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - resty := New().Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - ra.Equal(200, resp.StatusCode) - ra.Equal(nil, err) - ra.Equal(name, string(respBody)) - return nil - }) - - client := &mocks.Client{} - setupMockClient(client, urls, statusCode, name) - resty.client = client - - ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second) - go func() { - <-ctx.Done() - cancel() - }() - return context.TODO(), resty - } -} - -func getSetupFuncForHandlerErrorTest() func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - return func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - resty := New().Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - return fmt.Errorf("handler returned error") - }) - - client := &mocks.Client{} - setupMockClient(client, urls, statusCode, name) - resty.client = client - - ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second) - go func() { - <-ctx.Done() - cancel() - }() - return context.TODO(), resty - } -} - -func getSetupFuncForInterceptorErrorTest() func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - return func(ra *require.Assertions, name string, statusCode int, urls []string) (context.Context, *Resty) { - opts := make([]Option, 0) - opts = append(opts, WithRequestInterceptor(func(r *http.Request) error { - return fmt.Errorf("interceptor returned with error") //nolint - })) - // create a resty object with an interceptor which returns an error, but the handler doesn't return any error - resty := New(opts...).Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - return nil - }) - - client := &mocks.Client{} - setupMockClient(client, urls, statusCode, name) - resty.client = client - - ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second) - go func() { - <-ctx.Done() - cancel() - }() - return context.TODO(), resty - } -} - -func setupMockClient(mck *mocks.Client, urls []string, statusCode int, name string) { - for _, url := range urls { - func(u string) { - mck.On("Do", mock.MatchedBy(func(r *http.Request) bool { - return r.URL.String() == u - })).Return(&http.Response{ - StatusCode: statusCode, - Body: ioutil.NopCloser(strings.NewReader(name)), - }, nil) - }(url) - } -} diff --git a/core/resty/result.go b/core/resty/result.go deleted file mode 100644 index b86e7f2a0..000000000 --- a/core/resty/result.go +++ /dev/null @@ -1,11 +0,0 @@ -package resty - -import "net/http" - -// Result result of a http request -type Result struct { - Request *http.Request - Response *http.Response - ResponseBody []byte - Err error -} diff --git a/core/resty/transport.go b/core/resty/transport.go deleted file mode 100644 index 941e0e649..000000000 --- a/core/resty/transport.go +++ /dev/null @@ -1,29 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package resty - -import ( - "net" - "net/http" - "time" -) - -var DefaultHeader = make(map[string]string) - -// Run the HTTP request in a goroutine and pass the response to f. -var DefaultTransport = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - MaxIdleConns: 1000, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: 5, - ForceAttemptHTTP2: true, - - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, -} diff --git a/core/resty/transport_wasm.go b/core/resty/transport_wasm.go deleted file mode 100644 index 2896166a0..000000000 --- a/core/resty/transport_wasm.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package resty - -import ( - "net/http" - "time" -) - -var DefaultHeader map[string]string - -// Run the HTTP request in a goroutine and pass the response to f. -var DefaultTransport = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - MaxIdleConns: 1000, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: 5, - ForceAttemptHTTP2: true, -} - -func init() { - DefaultHeader = make(map[string]string) - DefaultHeader["js.fetch:mode"] = "cors" -} diff --git a/core/resty/vars.go b/core/resty/vars.go deleted file mode 100644 index 5204c5025..000000000 --- a/core/resty/vars.go +++ /dev/null @@ -1,14 +0,0 @@ -package resty - -import ( - "time" -) - -var ( - // DefaultDialTimeout default timeout of a dialer - DefaultDialTimeout = 5 * time.Second - // DefaultRequestTimeout default time out of a http request - DefaultRequestTimeout = 10 * time.Second - // DefaultRetry retry times if a request is failed with 5xx status code - DefaultRetry = 3 -) diff --git a/core/sys/doc.go b/core/sys/doc.go deleted file mode 100644 index 5fc9edc91..000000000 --- a/core/sys/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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/fs.go b/core/sys/fs.go deleted file mode 100644 index b2b77c2d8..000000000 --- a/core/sys/fs.go +++ /dev/null @@ -1,63 +0,0 @@ -package sys - -import ( - "io/fs" - "os" -) - -// FS An FS provides access to a hierarchical file system. -type FS interface { - - // Open opens the named file for reading. If successful, methods on - // the returned file can be used for reading; the associated file - // descriptor has mode O_RDONLY. - // If there is an error, it will be of type *PathError. - Open(name string) (File, error) - - // OpenFile open a file - OpenFile(name string, flag int, perm os.FileMode) (File, error) - - // ReadFile reads the file named by filename and returns the contents. - ReadFile(name string) ([]byte, error) - - // WriteFile writes data to a file named by filename. - WriteFile(name string, data []byte, perm fs.FileMode) error - - Stat(name string) (fs.FileInfo, error) - - // Remove removes the named file or (empty) directory. - // If there is an error, it will be of type *PathError. - Remove(name string) error - - //MkdirAll creates a directory named path - MkdirAll(path string, perm os.FileMode) error - - // LoadProgress load progress - LoadProgress(progressID string) ([]byte, error) - - // SaveProgress save progress - SaveProgress(progressID string, data []byte, perm fs.FileMode) error - - // RemoveProgress remove progress - RemoveProgress(progressID string) error - - // Create Directory - CreateDirectory(dirID string) error - - // GetFileHandler - GetFileHandler(dirID, name string) (File, error) - - // Remove all created directories(used in download directory) - RemoveAllDirectories() -} - -type File interface { - Stat() (fs.FileInfo, error) - Read([]byte) (int, error) - Write(p []byte) (n int, err error) - - Sync() error - Seek(offset int64, whence int) (ret int64, err error) - - Close() error -} diff --git a/core/sys/fs_disk.go b/core/sys/fs_disk.go deleted file mode 100644 index 338d47f90..000000000 --- a/core/sys/fs_disk.go +++ /dev/null @@ -1,90 +0,0 @@ -package sys - -import ( - "io/fs" - "os" - "path/filepath" -) - -// DiskFS implement file system on disk -type DiskFS struct { -} - -// NewDiskFS create DiskFS instance -func NewDiskFS() FS { - return &DiskFS{} -} - -// Open opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func (dfs *DiskFS) Open(name string) (File, error) { - return dfs.OpenFile(name, os.O_RDONLY, 0) -} - -func (dfs *DiskFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - dir := filepath.Dir(name) - if _, err := os.Stat(dir); os.IsNotExist(err) { - if err := os.MkdirAll(dir, 0744); err != nil { - return nil, err - } - } - return os.OpenFile(name, flag, perm) -} - -// ReadFile reads the file named by filename and returns the contents. -func (dfs *DiskFS) ReadFile(name string) ([]byte, error) { - return os.ReadFile(name) -} - -// WriteFile writes data to a file named by filename. -func (dfs *DiskFS) WriteFile(name string, data []byte, perm os.FileMode) error { - return os.WriteFile(name, data, perm) -} - -// Remove removes the named file or (empty) directory. -// If there is an error, it will be of type *PathError. -func (dfs *DiskFS) Remove(name string) error { - return os.Remove(name) -} - -// MkdirAll creates a directory named path -func (dfs *DiskFS) MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} - -// Stat returns a FileInfo describing the named file. -// If there is an error, it will be of type *PathError. -func (dfs *DiskFS) Stat(name string) (fs.FileInfo, error) { - return os.Stat(name) -} - -func (dfs *DiskFS) LoadProgress(progressID string) ([]byte, error) { - return dfs.ReadFile(progressID) -} - -func (dfs *DiskFS) SaveProgress(progressID string, data []byte, perm fs.FileMode) error { - return dfs.WriteFile(progressID, data, perm) -} - -func (dfs *DiskFS) RemoveProgress(progressID string) error { - return dfs.Remove(progressID) -} - -func (dfs *DiskFS) CreateDirectory(_ string) error { - return nil -} - -func (dfs *DiskFS) GetFileHandler(_, name string) (File, error) { - dir := filepath.Dir(name) - if _, err := os.Stat(dir); os.IsNotExist(err) { - if err := os.MkdirAll(dir, 0744); err != nil { - return nil, err - } - } - return os.OpenFile(name, os.O_CREATE|os.O_WRONLY, 0644) -} - -func (dfs *DiskFS) RemoveAllDirectories() { -} diff --git a/core/sys/fs_mem.go b/core/sys/fs_mem.go deleted file mode 100644 index d3a458f06..000000000 --- a/core/sys/fs_mem.go +++ /dev/null @@ -1,217 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package sys - -import ( - "errors" - "io/fs" - "os" - "path/filepath" - "strings" - "sync" - "syscall/js" - "time" - - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/valyala/bytebufferpool" -) - -// MemFS implement file system on memory -type MemFS struct { - files map[string]*MemFile - dirs map[string]js.Value - sync.Mutex -} - -// NewMemFS create MemFS instance -func NewMemFS() FS { - return &MemFS{ - files: make(map[string]*MemFile), - dirs: make(map[string]js.Value), - } -} - -// Open opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func (mfs *MemFS) Open(name string) (File, error) { - mfs.Lock() - defer mfs.Unlock() - file := mfs.files[name] - if file != nil { - return file, nil - } - - fileName := filepath.Base(name) - - file = &MemFile{Name: fileName, Mode: fs.ModePerm, ModTime: time.Now()} - - mfs.files[name] = file - - return file, nil -} - -func (mfs *MemFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - mfs.Lock() - defer mfs.Unlock() - file := mfs.files[name] - if file != nil { - return file, nil - } - - fileName := filepath.Base(name) - file = &MemFile{Name: fileName, Mode: perm, ModTime: time.Now()} - - mfs.files[name] = file - - return file, nil - -} - -// ReadFile reads the file named by filename and returns the contents. -func (mfs *MemFS) ReadFile(name string) ([]byte, error) { - mfs.Lock() - defer mfs.Unlock() - file, ok := mfs.files[name] - if ok { - return file.Buffer, nil - } - - return nil, os.ErrNotExist -} - -// WriteFile writes data to a file named by filename. -func (mfs *MemFS) WriteFile(name string, data []byte, perm os.FileMode) error { - fileName := filepath.Base(name) - file := &MemFile{Name: fileName, Mode: perm, ModTime: time.Now()} - mfs.Lock() - defer mfs.Unlock() - mfs.files[name] = file - - return nil -} - -// Remove removes the named file or (empty) directory. -// If there is an error, it will be of type *PathError. -func (mfs *MemFS) Remove(name string) error { - mfs.Lock() - defer mfs.Unlock() - f, ok := mfs.files[name] - if ok { - b := f.Buffer - if len(b) > 0 { - buff := &bytebufferpool.ByteBuffer{ - B: b, - } - common.MemPool.Put(buff) - } - } - delete(mfs.files, name) - return nil -} - -// MkdirAll creates a directory named path -func (mfs *MemFS) MkdirAll(path string, perm os.FileMode) error { - return nil -} - -// Stat returns a FileInfo describing the named file. -// If there is an error, it will be of type *PathError. -func (mfs *MemFS) Stat(name string) (fs.FileInfo, error) { - mfs.Lock() - defer mfs.Unlock() - file, ok := mfs.files[name] - if ok { - return file.Stat() - } - - return nil, os.ErrNotExist -} - -func (mfs *MemFS) LoadProgress(progressID string) ([]byte, error) { - key := filepath.Base(progressID) - val := js.Global().Get("localStorage").Call("getItem", key) - if val.Truthy() { - return []byte(val.String()), nil - } - return nil, os.ErrNotExist -} - -func (mfs *MemFS) SaveProgress(progressID string, data []byte, _ fs.FileMode) error { - key := filepath.Base(progressID) - js.Global().Get("localStorage").Call("setItem", key, string(data)) - return nil -} - -func (mfs *MemFS) RemoveProgress(progressID string) error { - key := filepath.Base(progressID) - js.Global().Get("localStorage").Call("removeItem", key) - return nil -} - -func (mfs *MemFS) CreateDirectory(dirID string) error { - if !js.Global().Get("showDirectoryPicker").Truthy() || !js.Global().Get("WritableStream").Truthy() { - return errors.New("dir_picker: not supported") - } - showDirectoryPicker := js.Global().Get("showDirectoryPicker") - dirHandle, err := jsbridge.Await(showDirectoryPicker.Invoke()) - if len(err) > 0 && !err[0].IsNull() { - return errors.New("dir_picker: " + err[0].String()) - } - mfs.dirs[dirID] = dirHandle[0] - return nil -} - -func (mfs *MemFS) GetFileHandler(dirID, path string) (File, error) { - dirHandler, ok := mfs.dirs[dirID] - if !ok { - return nil, errors.New("dir_picker: directory not found") - } - currHandler, err := mfs.mkdir(dirHandler, filepath.Dir(path)) - if err != nil { - return nil, err - } - return jsbridge.NewFileWriterFromHandle(currHandler, filepath.Base(path)) -} - -func (mfs *MemFS) RemoveAllDirectories() { - for k := range mfs.dirs { - delete(mfs.dirs, k) - } -} - -func (mfs *MemFS) mkdir(dirHandler js.Value, dirPath string) (js.Value, error) { - if dirPath == "/" { - return dirHandler, nil - } - currHandler, ok := mfs.dirs[dirPath] - if !ok { - currHandler = dirHandler - paths := strings.Split(dirPath, "/") - paths = paths[1:] - currPath := "/" - for _, path := range paths { - currPath = filepath.Join(currPath, path) - handler, ok := mfs.dirs[currPath] - if ok { - currHandler = handler - continue - } - options := js.Global().Get("Object").New() - options.Set("create", true) - currHandlers, err := jsbridge.Await(currHandler.Call("getDirectoryHandle", path, options)) - if len(err) > 0 && !err[0].IsNull() { - return js.Value{}, errors.New("dir_picker: " + err[0].String()) - } - currHandler = currHandlers[0] - mfs.dirs[currPath] = currHandler - } - if !currHandler.Truthy() { - return js.Value{}, errors.New("dir_picker: failed to create directory") - } - } - return currHandler, nil -} diff --git a/core/sys/sign.go b/core/sys/sign.go deleted file mode 100644 index 37ac18479..000000000 --- a/core/sys/sign.go +++ /dev/null @@ -1,16 +0,0 @@ -package sys - -// KeyPair private and publickey -type KeyPair struct { - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` -} - -// SignFunc sign method for request verification -type SignFunc func(hash string, signatureScheme string, keys []KeyPair) (string, error) - -type VerifyFunc func(signature string, msg string) (bool, error) - -type VerifyWithFunc func(pk, signature string, msg string) (bool, error) - -type AuthorizeFunc func(msg string) (string, error) diff --git a/core/sys/util.go b/core/sys/util.go deleted file mode 100644 index 8810406f2..000000000 --- a/core/sys/util.go +++ /dev/null @@ -1,272 +0,0 @@ -package sys - -import ( - "bytes" - "io" - "io/fs" - "os" - "time" - - "github.com/0chain/gosdk_common/core/common" - "github.com/valyala/bytebufferpool" -) - -// 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 - Mode fs.FileMode // FileInfo.Mode - ModTime time.Time // FileInfo.ModTime - Sys interface{} // FileInfo.Sys - 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) - } - 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 - } - - copy(f.Buffer[offset:], p) - - return len(p), nil -} - -// InitBuffer initializes the buffer with a specific size -func (f *MemFile) InitBuffer(size int) { - buff := common.MemPool.Get() - if cap(buff.B) < size { - buff.B = make([]byte, size) - } - f.Buffer = buff.B[:size] -} - -// Sync not implemented -func (f *MemFile) Sync() error { - return nil -} -func (f *MemFile) Seek(offset int64, whence int) (ret int64, err error) { - - if whence != io.SeekStart { - return 0, os.ErrInvalid - } - switch { - case offset < 0: - return 0, os.ErrInvalid - case offset > int64(len(f.Buffer)): - return 0, io.EOF - default: - f.reader = bytes.NewReader(f.Buffer[offset:]) - return offset, nil - } -} - -func (f *MemFile) Close() error { - f.reader = nil - 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 - Mode fs.FileMode // FileInfo.Mode - ModTime time.Time // FileInfo.ModTime - ChunkWriteSize int // 0 value means no limit - Sys interface{} // FileInfo.Sys - ErrChan chan error - 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: - return 0, err - case recieveData, ok := <-f.Buffer: - if !ok { - return 0, io.EOF - } - if len(recieveData) > len(p) { - return 0, io.ErrShortBuffer - } - n := copy(p, recieveData) - return n, nil - } -} - -// 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)) - copy(data, p) - f.Buffer <- data - } else { - if cap(f.data) == 0 { - bbuf := common.MemPool.Get() - if cap(bbuf.B) < len(p) { - bbuf.B = make([]byte, 0, len(p)) - } - f.data = bbuf.B - } - f.data = append(f.data, p...) - } - 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 { - end := current + f.ChunkWriteSize - if end > len(f.data) { - end = len(f.data) - } - f.Buffer <- f.data[current:end] - } - f.data = f.data[:0] - 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) - if cap(f.data) > 0 { - bbuf := &bytebufferpool.ByteBuffer{ - B: f.data, - } - common.MemPool.Put(bbuf) - } - 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/sys/vars.go b/core/sys/vars.go deleted file mode 100644 index b1b53876e..000000000 --- a/core/sys/vars.go +++ /dev/null @@ -1,38 +0,0 @@ -// Package sys provides platform-independent interfaces to support webassembly runtime -package sys - -import ( - "time" -) - -var ( - //Files file system implementation on sdk. DiskFS doesn't work on webassembly. it should be initialized with common.NewMemFS() - Files FS = NewDiskFS() - - //Sleep pauses the current goroutine for at least the duration. - // time.Sleep will stop webassembly main thread. it should be bridged to javascript method on webassembly sdk - Sleep = time.Sleep - - // Sign sign method. it should be initialized on different platform. - Sign SignFunc - SignWithAuth SignFunc - - // Verify verify method. it should be initialized on different platform. - Verify VerifyFunc - - // Verify verify method. it should be initialized on different platform. - VerifyWith VerifyWithFunc - - Authorize AuthorizeFunc - - AuthCommon AuthorizeFunc -) - -// SetAuthorize sets the authorize callback function -func SetAuthorize(auth AuthorizeFunc) { - Authorize = auth -} - -func SetAuthCommon(auth AuthorizeFunc) { - AuthCommon = auth -} diff --git a/core/tokenrate/bancor.go b/core/tokenrate/bancor.go deleted file mode 100644 index 8a49bce90..000000000 --- a/core/tokenrate/bancor.go +++ /dev/null @@ -1,143 +0,0 @@ -package tokenrate - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "strconv" - "strings" - - "github.com/0chain/gosdk_common/core/resty" -) - -type bancorQuoteQuery struct { -} - -func (qq *bancorQuoteQuery) getUSD(ctx context.Context, symbol string) (float64, error) { - - var result bancorResponse - - s := strings.ToLower(symbol) - var dltId string - // - switch s { - case "zcn": - dltId = "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78" - case "eth": - dltId = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" - default: - evnName := "BANCOR_DLTID_" + strings.ToUpper(symbol) - id, ok := os.LookupEnv(evnName) - if !ok { - return 0, errors.New("bancor: please configure dlt_id on environment variable [" + evnName + "] first") - } - dltId = id - } - - r := resty.New() - r.DoGet(ctx, "https://api-v3.bancor.network/tokens?dlt_id="+dltId). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - - if err != nil { - return err - } - - if resp.StatusCode != http.StatusOK { - return errors.New("bancor: " + strconv.Itoa(resp.StatusCode) + resp.Status) - } - - err = json.Unmarshal(respBody, &result) - if err != nil { - return err - } - - result.Raw = string(respBody) - - return nil - - }) - - errs := r.Wait() - if len(errs) > 0 { - return 0, errs[0] - } - - rate, ok := result.Data.Rate24hAgo["usd"] - - if ok { - - if rate.Value > 0 { - return rate.Value, nil - } - - //rate24ago is invalid, try get current rate - rate, ok = result.Data.Rate["usd"] - if ok && rate.Value > 0 { - return rate.Value, nil - } - } - - return 0, fmt.Errorf("bancor: %s price is not provided on bancor apis", symbol) -} - -// { -// "data": { -// "dltId": "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78", -// "symbol": "ZCN", -// "decimals": 10, -// "rate": { -// "bnt": "0.271257342312491431", -// "usd": "0.118837", -// "eur": "0.121062", -// "eth": "0.000089243665620809" -// }, -// "rate24hAgo": { -// "bnt": "0.273260935543748855", -// "usd": "0.120972", -// "eur": "0.126301", -// "eth": "0.000094001761827049" -// } -// }, -// "timestamp": { -// "ethereum": { -// "block": 15644407, -// "timestamp": 1664519843 -// } -// } -// } - -type bancorResponse struct { - Data bancorMarketData `json:"data"` - Raw string `json:"-"` -} - -type bancorMarketData struct { - Rate map[string]Float64 `json:"rate"` - Rate24hAgo map[string]Float64 `json:"rate24hAgo"` -} - -type Float64 struct { - Value float64 -} - -func (s *Float64) UnmarshalJSON(data []byte) error { - - if data == nil { - s.Value = 0 - return nil - } - - js := strings.Trim(string(data), "\"") - - v, err := strconv.ParseFloat(js, 64) - if err != nil { - return err - } - - s.Value = v - return nil - -} diff --git a/core/tokenrate/bancor_test.go b/core/tokenrate/bancor_test.go deleted file mode 100644 index 94a9899f2..000000000 --- a/core/tokenrate/bancor_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package tokenrate - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestBancorJson(t *testing.T) { - js := ` { - "data": { - "dltId": "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78", - "symbol": "ZCN", - "decimals": 10, - "rate": { - "bnt": "0.271257342312491431", - "usd": "0.118837", - "eur": "0.121062", - "eth": "0.000089243665620809" - }, - "rate24hAgo": { - "bnt": "0.273260935543748855", - "usd": "0.120972", - "eur": "0.126301", - "eth": "0.000094001761827049" - } - }, - "timestamp": { - "ethereum": { - "block": 15644407, - "timestamp": 1664519843 - } - } - }` - bs := &bancorResponse{} - - err := json.Unmarshal([]byte(js), bs) - require.Nil(t, err) - - require.Equal(t, 0.118837, bs.Data.Rate["usd"].Value) - require.Equal(t, 0.120972, bs.Data.Rate24hAgo["usd"].Value) - -} diff --git a/core/tokenrate/coingecko.go b/core/tokenrate/coingecko.go deleted file mode 100644 index 24c6f765f..000000000 --- a/core/tokenrate/coingecko.go +++ /dev/null @@ -1,83 +0,0 @@ -package tokenrate - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - - "github.com/0chain/gosdk_common/core/resty" -) - -type coingeckoQuoteQuery struct { -} - -func (qq *coingeckoQuoteQuery) getUSD(ctx context.Context, symbol string) (float64, error) { - - var result coingeckoResponse - - r := resty.New() - r.DoGet(ctx, "https://zcnprices.zus.network/market"). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - - if err != nil { - return err - } - - if resp.StatusCode != http.StatusOK { - return errors.New("market API: " + strconv.Itoa(resp.StatusCode) + resp.Status) - } - - err = json.Unmarshal(respBody, &result) - if err != nil { - return err - } - result.Raw = string(respBody) - - return nil - - }) - - errs := r.Wait() - if len(errs) > 0 { - return 0, errs[0] - } - - var rate float64 - - h, ok := result.MarketData.High24h["usd"] - if ok { - l, ok := result.MarketData.Low24h["usd"] - if ok { - rate = (h + l) / 2 - if rate > 0 { - return rate, nil - } - } - } - - rate, ok = result.MarketData.CurrentPrice["usd"] - - if ok { - if rate > 0 { - return rate, nil - } - - return 0, fmt.Errorf("market API: invalid response %s", result.Raw) - } - - return 0, fmt.Errorf("market API: %s price is not provided on internal https://zcnprices.zus.network/market api", symbol) -} - -type coingeckoResponse struct { - MarketData coingeckoMarketData `json:"market_data"` - Raw string `json:"-"` -} - -type coingeckoMarketData struct { - CurrentPrice map[string]float64 `json:"current_price"` - High24h map[string]float64 `json:"high_24h"` - Low24h map[string]float64 `json:"low_24h"` -} diff --git a/core/tokenrate/coinmarketcap.go b/core/tokenrate/coinmarketcap.go deleted file mode 100644 index 311f47853..000000000 --- a/core/tokenrate/coinmarketcap.go +++ /dev/null @@ -1,186 +0,0 @@ -package tokenrate - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "strconv" - "strings" - - "github.com/0chain/gosdk_common/core/resty" -) - -type coinmarketcapQuoteQuery struct { - APIKey string -} - -// js call is unsupported for coinmarketcap api due to core issue -// https://coinmarketcap.com/api/documentation/v1/#section/Quick-Start-Guide -// Note: Making HTTP requests on the client side with Javascript is currently prohibited through CORS configuration. This is to protect your API Key which should not be visible to users of your application so your API Key is not stolen. Secure your API Key by routing calls through your own backend service. -func createCoinmarketcapQuoteQuery() quoteQuery { - - coinmarketcapAPIKEY, ok := os.LookupEnv("COINMARKETCAP_API_KEY") - if !ok { - coinmarketcapAPIKEY = "7e386213-56ef-4a7e-af17-806496c20d3b" - } - - return &coinmarketcapQuoteQuery{ - APIKey: coinmarketcapAPIKEY, - } -} - -func (qq *coinmarketcapQuoteQuery) getUSD(ctx context.Context, symbol string) (float64, error) { - - var result coinmarketcapResponse - - r := resty.New(resty.WithHeader(map[string]string{ - "X-CMC_PRO_API_KEY": qq.APIKey, - })) - - s := strings.ToUpper(symbol) - - r.DoGet(ctx, "https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol="+s). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return errors.New("coinmarketcap: " + strconv.Itoa(resp.StatusCode) + resp.Status) - } - - err = json.Unmarshal(respBody, &result) - if err != nil { - return err - } - - result.Raw = string(respBody) - - return nil - - }) - - errs := r.Wait() - if len(errs) > 0 { - return 0, errs[0] - } - - zcn, ok := result.Data[s] - - if !ok || len(zcn) == 0 { - return 0, errors.New("coinmarketcap: " + symbol + " is not provided on coinmarketcap apis") - } - - rate, ok := zcn[0].Quote["USD"] - if ok { - if rate.Price > 0 { - return rate.Price, nil - } - - return 0, fmt.Errorf("coinmarketcap: invalid response %s", result.Raw) - } - - return 0, errors.New("coinmarketcap: " + symbol + " to USD quote is not provided on coinmarketcap apis") -} - -// { -// "status": { -// "timestamp": "2022-06-03T02:18:34.093Z", -// "error_code": 0, -// "error_message": null, -// "elapsed": 50, -// "credit_count": 1, -// "notice": null -// }, -// "data": { -// "ZCN": [ -// { -// "id": 2882, -// "name": "0Chain", -// "symbol": "ZCN", -// "slug": "0chain", -// "num_market_pairs": 8, -// "date_added": "2018-07-02T00:00:00.000Z", -// "tags": [ -// { -// "slug": "platform", -// "name": "Platform", -// "category": "PROPERTY" -// }, -// { -// "slug": "ai-big-data", -// "name": "AI & Big Data", -// "category": "PROPERTY" -// }, -// { -// "slug": "distributed-computing", -// "name": "Distributed Computing", -// "category": "PROPERTY" -// }, -// { -// "slug": "filesharing", -// "name": "Filesharing", -// "category": "PROPERTY" -// }, -// { -// "slug": "iot", -// "name": "IoT", -// "category": "PROPERTY" -// }, -// { -// "slug": "storage", -// "name": "Storage", -// "category": "PROPERTY" -// } -// ], -// "max_supply": 400000000, -// "circulating_supply": 48400982, -// "total_supply": 200000000, -// "platform": { -// "id": 1027, -// "name": "Ethereum", -// "symbol": "ETH", -// "slug": "ethereum", -// "token_address": "0xb9ef770b6a5e12e45983c5d80545258aa38f3b78" -// }, -// "is_active": 1, -// "cmc_rank": 782, -// "is_fiat": 0, -// "self_reported_circulating_supply": 115000000, -// "self_reported_market_cap": 25409234.858036295, -// "last_updated": "2022-06-03T02:17:00.000Z", -// "quote": { -// "USD": { -// "price": 0.2209498683307504, -// "volume_24h": 28807.79174117, -// "volume_change_24h": -78.341, -// "percent_change_1h": 0.09600341, -// "percent_change_24h": 0.1834049, -// "percent_change_7d": 24.08736297, -// "percent_change_30d": -43.56084388, -// "percent_change_60d": -63.69787917, -// "percent_change_90d": -27.17695342, -// "market_cap": 10694190.59997902, -// "market_cap_dominance": 0.0008, -// "fully_diluted_market_cap": 88379947.33, -// "last_updated": "2022-06-03T02:17:00.000Z" -// } -// } -// } -// ] -// } -// } -type coinmarketcapResponse struct { - Data map[string][]coinmarketcapCurrency `json:"data"` - Raw string `json:"-"` -} - -type coinmarketcapCurrency struct { - Quote map[string]coinmarketcapQuote `json:"quote"` -} - -type coinmarketcapQuote struct { - Price float64 `json:"price"` -} diff --git a/core/tokenrate/doc.go b/core/tokenrate/doc.go deleted file mode 100644 index c268146ea..000000000 --- a/core/tokenrate/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Provides functions to get token rates from different sources (for example: CoinGecko, Bancor, Uniswap, CoinMarketCap). -package tokenrate diff --git a/core/tokenrate/mockresponses/bancor.json b/core/tokenrate/mockresponses/bancor.json deleted file mode 100644 index 5532d34ea..000000000 --- a/core/tokenrate/mockresponses/bancor.json +++ /dev/null @@ -1,25 +0,0 @@ -{ -"data": { - "dltId": "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78", - "symbol": "ZCN", - "decimals": 10, - "rate": { - "bnt": "0.271257342312491431", - "usd": "0.118837", - "eur": "0.121062", - "eth": "0.000089243665620809" - }, - "rate24hAgo": { - "bnt": "0.273260935543748855", - "usd": "0.120972", - "eur": "0.126301", - "eth": "0.000094001761827049" - } -}, -"timestamp": { - "ethereum": { - "block": 15644407, - "timestamp": 1664519843 - } -} -} \ No newline at end of file diff --git a/core/tokenrate/mockresponses/coingecko.json b/core/tokenrate/mockresponses/coingecko.json deleted file mode 100644 index 0afee7141..000000000 --- a/core/tokenrate/mockresponses/coingecko.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "id": "0chain", - "symbol": "zcn", - "name": "Zus", - "asset_platform_id": "ethereum", - "market_data": { - "current_price": { - "aed": 0.801944, - "ars": 42.97, - "usd": 0.218343 - }, - "high_24h": { - "aed": 0.813634, - "ars": 43.39 - }, - "low_24h": { - "aed": 0.770675, - "ars": 41.13 - } - } -} \ No newline at end of file diff --git a/core/tokenrate/mockresponses/coinmarketcap.json b/core/tokenrate/mockresponses/coinmarketcap.json deleted file mode 100644 index 5a2d8996d..000000000 --- a/core/tokenrate/mockresponses/coinmarketcap.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "status": { - "timestamp": "2022-06-03T02:18:34.093Z", - "error_code": 0, - "error_message": null, - "elapsed": 50, - "credit_count": 1, - "notice": null - }, - "data": { - "ZCN": [ - { - "id": 2882, - "name": "0Chain", - "symbol": "ZCN", - "slug": "0chain", - "num_market_pairs": 8, - "date_added": "2018-07-02T00:00:00.000Z", - "tags": [ - { - "slug": "platform", - "name": "Platform", - "category": "PROPERTY" - }, - { - "slug": "ai-big-data", - "name": "AI & Big Data", - "category": "PROPERTY" - }, - { - "slug": "distributed-computing", - "name": "Distributed Computing", - "category": "PROPERTY" - }, - { - "slug": "filesharing", - "name": "Filesharing", - "category": "PROPERTY" - }, - { - "slug": "iot", - "name": "IoT", - "category": "PROPERTY" - }, - { - "slug": "storage", - "name": "Storage", - "category": "PROPERTY" - } - ], - "max_supply": 400000000, - "circulating_supply": 48400982, - "total_supply": 200000000, - "platform": { - "id": 1027, - "name": "Ethereum", - "symbol": "ETH", - "slug": "ethereum", - "token_address": "0xb9ef770b6a5e12e45983c5d80545258aa38f3b78" - }, - "is_active": 1, - "cmc_rank": 782, - "is_fiat": 0, - "self_reported_circulating_supply": 115000000, - "self_reported_market_cap": 25409234.858036295, - "last_updated": "2022-06-03T02:17:00.000Z", - "quote": { - "USD": { - "price": 0.2209498683307504, - "volume_24h": 28807.79174117, - "volume_change_24h": -78.341, - "percent_change_1h": 0.09600341, - "percent_change_24h": 0.1834049, - "percent_change_7d": 24.08736297, - "percent_change_30d": -43.56084388, - "percent_change_60d": -63.69787917, - "percent_change_90d": -27.17695342, - "market_cap": 10694190.59997902, - "market_cap_dominance": 0.0008, - "fully_diluted_market_cap": 88379947.33, - "last_updated": "2022-06-03T02:17:00.000Z" - } - } - } - ] - } -} \ No newline at end of file diff --git a/core/tokenrate/tokenrate.go b/core/tokenrate/tokenrate.go deleted file mode 100644 index d7decffeb..000000000 --- a/core/tokenrate/tokenrate.go +++ /dev/null @@ -1,54 +0,0 @@ -package tokenrate - -import ( - "context" - "errors" -) - -var ErrNoAvailableQuoteQuery = errors.New("token: no available quote query service") -var quotes []quoteQuery - -func init() { - - //priority: uniswap > bancor > coingecko > coinmarketcap - quotes = []quoteQuery{ - &coingeckoQuoteQuery{}, - &bancorQuoteQuery{}, - &uniswapQuoteQuery{}, - createCoinmarketcapQuoteQuery(), - //more query services - } - -} - -func GetUSD(ctx context.Context, symbol string) (float64, error) { - var err error - - ctx, cancel := context.WithCancel(ctx) - defer func() { - cancel() - }() - - for _, q := range quotes { - val, err := q.getUSD(ctx, symbol) - - if err != nil { - continue - } - - if val > 0 { - return val, nil - } - } - - // All conversion APIs failed - if err != nil { - return 0, err - } - - return 0, ErrNoAvailableQuoteQuery -} - -type quoteQuery interface { - getUSD(ctx context.Context, symbol string) (float64, error) -} diff --git a/core/tokenrate/tokenrate_test.go b/core/tokenrate/tokenrate_test.go deleted file mode 100644 index 74c998736..000000000 --- a/core/tokenrate/tokenrate_test.go +++ /dev/null @@ -1,242 +0,0 @@ -package tokenrate - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - "github.com/0chain/gosdk_common/core/resty" - "github.com/0chain/gosdk_common/zboxcore/mocks" -) - -func TestGetUSD(t *testing.T) { - mockProviderUrl := "coinProvider" - var mockClient = mocks.HttpClient{} - resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { - return &mockClient - } - - for _, tc := range []struct { - name string - expectedErr error - expectedValue float64 - timeout time.Duration - symbol string - provider string - setup func(testcaseName, symbol, provider string) - response func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) - }{ - { - name: "ContextDeadlineExceeded", - expectedErr: context.DeadlineExceeded, - timeout: 1 * time.Microsecond, - symbol: "ZCN", - provider: "bancor", - setup: func(testCaseName, symbol, provider string) { - setupMockHttpResponse(&mockClient, provider, mockProviderUrl, "TestGetUSD", testCaseName, "GET", symbol, http.StatusOK, getProviderJsonResponse(t, provider)) - }, - response: getBancorResponse(), - }, - { - name: "TestBancorCorrectSymbol", - expectedErr: nil, - expectedValue: 0.118837, - timeout: 10 * time.Second, - symbol: "ZCN", - provider: "bancor", - setup: func(testCaseName, symbol, provider string) { - setupMockHttpResponse(&mockClient, provider, mockProviderUrl, "TestGetUSD", testCaseName, "GET", symbol, http.StatusOK, getProviderJsonResponse(t, provider)) - }, - response: getBancorResponse(), - }, - { - name: "TestCoinmarketcapCorrectSymbol", - expectedErr: nil, - expectedValue: 0.2209498683307504, - timeout: 10 * time.Second, - symbol: "ZCN", - provider: "coinmarketcap", - setup: func(testCaseName, symbol, provider string) { - setupMockHttpResponse(&mockClient, provider, mockProviderUrl, "TestGetUSD", testCaseName, "GET", symbol, http.StatusOK, getProviderJsonResponse(t, provider)) - }, - response: getCoinmarketcapResponse(), - }, - { - name: "TestCoingeckoCorrectSymbol", - expectedErr: nil, - expectedValue: 0.218343, - timeout: 10 * time.Second, - symbol: "0chain", - provider: "coingecko", - setup: func(testCaseName, symbol, provider string) { - setupMockHttpResponse(&mockClient, provider, mockProviderUrl, "TestGetUSD", testCaseName, "GET", symbol, http.StatusOK, getProviderJsonResponse(t, provider)) - }, - response: getCoinGeckoResponse(), - }, - { - name: "TestCoinmarketcapWrongSymbol", - expectedErr: fmt.Errorf("429, failed to get coin data from provider coinmarketcap for symbol \"wrong\""), - timeout: 10 * time.Second, - symbol: "wrong", - provider: "coinmarketcap", - setup: func(testCaseName, symbol, provider string) { - setupMockHttpResponse(&mockClient, provider, mockProviderUrl, "TestGetUSD", testCaseName, "GET", symbol, http.StatusTooManyRequests, getProviderJsonResponse(t, provider)) - }, - response: getBancorResponse(), - }, - } { - t.Run(tc.name, func(t *testing.T) { - if tc.setup != nil { - tc.setup(tc.name, tc.symbol, tc.provider) - } - var value float64 - var err error - if tc.response != nil { - value, err = tc.response(tc.name, mockProviderUrl, tc.provider, tc.symbol, tc.timeout) - } - - if tc.expectedErr != nil { - require.EqualError(t, err, tc.expectedErr.Error()) - } else { - require.NoError(t, err) - require.Equal(t, value, tc.expectedValue) - } - }) - } -} - -func setupMockHttpResponse( - mockClient *mocks.HttpClient, provider, mockProviderUrl, funcName, testCaseName, httpMethod, symbol string, - statusCode int, body []byte) { - url := funcName + testCaseName + mockProviderUrl + provider - mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { - return req.Method == httpMethod && - strings.Contains(req.URL.String(), url) && (req.URL.Query().Get("symbol") == symbol) - })).Return( - &http.Response{ - StatusCode: statusCode, - Body: ioutil.NopCloser(bytes.NewReader(body)), - }, nil).Once() -} - -func getBancorResponse() func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) { - return func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) { - var br bancorResponse - ctx, cancel := context.WithTimeout(context.TODO(), timeout) - go func() { - <-ctx.Done() - cancel() - }() - - reqUrl := "TestGetUSD" + testCaseName + mockProviderURL + providerName + "?symbol=" + symbol - r := resty.New(resty.WithRetry(1)) - r.DoGet(ctx, reqUrl).Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("%v, failed to get coin data from provider %v for symbol \"%v\"", resp.StatusCode, providerName, symbol) - } - err = json.Unmarshal(respBody, &br) - log.Printf("==Response: %v", br) - if err != nil { - return err - } - br.Raw = string(respBody) - return nil - }) - errs := r.Wait() - if len(errs) != 0 { - return 0.0, errs[0] - } - return br.Data.Rate["usd"].Value, nil - } -} - -func getCoinmarketcapResponse() func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) { - return func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) { - var cr coinmarketcapResponse - ctx, cancel := context.WithTimeout(context.TODO(), timeout) - go func() { - <-ctx.Done() - cancel() - }() - - reqUrl := "TestGetUSD" + testCaseName + mockProviderURL + providerName + "?symbol=" + symbol - r := resty.New(resty.WithRetry(1)) - r.DoGet(ctx, reqUrl).Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("failed to get coin data from provider %v for symbol \"%v\"", providerName, symbol) - } - err = json.Unmarshal(respBody, &cr) - if err != nil { - return err - } - cr.Raw = string(respBody) - return nil - }) - errs := r.Wait() - if len(errs) != 0 { - return 0.0, errs[0] - } - if len(cr.Data[strings.ToUpper(symbol)]) == 0 { - return 0.0, fmt.Errorf("coinmarketcap: symbol \"%v\" is not provided on coinmarketcap apis", symbol) - } - val := cr.Data[strings.ToUpper(symbol)][0].Quote["USD"].Price - return val, nil - } -} - -func getCoinGeckoResponse() func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) { - return func(testCaseName, mockProviderURL, providerName, symbol string, timeout time.Duration) (float64, error) { - var cg coingeckoResponse - ctx, cancel := context.WithTimeout(context.TODO(), timeout) - go func() { - <-ctx.Done() - cancel() - }() - - reqUrl := "TestGetUSD" + testCaseName + mockProviderURL + providerName + "?symbol=" + symbol - r := resty.New(resty.WithRetry(1)) - r.DoGet(ctx, reqUrl).Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("failed to get coin data from provider %v for symbol \"%v\"", providerName, symbol) - } - err = json.Unmarshal(respBody, &cg) - if err != nil { - return err - } - cg.Raw = string(respBody) - return nil - }) - errs := r.Wait() - if len(errs) != 0 { - return 0.0, errs[0] - } - return cg.MarketData.CurrentPrice["usd"], nil - } -} - -func getProviderJsonResponse(t *testing.T, provider string) []byte { - data, err := ioutil.ReadFile("mockresponses/" + provider + ".json") - if err != nil { - t.Fatal(err) - } - return data -} diff --git a/core/tokenrate/uniswap.go b/core/tokenrate/uniswap.go deleted file mode 100644 index 0650611df..000000000 --- a/core/tokenrate/uniswap.go +++ /dev/null @@ -1,100 +0,0 @@ -package tokenrate - -import ( - "context" - "errors" - "strconv" - "strings" - - "github.com/0chain/gosdk_common/core/resty" - "github.com/machinebox/graphql" -) - -type V2Pair struct { - ID string - VolumeToken0 string - VolumeToken1 string - Token0Price string - Token1Price string - Token0 V2Token - Token1 V2Token -} - -type V2Token struct { - ID string - Symbol string -} - -type Query struct { - ZCN V2Pair - USDC V2Pair -} - -type uniswapQuoteQuery struct { -} - -func (qq *uniswapQuoteQuery) getUSD(ctx context.Context, symbol string) (float64, error) { - - hql := graphql.NewClient("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2") - - // make a request - req := graphql.NewRequest(` - { - zcn: pair(id:"0xa6890ac41e3a99a427bef68398bf06119fb5e211"){ - token0 { - id - symbol - totalSupply - } - token1 { - id - symbol - totalSupply - } - token0Price - token1Price - volumeToken0 - volumeToken1 - } - - usdc: pair(id:"0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc"){ - token0 { - id - symbol - totalSupply - } - token1 { - id - symbol - totalSupply - } - token0Price - token1Price - volumeToken0 - volumeToken1 - } - } -`) - - for k, v := range resty.DefaultHeader { - req.Header.Add(k, v) - } - - // run it and capture the response - q := &Query{} - if err := hql.Run(ctx, req, q); err != nil { - return 0, err - } - - switch strings.ToUpper(symbol) { - case "ZCN": - ethPerZCN, _ := strconv.ParseFloat(q.ZCN.Token1Price, 64) - usdcPerETH, _ := strconv.ParseFloat(q.USDC.Token0Price, 64) - return ethPerZCN * usdcPerETH, nil - case "ETH": - usdcPerETH, _ := strconv.ParseFloat(q.USDC.Token0Price, 64) - return usdcPerETH, nil - } - - return 0, errors.New("uniswap: quote [" + symbol + "] is unimplemented yet") -} diff --git a/core/transaction/entity.go b/core/transaction/entity.go deleted file mode 100644 index 1d6a7cda0..000000000 --- a/core/transaction/entity.go +++ /dev/null @@ -1,464 +0,0 @@ -// Provides low-level functions and types to work with the native smart contract transactions. -package transaction - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/util" - lru "github.com/hashicorp/golang-lru" -) - -const TXN_SUBMIT_URL = "v1/transaction/put" -const TXN_VERIFY_URL = "v1/transaction/get/confirmation?hash=" -const BLOCK_BY_ROUND_URL = "v1/screst/6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d7/block?round=" - -const ( - TxnSuccess = 1 // Indicates the transaction is successful in updating the state or smart contract - TxnChargeableError = 2 // Indicates the transaction is successful in updating the state or smart contract - TxnFail = 3 // Indicates a transaction has failed to update the state or smart contract -) - -// TxnReceipt - a transaction receipt is a processed transaction that contains the output -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"` -} - -type StorageAllocation struct { - ID string `json:"id"` - 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"` - ReadRatio *Ratio `json:"read_ratio"` - WriteRatio *Ratio `json:"write_ratio"` - MinLockDemand float64 `json:"min_lock_demand"` -} -type Ratio struct { - ZCN int64 `json:"zcn"` - Size int64 `json:"size"` -} -type RoundBlockHeader struct { - Version string `json:"version"` - CreationDate int64 `json:"creation_date"` - Hash string `json:"block_hash"` - PreviousBlockHash string `json:"previous_block_hash"` - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - RoundRandomSeed int64 `json:"round_random_seed"` - MerkleTreeRoot string `json:"merkle_tree_root"` - StateChangesCount int `json:"state_changes_count"` - StateHash string `json:"state_hash"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - NumberOfTxns int64 `json:"num_txns"` -} - -type Block struct { - Hash string `json:"hash" gorm:"uniqueIndex:idx_bhash"` - Version string `json:"version"` - CreationDate int64 `json:"creation_date" gorm:"index:idx_bcreation_date"` - Round int64 `json:"round" gorm:"index:idx_bround"` - MinerID string `json:"miner_id"` - RoundRandomSeed int64 `json:"round_random_seed"` - MerkleTreeRoot string `json:"merkle_tree_root"` - StateHash string `json:"state_hash"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - NumTxns int `json:"num_txns"` - MagicBlockHash string `json:"magic_block_hash"` - PrevHash string `json:"prev_hash"` - Signature string `json:"signature"` - ChainId string `json:"chain_id"` - StateChangesCount int `json:"state_changes_count"` - RunningTxnCount string `json:"running_txn_count"` - RoundTimeoutCount int `json:"round_timeout_count"` -} - -const ( - NEW_ALLOCATION_REQUEST = "new_allocation_request" - NEW_FREE_ALLOCATION = "free_allocation_request" - UPDATE_ALLOCATION_REQUEST = "update_allocation_request" - LOCK_TOKEN = "lock" - UNLOCK_TOKEN = "unlock" - - ADD_FREE_ALLOCATION_ASSIGNER = "add_free_storage_assigner" - - // Vesting SC - VESTING_TRIGGER = "trigger" - VESTING_STOP = "stop" - VESTING_UNLOCK = "unlock" - VESTING_ADD = "add" - VESTING_DELETE = "delete" - VESTING_UPDATE_SETTINGS = "vestingsc-update-settings" - - // Storage SC - STORAGESC_FINALIZE_ALLOCATION = "finalize_allocation" - STORAGESC_CANCEL_ALLOCATION = "cancel_allocation" - STORAGESC_CREATE_ALLOCATION = "new_allocation_request" - STORAGESC_CREATE_READ_POOL = "new_read_pool" - STORAGESC_READ_POOL_LOCK = "read_pool_lock" - STORAGESC_READ_POOL_UNLOCK = "read_pool_unlock" - STORAGESC_STAKE_POOL_LOCK = "stake_pool_lock" - STORAGESC_STAKE_POOL_UNLOCK = "stake_pool_unlock" - STORAGESC_UPDATE_BLOBBER_SETTINGS = "update_blobber_settings" - STORAGESC_UPDATE_VALIDATOR_SETTINGS = "update_validator_settings" - STORAGESC_UPDATE_ALLOCATION = "update_allocation_request" - STORAGESC_WRITE_POOL_LOCK = "write_pool_lock" - STORAGESC_WRITE_POOL_UNLOCK = "write_pool_unlock" - STORAGESC_UPDATE_SETTINGS = "update_settings" - ADD_HARDFORK = "add_hardfork" - STORAGESC_COLLECT_REWARD = "collect_reward" - STORAGESC_KILL_BLOBBER = "kill_blobber" - STORAGESC_KILL_VALIDATOR = "kill_validator" - STORAGESC_SHUTDOWN_BLOBBER = "shutdown_blobber" - STORAGESC_SHUTDOWN_VALIDATOR = "shutdown_validator" - STORAGESC_RESET_BLOBBER_STATS = "reset_blobber_stats" - STORAGESC_RESET_ALLOCATION_STATS = "reset_allocation_stats" - - MINERSC_LOCK = "addToDelegatePool" - MINERSC_UNLOCK = "deleteFromDelegatePool" - MINERSC_MINER_SETTINGS = "update_miner_settings" - MINERSC_SHARDER_SETTINGS = "update_sharder_settings" - MINERSC_UPDATE_SETTINGS = "update_settings" - MINERSC_UPDATE_GLOBALS = "update_globals" - MINERSC_MINER_DELETE = "delete_miner" - MINERSC_SHARDER_DELETE = "delete_sharder" - MINERSC_COLLECT_REWARD = "collect_reward" - MINERSC_KILL_MINER = "kill_miner" - MINERSC_KILL_SHARDER = "kill_sharder" - - // Faucet SC - FAUCETSC_UPDATE_SETTINGS = "update-settings" - - // ZCNSC smart contract - - ZCNSC_UPDATE_GLOBAL_CONFIG = "update-global-config" - ZCNSC_UPDATE_AUTHORIZER_CONFIG = "update-authorizer-config" - ZCNSC_ADD_AUTHORIZER = "add-authorizer" - ZCNSC_AUTHORIZER_HEALTH_CHECK = "authorizer-health-check" - ZCNSC_DELETE_AUTHORIZER = "delete-authorizer" - ZCNSC_COLLECT_REWARD = "collect-rewards" - ZCNSC_LOCK = "add-to-delegate-pool" - ZCNSC_UNLOCK = "delete-from-delegate-pool" - - ESTIMATE_TRANSACTION_COST = `/v1/estimate_txn_fee` - FEES_TABLE = `/v1/fees_table` -) - -type SignFunc = func(msg string) (string, error) -type VerifyFunc = func(publicKey, signature, msgHash string) (bool, error) -type SignWithWallet = func(msg string, wallet interface{}) (string, error) - -var cache *lru.Cache - -func init() { - var err error - cache, err = lru.New(100) - if err != nil { - fmt.Println("caching Initilization failed, err:", err) - } -} - -func NewTransactionEntity(clientID string, chainID string, publicKey string, nonce int64) *Transaction { - txn := &Transaction{} - txn.Version = "1.0" - txn.ClientID = clientID - txn.CreationDate = int64(common.Now()) - txn.ChainID = chainID - txn.PublicKey = publicKey - txn.TransactionNonce = nonce - return txn -} - -func (t *Transaction) ComputeHashAndSignWithWallet(signHandler SignWithWallet, signingWallet interface{}) error { - t.ComputeHashData() - var err error - t.Signature, err = signHandler(t.Hash, signingWallet) - if err != nil { - return err - } - return nil -} - -func (t *Transaction) ComputeHashAndSign(signHandler SignFunc) error { - t.ComputeHashData() - var err error - t.Signature, err = signHandler(t.Hash) - if err != nil { - return err - } - return nil -} - -func (t *Transaction) ComputeHashData() { - hashdata := fmt.Sprintf("%v:%v:%v:%v:%v:%v", t.CreationDate, t.TransactionNonce, t.ClientID, - t.ToClientID, t.Value, encryption.Hash(t.TransactionData)) - t.Hash = encryption.Hash(hashdata) -} - -func (t *Transaction) DebugJSON() []byte { - jsonByte, err := json.MarshalIndent(t, "", " ") - if err != nil { - panic(err) // This JSONify function only supposed to be debug-only anyway. - } - return jsonByte -} - -// GetHash - implement interface -func (rh *TxnReceipt) GetHash() string { - return rh.Transaction.OutputHash -} - -/*GetHashBytes - implement Hashable interface */ -func (rh *TxnReceipt) GetHashBytes() []byte { - return util.HashStringToBytes(rh.Transaction.OutputHash) -} - -// NewTransactionReceipt - create a new transaction receipt -func NewTransactionReceipt(t *Transaction) *TxnReceipt { - return &TxnReceipt{Transaction: t} -} - -// VerifySigWith verify the signature with the given public key and handler -func (t *Transaction) VerifySigWith(pubkey string, verifyHandler VerifyFunc) (bool, error) { - // Store the hash - hash := t.Hash - t.ComputeHashData() - if t.Hash != hash { - return false, errors.New("verify_transaction", fmt.Sprintf(`{"error":"hash_mismatch", "expected":"%v", "actual":%v"}`, t.Hash, hash)) - } - return verifyHandler(pubkey, t.Signature, t.Hash) -} - -func SendTransactionSync(txn *Transaction, miners []string) error { - wg := sync.WaitGroup{} - wg.Add(len(miners)) - fails := make(chan error, len(miners)) - - for _, miner := range miners { - url := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL) - go func() { - _, err := sendTransactionToURL(url, txn, &wg) - if err != nil { - fails <- err - } - wg.Done() - }() //nolint - } - wg.Wait() - close(fails) - - failureCount := 0 - messages := make(map[string]int) - for e := range fails { - if e != nil { - failureCount++ - messages[e.Error()] += 1 - } - } - - max := 0 - dominant := "" - for m, s := range messages { - if s > max { - dominant = m - } - } - - if failureCount == len(miners) { - return errors.New("transaction_send_error", dominant) - } - - return nil -} - -func sendTransactionToURL(url string, txn *Transaction, wg *sync.WaitGroup) ([]byte, error) { - postReq, err := util.NewHTTPPostRequest(url, txn) - if err != nil { - //Logger.Error("Error in serializing the transaction", txn, err.Error()) - return nil, err - } - postResponse, err := postReq.Post() - if postResponse.StatusCode >= 200 && postResponse.StatusCode <= 299 { - return []byte(postResponse.Body), nil - } - return nil, errors.Wrap(err, errors.New("transaction_send_error", postResponse.Body)) -} - -type cachedObject struct { - Expiration time.Duration - Value interface{} -} - -func retriveFromTable(table map[string]map[string]int64, txnName, toAddress string) (uint64, error) { - var fees uint64 - if val, ok := table[toAddress]; ok { - fees = uint64(val[txnName]) - } else { - if txnName == "transfer" { - fees = uint64(table["transfer"]["transfer"]) - } else { - return 0, fmt.Errorf("invalid transaction") - } - } - return fees, nil -} - -// EstimateFee estimates transaction fee -func EstimateFee(txn *Transaction, miners []string, reqPercent ...float32) (uint64, error) { - const minReqNum = 3 - var reqN int - - if len(reqPercent) > 0 { - reqN = int(reqPercent[0] * float32(len(miners))) - } - - txData := txn.TransactionData - - var sn SmartContractTxnData - err := json.Unmarshal([]byte(txData), &sn) - if err != nil { - return 0, err - } - - txnName := sn.Name - txnName = strings.ToLower(txnName) - toAddress := txn.ToClientID - - reqN = util.MaxInt(minReqNum, reqN) - reqN = util.MinInt(reqN, len(miners)) - randomMiners := util.Shuffle(miners)[:reqN] - - // Retrieve the object from the cache - cached, ok := cache.Get(FEES_TABLE) - if ok { - cachedObj, ok := cached.(*cachedObject) - if ok { - table := cachedObj.Value.(map[string]map[string]int64) - fees, err := retriveFromTable(table, txnName, toAddress) - if err != nil { - return 0, err - } - return fees, nil - } - } - - table, err := GetFeesTable(randomMiners, reqPercent...) - if err != nil { - return 0, err - } - - fees, err := retriveFromTable(table, txnName, toAddress) - if err != nil { - return 0, err - } - - cache.Add(FEES_TABLE, &cachedObject{ - Expiration: 30 * time.Hour, - Value: table, - }) - - return fees, nil -} - -// GetFeesTable get fee tables -func GetFeesTable(miners []string, reqPercent ...float32) (map[string]map[string]int64, error) { - const minReqNum = 3 - var reqN int - - if len(reqPercent) > 0 { - reqN = int(reqPercent[0] * float32(len(miners))) - } - - reqN = util.MaxInt(minReqNum, reqN) - reqN = util.MinInt(reqN, len(miners)) - randomMiners := util.Shuffle(miners)[:reqN] - - var ( - feesC = make(chan string, reqN) - errC = make(chan error, reqN) - ) - - wg := &sync.WaitGroup{} - wg.Add(len(randomMiners)) - - for _, miner := range randomMiners { - go func(minerUrl string) { - defer wg.Done() - - url := minerUrl + FEES_TABLE - req, err := util.NewHTTPGetRequest(url) - if err != nil { - errC <- fmt.Errorf("create request failed, url: %s, err: %v", url, err) - return - } - - res, err := req.Get() - if err != nil { - errC <- fmt.Errorf("request failed, url: %s, err: %v", url, err) - return - } - - if res.StatusCode == http.StatusOK { - feesC <- res.Body - return - } - - feesC <- "" - - }(miner) - } - - // wait for requests to complete - wg.Wait() - close(feesC) - close(errC) - - feesCount := make(map[string]int, reqN) - for f := range feesC { - feesCount[f]++ - } - - if len(feesCount) > 0 { - var ( - max int - fees string - ) - - for f, count := range feesCount { - if f != "" && count > max { - max = count - fees = f - } - } - - feesTable := make(map[string]map[string]int64) - err := json.Unmarshal([]byte(fees), &feesTable) - if err != nil { - return nil, errors.New("failed to get fees table", err.Error()) - } - - return feesTable, nil - } - - errs := make([]string, 0, reqN) - for err := range errC { - errs = append(errs, err.Error()) - } - - return nil, errors.New("failed to get fees table", strings.Join(errs, ",")) -} diff --git a/core/transaction/entity_test.go b/core/transaction/entity_test.go deleted file mode 100644 index 9b6c951c4..000000000 --- a/core/transaction/entity_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package transaction - -import ( - "testing" - - "github.com/0chain/gosdk_common/core/conf" - "github.com/stretchr/testify/assert" -) - -func TestOptimisticVerificationLearning(t *testing.T) { - t.Skip() - conf.InitClientConfig(&conf.Config{ - BlockWorker: "", - MinSubmit: 0, - MinConfirmation: 50, - ConfirmationChainLength: 3, - MaxTxnQuery: 0, - QuerySleepTime: 0, - SignatureScheme: "", - ChainID: "", - EthereumNode: "", - }) - ov := NewOptimisticVerifier([]string{"https://dev.zus.network/sharder01", "https://dev.zus.network/sharder02"}) - _, err := ov.VerifyTransactionOptimistic("a20360964c067b319d52b5cad71d771b0e1d2a80e76001da73009899b09ffa31") - - assert.NoError(t, err) - -} diff --git a/core/transaction/transaction.go b/core/transaction/transaction.go deleted file mode 100644 index 2040630cf..000000000 --- a/core/transaction/transaction.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !mobile -// +build !mobile - -package transaction - -// Transaction entity that encapsulates the transaction related data and meta data -type Transaction struct { - Hash string `json:"hash,omitempty"` - Version string `json:"version,omitempty"` - ClientID string `json:"client_id,omitempty"` - PublicKey string `json:"public_key,omitempty"` - ToClientID string `json:"to_client_id,omitempty"` - ChainID string `json:"chain_id,omitempty"` - TransactionData string `json:"transaction_data"` - Value uint64 `json:"transaction_value"` - Signature string `json:"signature,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - TransactionType int `json:"transaction_type"` - TransactionOutput string `json:"transaction_output,omitempty"` - TransactionFee uint64 `json:"transaction_fee"` - TransactionNonce int64 `json:"transaction_nonce"` - OutputHash string `json:"txn_output_hash"` - Status int `json:"transaction_status"` -} diff --git a/core/transaction/transaction_mobile.go b/core/transaction/transaction_mobile.go deleted file mode 100644 index 3119429e5..000000000 --- a/core/transaction/transaction_mobile.go +++ /dev/null @@ -1,82 +0,0 @@ -//go:build mobile -// +build mobile - -package transaction - -import ( - "encoding/json" - "strconv" -) - -// Transaction represents entity that encapsulates the transaction related data and metadata. -type Transaction struct { - Hash string `json:"hash,omitempty"` - Version string `json:"version,omitempty"` - ClientID string `json:"client_id,omitempty"` - PublicKey string `json:"public_key,omitempty"` - ToClientID string `json:"to_client_id,omitempty"` - ChainID string `json:"chain_id,omitempty"` - TransactionData string `json:"transaction_data"` - Value string `json:"transaction_value"` - Signature string `json:"signature,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - TransactionType int `json:"transaction_type"` - TransactionOutput string `json:"transaction_output,omitempty"` - TransactionFee string `json:"transaction_fee"` - TransactionNonce int64 `json:"transaction_nonce"` - OutputHash string `json:"txn_output_hash"` - Status int `json:"transaction_status"` -} - -// TransactionWrapper represents wrapper for mobile transaction entity. -type TransactionWrapper struct { - Hash string `json:"hash,omitempty"` - Version string `json:"version,omitempty"` - ClientID string `json:"client_id,omitempty"` - PublicKey string `json:"public_key,omitempty"` - ToClientID string `json:"to_client_id,omitempty"` - ChainID string `json:"chain_id,omitempty"` - TransactionData string `json:"transaction_data"` - Value uint64 `json:"transaction_value"` - Signature string `json:"signature,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - TransactionType int `json:"transaction_type"` - TransactionOutput string `json:"transaction_output,omitempty"` - TransactionFee uint64 `json:"transaction_fee"` - TransactionNonce int64 `json:"transaction_nonce"` - OutputHash string `json:"txn_output_hash"` - Status int `json:"transaction_status"` -} - -func (t *Transaction) MarshalJSON() ([]byte, error) { - valueRaw, err := strconv.ParseUint(t.Value, 0, 64) - if err != nil { - return nil, err - } - - transactionFeeRaw, err := strconv.ParseUint(t.TransactionFee, 0, 64) - if err != nil { - return nil, err - } - - wrapper := TransactionWrapper{ - Hash: t.Hash, - Version: t.Version, - ClientID: t.ClientID, - PublicKey: t.PublicKey, - ToClientID: t.ToClientID, - ChainID: t.ChainID, - TransactionData: t.TransactionData, - Value: valueRaw, - Signature: t.Signature, - CreationDate: t.CreationDate, - TransactionType: t.TransactionType, - TransactionOutput: t.TransactionOutput, - TransactionFee: transactionFeeRaw, - TransactionNonce: t.TransactionNonce, - OutputHash: t.OutputHash, - Status: t.Status, - } - - return json.Marshal(wrapper) -} diff --git a/core/transaction/transport.go b/core/transaction/transport.go deleted file mode 100644 index 93677c398..000000000 --- a/core/transaction/transport.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package transaction - -import ( - "net" - "net/http" - "time" -) - -func createTransport(dialTimeout time.Duration) *http.Transport { - return &http.Transport{ - Dial: (&net.Dialer{ - Timeout: dialTimeout, - }).Dial, - TLSHandshakeTimeout: dialTimeout, - } - -} diff --git a/core/transaction/transport_wasm.go b/core/transaction/transport_wasm.go deleted file mode 100644 index 7a911d642..000000000 --- a/core/transaction/transport_wasm.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package transaction - -import ( - "net/http" - "time" -) - -func createTransport(dialTimeout time.Duration) *http.Transport { - return &http.Transport{ - TLSHandshakeTimeout: dialTimeout, - } -} diff --git a/core/transaction/type.go b/core/transaction/type.go deleted file mode 100644 index 5f75a1826..000000000 --- a/core/transaction/type.go +++ /dev/null @@ -1,15 +0,0 @@ -package transaction - -const ( - TxnTypeSend = 0 // A transaction to send tokens to another account, state is maintained by account - - TxnTypeLockIn = 2 // A transaction to lock tokens, state is maintained on the account and the parent lock in transaction - - // Any txn type that refers to a parent txn should have an odd value - TxnTypeStorageWrite = 101 // A transaction to write data to the blobber - TxnTypeStorageRead = 103 // A transaction to read data from the blobber - - TxnTypeData = 10 // A transaction to just store a piece of data on the block chain - - TxnTypeSmartContract = 1000 // A smart contract transaction type -) diff --git a/core/transaction/utils.go b/core/transaction/utils.go deleted file mode 100644 index b42f2a96e..000000000 --- a/core/transaction/utils.go +++ /dev/null @@ -1,435 +0,0 @@ -package transaction - -import ( - "context" - "encoding/json" - "fmt" - "math" - "net/http" - "strconv" - "strings" - "time" - - "github.com/0chain/common/core/encryption" - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/resty" - "github.com/0chain/gosdk_common/core/util" -) - -const retriesCount = 30 - -type OptimisticVerifier struct { - allSharders []string - sharders []string - options []resty.Option -} - -func NewOptimisticVerifier(sharders []string) *OptimisticVerifier { - //initialize resty - header := map[string]string{ - "Content-Type": "application/json; charset=utf-8", - "Access-Control-Allow-Origin": "*", - } - - transport := createTransport(resty.DefaultDialTimeout) - - options := []resty.Option{ - resty.WithRetry(resty.DefaultRetry), - resty.WithHeader(header), - resty.WithTransport(transport), - } - - return &OptimisticVerifier{ - allSharders: sharders, - options: options, - } -} - -func (v *OptimisticVerifier) VerifyTransactionOptimistic(txnHash string) (*Transaction, error) { - cfg, err := conf.GetClientConfig() - if err != nil { - - return nil, err - } - - //refresh sharders - v.sharders = v.allSharders - - //amount of sharders to query - minNumConfirmation := int(math.Ceil(float64(cfg.MinConfirmation*len(v.sharders)) / 100)) - if minNumConfirmation > len(v.sharders) { - return nil, errors.New("verify_optimistic", "wrong number of min_confirmations") - } - shuffled := util.Shuffle(v.sharders)[:minNumConfirmation] - - //prepare urls for confirmation request - urls := make([]string, 0, len(shuffled)) - mappedSharders := make(map[string]string) - for _, sharder := range shuffled { - url := fmt.Sprintf("%v/%v%v", sharder, TXN_VERIFY_URL, txnHash) - urls = append(urls, url) - mappedSharders[url] = sharder - } - - var url string - var chain []*RoundBlockHeader - var txn *Transaction - r := resty.New(v.options...).Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { //network issue - return err - } - - if resp.StatusCode != 200 { - return errors.Throw(ErrInvalidRequest, strconv.Itoa(resp.StatusCode)+": "+resp.Status) - } - - //parse response - var objmap map[string]json.RawMessage - err = json.Unmarshal(respBody, &objmap) - if err != nil { - return err - } - txnRawJSON, ok := objmap["txn"] - // txn data is found, success - if !ok { - return errors.New("handle_response", "bad transaction response") - } - merklePathRawJSON, ok := objmap["merkle_tree_path"] - if !ok { - return errors.New("handle_response", "bad merkle_tree_path response") - } - - txn = &Transaction{} - err = json.Unmarshal(txnRawJSON, txn) - if err != nil { - return err - } - - b := &RoundBlockHeader{} - err = json.Unmarshal(respBody, b) - if err != nil { - return err - } - err = validateBlockHash(b) - if err != nil { - return err - } - - err = verifyMerklePath(merklePathRawJSON, txn.Hash, b.MerkleTreeRoot) - if err != nil { - return err - } - - url = req.URL.String() - chain = append(chain, b) - return nil - }) - - retries := 0 - ticker := time.NewTicker(time.Second) -L: - //loop query confirmation - for retries < retriesCount { - <-ticker.C - retries++ - r.DoGet(context.TODO(), urls...) - //need single valid confirmation - errs := r.First() - if len(errs) == 0 { - break L - } - } - - if len(chain) == 0 { - return nil, errors.Newf("verify", "can't get confirmation after %v retries", retriesCount) - } - - //remove current sharder from the list to avoid building chain with it - toDelete := mappedSharders[url] - for i, s := range v.sharders { - if s == toDelete { - v.sharders = append(v.sharders[:i], v.sharders[i+1:]...) - break - } - } - - err = v.checkConfirmation(chain) - if err != nil { - return nil, err - } - - return txn, err -} - -func (v *OptimisticVerifier) checkConfirmation(chain []*RoundBlockHeader) error { - cfg, err := conf.GetClientConfig() - if err != nil { - - return err - } - - //build blockchain starting from confirmation block - curRound := chain[0].Round - rb := resty.New(v.options...).Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { //network issue - return err - } - - if resp.StatusCode != 200 { - return errors.Throw(ErrInvalidRequest, strconv.Itoa(resp.StatusCode)+": "+resp.Status) - } - - curBlock := &Block{} - err = json.Unmarshal(respBody, &curBlock) - if err != nil { - return err - } - - //get tail block and check that current extends it - prevBlock := chain[len(chain)-1] - if prevBlock.Hash == curBlock.PrevHash && prevBlock.Round+1 == curBlock.Round { - blockHeader := &RoundBlockHeader{ - Version: curBlock.Version, - CreationDate: curBlock.CreationDate, - Hash: curBlock.Hash, - PreviousBlockHash: curBlock.PrevHash, - MinerID: curBlock.MinerID, - Round: curBlock.Round, - RoundRandomSeed: curBlock.RoundRandomSeed, - MerkleTreeRoot: curBlock.MerkleTreeRoot, - StateChangesCount: curBlock.StateChangesCount, - StateHash: curBlock.StateHash, - ReceiptMerkleTreeRoot: curBlock.ReceiptMerkleTreeRoot, - NumberOfTxns: int64(curBlock.NumTxns), - } - err = validateBlockHash(blockHeader) - if err != nil { - return err - } - - chain = append(chain, blockHeader) - return nil - } - return errors.New("get_block", "wrong block") - }) - - //query for blocks until ConfirmationChainLength is built or every sharder is queried - for len(chain) < cfg.ConfirmationChainLength && len(v.sharders) > 0 { - //for every new block create sharder list to query - rand := util.NewRand(len(v.sharders)) - //iterate through all sharders sequentially to get next block - for { - next, err := rand.Next() - if err != nil { - return errors.New("get_round_block", "can't get round block, blockchain might be stuck") - } - - cur := v.sharders[next] - burl := fmt.Sprintf("%v/%v%v", cur, BLOCK_BY_ROUND_URL, curRound+1) - rb.DoGet(context.TODO(), burl) - - wait := rb.Wait() - if len(wait) != 0 { - continue - } - //exclude sharder if it gave block, we do it to avoid building blockchain from single sharder - v.sharders = append(v.sharders[:next], v.sharders[next+1:]...) - curRound++ - break - } - } - - return nil -} - -func verifyMerklePath(merklePathRawJSON json.RawMessage, txnHash string, merkleRoot string) error { - merklePath := &util.MTPath{} - err := json.Unmarshal(merklePathRawJSON, merklePath) - if err != nil { - return err - } - if !util.VerifyMerklePath(txnHash, merklePath, merkleRoot) { - return errors.New("handle_response", "invalid merkle path") - } - return nil -} - -func validateBlockHash(b *RoundBlockHeader) error { - hashBuilder := strings.Builder{} - hashBuilder.WriteString(b.MinerID) - hashBuilder.WriteString(":") - hashBuilder.WriteString(b.PreviousBlockHash) - hashBuilder.WriteString(":") - hashBuilder.WriteString(strconv.FormatInt(b.CreationDate, 10)) - hashBuilder.WriteString(":") - hashBuilder.WriteString(strconv.FormatInt(b.Round, 10)) - hashBuilder.WriteString(":") - hashBuilder.WriteString(strconv.FormatInt(b.RoundRandomSeed, 10)) - hashBuilder.WriteString(":") - hashBuilder.WriteString(strconv.Itoa(b.StateChangesCount)) - hashBuilder.WriteString(":") - hashBuilder.WriteString(b.MerkleTreeRoot) - hashBuilder.WriteString(":") - hashBuilder.WriteString(b.ReceiptMerkleTreeRoot) - //todo handling of magic block here - hash := encryption.Hash(hashBuilder.String()) - if hash != b.Hash { - return errors.New("handle_response", "invalid block hash") - } - return nil -} - -// VerifyTransaction query transaction status from sharders, and verify it by mininal confirmation -func VerifyTransaction(txnHash string, sharders []string) (*Transaction, error) { - cfg, err := conf.GetClientConfig() - if err != nil { - return nil, err - } - - if cfg.VerifyOptimistic { - ov := NewOptimisticVerifier(sharders) - return ov.VerifyTransactionOptimistic(txnHash) - } else { - return VerifyTransactionTrusted(txnHash, sharders) - } -} - -// VerifyTransaction query transaction status from sharders, and verify it by mininal confirmation -func VerifyTransactionTrusted(txnHash string, sharders []string) (*Transaction, error) { - - cfg, err := conf.GetClientConfig() - if err != nil { - - return nil, err - } - - numSharders := len(sharders) - - if numSharders == 0 { - return nil, ErrNoAvailableSharder - } - - minNumConfirmation := int(math.Ceil(float64(cfg.MinConfirmation*numSharders) / 100)) - - rand := util.NewRand(numSharders) - - selectedSharders := make([]string, 0, minNumConfirmation+1) - - // random pick minNumConfirmation+1 first - for i := 0; i <= minNumConfirmation; i++ { - n, err := rand.Next() - - if err != nil { - break - } - - selectedSharders = append(selectedSharders, sharders[n]) - } - - numSuccess := 0 - - var retTxn *Transaction - - //leave first item for ErrTooLessConfirmation - var msgList = make([]string, 1, numSharders) - - urls := make([]string, 0, len(selectedSharders)) - - for _, sharder := range selectedSharders { - urls = append(urls, fmt.Sprintf("%v/%v%v", sharder, TXN_VERIFY_URL, txnHash)) - } - - header := map[string]string{ - "Content-Type": "application/json; charset=utf-8", - "Access-Control-Allow-Origin": "*", - } - - transport := createTransport(resty.DefaultDialTimeout) - - options := []resty.Option{ - resty.WithRetry(resty.DefaultRetry), - resty.WithHeader(header), - resty.WithTransport(transport), - } - - r := resty.New(options...). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - url := req.URL.String() - - if err != nil { //network issue - msgList = append(msgList, err.Error()) - return err - } - - if resp.StatusCode != 200 { - msgList = append(msgList, url+": ["+strconv.Itoa(resp.StatusCode)+"] "+string(respBody)) - return errors.Throw(ErrInvalidRequest, strconv.Itoa(resp.StatusCode)+": "+resp.Status) - } - - var objmap map[string]json.RawMessage - err = json.Unmarshal(respBody, &objmap) - if err != nil { - msgList = append(msgList, "json: "+string(respBody)) - return err - } - txnRawJSON, ok := objmap["txn"] - - // txn data is found, success - if ok { - txn := &Transaction{} - err = json.Unmarshal(txnRawJSON, txn) - if err != nil { - msgList = append(msgList, "json: "+string(txnRawJSON)) - return err - } - if len(txn.Signature) > 0 { - retTxn = txn - } - numSuccess++ - - } else { - // txn data is not found, but get block_hash, success - if _, ok := objmap["block_hash"]; ok { - numSuccess++ - } else { - // txn and block_hash - msgList = append(msgList, fmt.Sprintf("Sharder does not have the block summary with url: %s, contents: %s", url, string(respBody))) - } - - } - - return nil - }) - - for { - r.DoGet(context.TODO(), urls...) - - r.Wait() - - if numSuccess >= minNumConfirmation { - break - } - - // pick one more sharder to query transaction - n, err := rand.Next() - - if errors.Is(err, util.ErrNoItem) { - break - } - - urls = []string{fmt.Sprintf("%v/%v%v", sharders[n], TXN_VERIFY_URL, txnHash)} - - } - - if numSuccess > 0 && numSuccess >= minNumConfirmation { - if retTxn == nil { - return nil, errors.Throw(ErrNoTxnDetail, strings.Join(msgList, "\r\n")) - } - return retTxn, nil - } - - msgList[0] = fmt.Sprintf("min_confirmation is %v%%, but got %v/%v sharders", cfg.MinConfirmation, numSuccess, numSharders) - return nil, errors.Throw(ErrTooLessConfirmation, strings.Join(msgList, "\r\n")) - -} diff --git a/core/transaction/vars.go b/core/transaction/vars.go deleted file mode 100644 index 1b33159e9..000000000 --- a/core/transaction/vars.go +++ /dev/null @@ -1,19 +0,0 @@ -package transaction - -import ( - "errors" -) - -var ( - // ErrInvalidRequest invalid request - ErrInvalidRequest = errors.New("[txn] invalid request") - - // ErrNoAvailableSharder no any available sharder - ErrNoAvailableSharder = errors.New("[txn] there is no any available sharder") - - // ErrNoTxnDetail No transaction detail was found on any of the sharders - ErrNoTxnDetail = errors.New("[txn] no transaction detail was found on any of the sharders") - - // ErrTooLessConfirmation too less sharder to confirm transaction - ErrTooLessConfirmation = errors.New("[txn] too less sharders to confirm it") -) diff --git a/core/util/doc.go b/core/util/doc.go deleted file mode 100644 index 425c3445d..000000000 --- a/core/util/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index 239dd923a..000000000 --- a/core/util/fixed_merkle_tree.go +++ /dev/null @@ -1,271 +0,0 @@ -package util - -import ( - "bytes" - "encoding/hex" - "hash" - "io" - "sync" - - goError "errors" - - "github.com/0chain/errors" - "github.com/minio/sha256-simd" -) - -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 -) - -var ( - leafPool = sync.Pool{ - New: func() interface{} { - return &leaf{ - h: sha256.New(), - } - }, - } -) - -type leaf struct { - h hash.Hash -} - -func (l *leaf) GetHashBytes() []byte { - return l.h.Sum(nil) -} - -func (l *leaf) GetHash() string { - return hex.EncodeToString(l.h.Sum(nil)) -} - -func (l *leaf) Write(b []byte) (int, error) { - return l.h.Write(b) -} - -func getNewLeaf() *leaf { - l, ok := leafPool.Get().(*leaf) - if !ok { - return &leaf{ - h: sha256.New(), - } - } - l.h.Reset() - return l -} - -// FixedMerkleTree A trusted mekerle tree for outsourcing attack protection. see section 1.8 on whitepager -// see detail on https://github.com/0chain/blobber/wiki/Protocols#what-is-fixedmerkletree -type FixedMerkleTree struct { - // Leaves will store hash digester that calculates sha256 hash of the leaf content - Leaves []Hashable `json:"leaves,omitempty"` - - writeLock sync.Mutex - // isFinal is set to true once Finalize() is called. - // After it is set to true, there will be no any writes to writeBytes field - isFinal bool - // writeCount will track count of bytes written to writeBytes field - writeCount int - // writeBytes will store bytes upto MaxMerkleLeavesSize. For the last bytes that - // does not make upto MaxMerkleLeavesSize, it will be sliced with writeCount field. - writeBytes []byte - merkleRoot []byte -} - -// Finalize will set isFinal to true and sends remaining bytes for leaf hash calculation -func (fmt *FixedMerkleTree) Finalize() error { - fmt.writeLock.Lock() - defer fmt.writeLock.Unlock() - - if fmt.isFinal { - return goError.New("already finalized") - } - fmt.isFinal = true - if fmt.writeCount > 0 { - return fmt.writeToLeaves(fmt.writeBytes[:fmt.writeCount]) - } - return nil -} - -// NewFixedMerkleTree create a FixedMerkleTree with specify hash method -func NewFixedMerkleTree() *FixedMerkleTree { - - t := &FixedMerkleTree{ - writeBytes: make([]byte, MaxMerkleLeavesSize), - } - t.initLeaves() - - return t - -} - -func (fmt *FixedMerkleTree) initLeaves() { - fmt.Leaves = make([]Hashable, FixedMerkleLeaves) - for i := 0; i < FixedMerkleLeaves; i++ { - fmt.Leaves[i] = getNewLeaf() - } -} - -// writeToLeaves will divide the data with MerkleChunkSize(64 bytes) and write to -// each leaf hasher -func (fmt *FixedMerkleTree) writeToLeaves(b []byte) error { - if len(b) > MaxMerkleLeavesSize { - return goError.New("data size greater than maximum required size") - } - - if len(b) < MaxMerkleLeavesSize && !fmt.isFinal { - return goError.New("invalid merkle leaf write") - } - - leafInd := 0 - for i := 0; i < len(b); i += MerkleChunkSize { - j := i + MerkleChunkSize - if j > len(b) { - j = len(b) - } - - _, err := fmt.Leaves[leafInd].Write(b[i:j]) - if err != nil { - return err - } - leafInd++ - } - - return nil -} - -// Write will write data to the leaves once MaxMerkleLeavesSize(64 KB) is reached. -// Since each 64KB is divided into 1024 pieces with 64 bytes each, once data len reaches -// 64KB then it will be written to leaf hashes. The remaining data that is not multiple of -// 64KB will be written to leaf hashes by Finalize() function. -// This can be used to write stream of data as well. -// fmt.Finalize() is required after data write is complete. -func (fmt *FixedMerkleTree) Write(b []byte) (int, error) { - - fmt.writeLock.Lock() - defer fmt.writeLock.Unlock() - if fmt.isFinal { - return 0, goError.New("cannot write. Tree is already finalized") - } - - for i, j := 0, MaxMerkleLeavesSize-fmt.writeCount; i < len(b); i, j = j, j+MaxMerkleLeavesSize { - if j > len(b) { - j = len(b) - } - prevWriteCount := fmt.writeCount - fmt.writeCount += int(j - i) - copy(fmt.writeBytes[prevWriteCount:fmt.writeCount], b[i:j]) - - if fmt.writeCount == MaxMerkleLeavesSize { - // data fragment reached 64KB, so send this slice to write to leaf hashes - err := fmt.writeToLeaves(fmt.writeBytes) - if err != nil { - return 0, err - } - fmt.writeCount = 0 // reset writeCount - } - } - return len(b), nil -} - -// GetMerkleRoot is only for interface compliance. -func (fmt *FixedMerkleTree) GetMerkleTree() MerkleTreeI { - return nil -} - -func (fmt *FixedMerkleTree) CalculateMerkleRoot() { - nodes := make([][]byte, len(fmt.Leaves)) - for i := 0; i < len(nodes); i++ { - nodes[i] = fmt.Leaves[i].GetHashBytes() - leafPool.Put(fmt.Leaves[i]) - } - - for i := 0; i < FixedMTDepth; i++ { - - newNodes := make([][]byte, (len(nodes)+1)/2) - nodeInd := 0 - for j := 0; j < len(nodes); j += 2 { - newNodes[nodeInd] = MHashBytes(nodes[j], nodes[j+1]) - nodeInd++ - } - nodes = newNodes - if len(nodes) == 1 { - break - } - } - - fmt.merkleRoot = nodes[0] -} - -// FixedMerklePath is used to verify existence of leaf hash for fixed merkle tree -type FixedMerklePath struct { - LeafHash []byte `json:"leaf_hash"` - RootHash []byte `json:"root_hash"` - Nodes [][]byte `json:"nodes"` - LeafInd int -} - -func (fp FixedMerklePath) VerifyMerklePath() bool { - leafInd := fp.LeafInd - hash := fp.LeafHash - for i := 0; i < len(fp.Nodes); i++ { - if leafInd&1 == 0 { - hash = MHashBytes(hash, fp.Nodes[i]) - } else { - hash = MHashBytes(fp.Nodes[i], hash) - } - leafInd = leafInd / 2 - } - return bytes.Equal(hash, fp.RootHash) -} - -// GetMerkleRoot get merkle root. -func (fmt *FixedMerkleTree) GetMerkleRoot() string { - if fmt.merkleRoot != nil { - return hex.EncodeToString(fmt.merkleRoot) - } - fmt.CalculateMerkleRoot() - return hex.EncodeToString(fmt.merkleRoot) -} - -// Reload reset and reload leaves from io.Reader -func (fmt *FixedMerkleTree) Reload(reader io.Reader) error { - - fmt.initLeaves() - - bytesBuf := bytes.NewBuffer(make([]byte, 0, MaxMerkleLeavesSize)) - for i := 0; ; i++ { - written, err := io.CopyN(bytesBuf, reader, MaxMerkleLeavesSize) - - if written > 0 { - _, err = fmt.Write(bytesBuf.Bytes()) - bytesBuf.Reset() - - if err != nil { - return err - } - - } - - if err != nil { - if errors.Is(err, io.EOF) { - break - } - - return err - } - - } - - return nil -} diff --git a/core/util/fixed_merkle_tree_test.go b/core/util/fixed_merkle_tree_test.go deleted file mode 100644 index e5c265012..000000000 --- a/core/util/fixed_merkle_tree_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package util - -import ( - "math/rand" - "testing" - - "fmt" - - "github.com/stretchr/testify/require" -) - -const ( - KB = 1024 -) - -func TestFixedMerkleTreeWrite(t *testing.T) { - for i := 0; i < 100; i++ { - var n int64 - for { - n = rand.Int63n(KB * KB) - if n != 0 { - break - } - } - - t.Run(fmt.Sprintf("Fmt test with dataSize: %d", n), func(t *testing.T) { - - b := make([]byte, n) - rand.Read(b) //nolint - - leaves := make([]Hashable, FixedMerkleLeaves) - for i := 0; i < len(leaves); i++ { - leaves[i] = getNewLeaf() - } - - for i := 0; i < len(b); i += MaxMerkleLeavesSize { - leafCount := 0 - endInd := i + MaxMerkleLeavesSize - if endInd > len(b) { - endInd = len(b) - } - - d := b[i:endInd] - for j := 0; j < len(d); j += MerkleChunkSize { - endInd := j + MerkleChunkSize - if endInd > len(d) { - endInd = len(d) - } - - _, err := leaves[leafCount].Write(d[j:endInd]) - require.NoError(t, err) - leafCount++ - } - } - - mt := MerkleTree{} - mt.ComputeTree(leaves) - - root := mt.GetRoot() - - ft := NewFixedMerkleTree() - _, err := ft.Write(b) - require.NoError(t, err) - err = ft.Finalize() - require.NoError(t, err) - - root1 := ft.GetMerkleRoot() - require.Equal(t, root, root1) - }) - } -} diff --git a/core/util/http_consensus_maps.go b/core/util/http_consensus_maps.go deleted file mode 100644 index 6f95f3b3a..000000000 --- a/core/util/http_consensus_maps.go +++ /dev/null @@ -1,93 +0,0 @@ -package util - -import ( - "crypto/sha1" - "encoding/hex" - "encoding/json" - "errors" - "net/http" - "sort" - "strings" -) - -var ErrNilHttpConsensusMaps = errors.New("nil_httpconsensusmaps") - -type HttpConsensusMaps struct { - ConsensusThresh int - MaxConsensus int - - WinMap map[string]json.RawMessage - WinMapConsensus map[string]int - - WinError string - WinInfo string -} - -func NewHttpConsensusMaps(consensusThresh int) *HttpConsensusMaps { - return &HttpConsensusMaps{ - ConsensusThresh: consensusThresh, - WinMapConsensus: make(map[string]int), - } -} - -func (c *HttpConsensusMaps) GetValue(name string) (json.RawMessage, bool) { - if c == nil || c.WinMap == nil { - return nil, false - } - v, ok := c.WinMap[name] - return v, ok -} - -func (c *HttpConsensusMaps) Add(statusCode int, respBody string) error { - if c == nil { - return ErrNilHttpConsensusMaps - } - if statusCode != http.StatusOK { - c.WinError = respBody - return nil - } - - m, hash, err := c.buildMap(respBody) - if err != nil { - return err - } - - c.WinMapConsensus[hash]++ - - if c.WinMapConsensus[hash] > c.MaxConsensus { - c.MaxConsensus = c.WinMapConsensus[hash] - c.WinMap = m - c.WinInfo = respBody - } - - return nil -} - -func (c *HttpConsensusMaps) buildMap(respBody string) (map[string]json.RawMessage, string, error) { - var m map[string]json.RawMessage - err := json.Unmarshal([]byte(respBody), &m) - if err != nil { - return nil, "", err - } - - keys := make([]string, 0, len(m)) - - for k := range m { - - keys = append(keys, k) - } - sort.Strings(keys) - - sb := strings.Builder{} - - for _, k := range keys { - sb.Write(m[k]) - sb.WriteString(":") - } - - h := sha1.New() - h.Write([]byte(sb.String())) - hash := h.Sum(nil) - - return m, hex.EncodeToString(hash), nil -} diff --git a/core/util/httpnet.go b/core/util/httpnet.go deleted file mode 100644 index 0acf86135..000000000 --- a/core/util/httpnet.go +++ /dev/null @@ -1,178 +0,0 @@ -package util - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - "net/http" - "net/url" - "os" - "time" -) - -type GetRequest struct { - *PostRequest -} - -type GetResponse struct { - *PostResponse -} - -type PostRequest struct { - req *http.Request - ctx context.Context - cncl context.CancelFunc - url string -} - -type PostResponse struct { - Url string - StatusCode int - Status string - Body string -} - -type HttpClient interface { - Do(req *http.Request) (*http.Response, error) -} - -var Client HttpClient - -func getEnvAny(names ...string) string { - for _, n := range names { - if val := os.Getenv(n); val != "" { - return val - } - } - return "" -} - -func (pfe *proxyFromEnv) initialize() { - pfe.HTTPProxy = getEnvAny("HTTP_PROXY", "http_proxy") - pfe.HTTPSProxy = getEnvAny("HTTPS_PROXY", "https_proxy") - pfe.NoProxy = getEnvAny("NO_PROXY", "no_proxy") - - if pfe.NoProxy != "" { - return - } - - if pfe.HTTPProxy != "" { - pfe.http, _ = url.Parse(pfe.HTTPProxy) - } - if pfe.HTTPSProxy != "" { - pfe.https, _ = url.Parse(pfe.HTTPSProxy) - } -} - -type proxyFromEnv struct { - HTTPProxy string - HTTPSProxy string - NoProxy string - - http, https *url.URL -} - -var envProxy proxyFromEnv - -func init() { - Client = &http.Client{ - Transport: transport, - } - envProxy.initialize() -} - -func httpDo(req *http.Request, ctx context.Context, cncl context.CancelFunc, f func(*http.Response, error) error) error { - c := make(chan error, 1) - go func() { c <- f(Client.Do(req.WithContext(ctx))) }() - defer cncl() - select { - case <-ctx.Done(): - transport.CancelRequest(req) //nolint - <-c // Wait for f to return. - return ctx.Err() - case err := <-c: - return err - } -} - -// NewHTTPGetRequest create a GetRequest instance with 60s timeout -func NewHTTPGetRequest(url string) (*GetRequest, error) { - var ctx, cancel = context.WithTimeout(context.Background(), 60*time.Second) - go func() { - //call cancel to avoid memory leak here - <-ctx.Done() - - cancel() - - }() - - return NewHTTPGetRequestContext(ctx, url) -} - -// NewHTTPGetRequestContext create a GetRequest with context and url -func NewHTTPGetRequestContext(ctx context.Context, url string) (*GetRequest, error) { - - req, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json; charset=utf-8") - req.Header.Set("Access-Control-Allow-Origin", "*") - - gr := new(GetRequest) - gr.PostRequest = &PostRequest{} - gr.url = url - gr.req = req - gr.ctx, gr.cncl = context.WithCancel(ctx) - return gr, nil -} - -func NewHTTPPostRequest(url string, data interface{}) (*PostRequest, error) { - pr := &PostRequest{} - jsonByte, err := json.Marshal(data) - if err != nil { - return nil, err - } - req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonByte)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json; charset=utf-8") - req.Header.Set("Access-Control-Allow-Origin", "*") - pr.url = url - pr.req = req - pr.ctx, pr.cncl = context.WithTimeout(context.Background(), time.Second*60) - return pr, nil -} - -func (r *GetRequest) Get() (*GetResponse, error) { - response := &GetResponse{} - presp, err := r.Post() - response.PostResponse = presp - return response, err -} - -func (r *PostRequest) Post() (*PostResponse, error) { - result := &PostResponse{} - err := httpDo(r.req, r.ctx, r.cncl, func(resp *http.Response, err error) error { - if err != nil { - return err - } - if resp.Body != nil { - defer resp.Body.Close() - } - - rspBy, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - result.Url = r.url - result.StatusCode = resp.StatusCode - result.Status = resp.Status - result.Body = string(rspBy) - return nil - }) - return result, err -} diff --git a/core/util/merkle_tree.go b/core/util/merkle_tree.go deleted file mode 100644 index 93ac42e9f..000000000 --- a/core/util/merkle_tree.go +++ /dev/null @@ -1,148 +0,0 @@ -package util - -import ( - "fmt" -) - -/*MerkleTree - A data structure that implements MerkleTreeI interface */ -type MerkleTree struct { - tree []string - leavesCount int - levels int -} - -func VerifyMerklePath(hash string, path *MTPath, root string) bool { - mthash := hash - pathNodes := path.Nodes - pl := len(pathNodes) - idx := path.LeafIndex - for i := 0; i < pl; i++ { - if idx&1 == 1 { - mthash = MHash(pathNodes[i], mthash) - } else { - mthash = MHash(mthash, pathNodes[i]) - } - idx = (idx - idx&1) / 2 - } - return mthash == root -} - -func (mt *MerkleTree) computeSize(leaves int) (int, int) { - if leaves == 1 { - return 2, 2 - } - var tsize int - var levels int - for ll := leaves; ll > 1; ll = (ll + 1) / 2 { - tsize += ll - levels++ - } - tsize++ - levels++ - return tsize, levels -} - -/*ComputeTree - given the leaf nodes, compute the merkle tree */ -func (mt *MerkleTree) ComputeTree(hashes []Hashable) { - var tsize int - tsize, mt.levels = mt.computeSize(len(hashes)) - mt.leavesCount = len(hashes) - mt.tree = make([]string, tsize) - for idx, hashable := range hashes { - mt.tree[idx] = hashable.GetHash() - } - if len(hashes) == 1 { - mt.tree[1] = DecodeAndMHash(mt.tree[0], mt.tree[0]) - return - } - for pl0, plsize := 0, mt.leavesCount; plsize > 1; pl0, plsize = pl0+plsize, (plsize+1)/2 { - l0 := pl0 + plsize - for i, j := 0, 0; i < plsize; i, j = i+2, j+1 { - mt.tree[pl0+plsize+j] = DecodeAndMHash(mt.tree[pl0+i], mt.tree[pl0+i+1]) - } - if plsize&1 == 1 { - mt.tree[l0+plsize/2] = DecodeAndMHash(mt.tree[pl0+plsize-1], mt.tree[pl0+plsize-1]) - } - } -} - -/*GetRoot - get the root of the merkle tree */ -func (mt *MerkleTree) GetRoot() string { - return mt.tree[len(mt.tree)-1] -} - -/*GetTree - get the entire merkle tree */ -func (mt *MerkleTree) GetTree() []string { - return mt.tree -} - -/*SetTree - set the entire merkle tree */ -func (mt *MerkleTree) SetTree(leavesCount int, tree []string) error { - size, levels := mt.computeSize(leavesCount) - if size != len(tree) { - return fmt.Errorf("Merkle tree with leaves %v should have size %v but only %v is given", leavesCount, size, len(tree)) - } - mt.levels = levels - mt.tree = tree - mt.leavesCount = leavesCount - return nil -} - -/*GetLeafIndex - Get the index of the leaf node in the tree */ -func (mt *MerkleTree) GetLeafIndex(hash Hashable) int { - hs := hash.GetHash() - for i := 0; i < mt.leavesCount; i++ { - if mt.tree[i] == hs { - return i - } - } - return -1 -} - -/*GetPath - get the path that can be used to verify the merkle tree */ -func (mt *MerkleTree) GetPath(hash Hashable) *MTPath { - hidx := mt.GetLeafIndex(hash) - if hidx < 0 { - return &MTPath{} - } - return mt.GetPathByIndex(hidx) -} - -/*VerifyPath - given a leaf node and the path, verify that the node is part of the tree */ -func (mt *MerkleTree) VerifyPath(hash Hashable, path *MTPath) bool { - hs := hash.GetHash() - return VerifyMerklePath(hs, path, mt.GetRoot()) -} - -/*GetPathByIndex - get the path of a leaf node at index i */ -func (mt *MerkleTree) GetPathByIndex(idx int) *MTPath { - path := make([]string, mt.levels-1) - mpath := &MTPath{LeafIndex: idx} - if idx&1 == 1 { - path[0] = mt.tree[idx-1] - } else { - if idx+1 < mt.leavesCount { - path[0] = mt.tree[idx+1] - } else { - path[0] = mt.tree[idx] - } - } - for pl0, plsize, pi := 0, mt.leavesCount, 1; plsize > 2; pl0, plsize, pi = pl0+plsize, (plsize+1)/2, pi+1 { - l0 := pl0 + plsize - idx = (idx - idx&1) / 2 - if idx&1 == 1 { - //path = append(path, mt.tree[l0+idx-1]) - path[pi] = mt.tree[l0+idx-1] - } else { - if l0+idx+1 < l0+(plsize+1)/2 { - //path = append(path, mt.tree[l0+idx+1]) - path[pi] = mt.tree[l0+idx+1] - } else { - //path = append(path, mt.tree[l0+idx]) - path[pi] = mt.tree[l0+idx] - } - } - } - mpath.Nodes = path - return mpath -} diff --git a/core/util/merkle_tree_interface.go b/core/util/merkle_tree_interface.go deleted file mode 100644 index c6f809211..000000000 --- a/core/util/merkle_tree_interface.go +++ /dev/null @@ -1,83 +0,0 @@ -package util - -import ( - "encoding/hex" - - "github.com/0chain/gosdk_common/core/encryption" - "github.com/minio/sha256-simd" -) - -/*MerkleTreeI - a merkle tree interface required for constructing and providing verification */ -type MerkleTreeI interface { - //API to create a tree from leaf nodes - ComputeTree(hashes []Hashable) - GetRoot() string - GetTree() []string - - //API to load an existing tree - SetTree(leavesCount int, tree []string) error - - // API for verification when the leaf node is known - GetPath(hash Hashable) *MTPath // Server needs to provide this - VerifyPath(hash Hashable, path *MTPath) bool //This is only required by a client but useful for testing - - /* API for random verification when the leaf node is uknown - (verification of the data to hash used as leaf node is outside this API) */ - GetPathByIndex(idx int) *MTPath -} - -/*MTPath - The merkle tree path*/ -type MTPath struct { - Nodes []string `json:"nodes"` - LeafIndex int `json:"leaf_index"` -} - -/*Hash - the hashing used for the merkle tree construction */ -func Hash(text string) string { - return encryption.Hash(text) -} - -func MHashBytes(h1, h2 []byte) []byte { - buf := make([]byte, len(h1)+len(h2)) - copy(buf, h1) - copy(buf[len(h1):], h2) - hash := sha256.New() - _, _ = hash.Write(buf) - return hash.Sum(nil) -} - -/*MHash - merkle hashing of a pair of child hashes */ -func MHash(h1 string, h2 string) string { - return Hash(h1 + h2) -} - -// DecodeAndMHash will decode hex-encoded string to []byte format. -// This function should only be used with hex-encoded string otherwise the result will -// be obsolute. -func DecodeAndMHash(h1, h2 string) string { - b1, _ := hex.DecodeString(h1) - - b2, _ := hex.DecodeString(h2) - - b3 := MHashBytes(b1, b2) - return hex.EncodeToString(b3) -} - -type StringHashable struct { - Hash string -} - -func NewStringHashable(hash string) *StringHashable { - return &StringHashable{Hash: hash} -} - -func (sh *StringHashable) GetHash() string { - return sh.Hash -} -func (sh *StringHashable) GetHashBytes() []byte { - return []byte(sh.Hash) -} - -func (StringHashable) Write(_ []byte) (int, error) { - return 0, nil -} diff --git a/core/util/rand.go b/core/util/rand.go deleted file mode 100644 index 540c39bdb..000000000 --- a/core/util/rand.go +++ /dev/null @@ -1,115 +0,0 @@ -package util - -import ( - "errors" - "math/rand" - "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 - } - 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 - } - 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 - } - 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 - } - 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) - var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) - rnd.Shuffle(len(in), func(i, j int) { - shuffle[i], shuffle[j] = shuffle[j], shuffle[i] - }) - return -} - -// GetRandom returns n random slice from in -// If n > len(in), then this will return a shuffled version of in -func GetRandom(in []string, n int) []string { - n = MinInt(len(in), n) - out := make([]string, 0) - - rand.Seed(time.Now().UnixNano()) //nolint - perm := rand.Perm(len(in)) - for i := 0; i < n; i++ { - out = append(out, in[perm[i]]) - } - return out -} - -var ( - randGen = rand.New(rand.NewSource(time.Now().UnixNano())) - // ErrNoItem there is no item anymore - ErrNoItem = errors.New("rand: there is no item anymore") -) - -// Rand a progressive rand -type Rand struct { - items []int -} - -// Next get next random item -func (r *Rand) Next() (int, error) { - if len(r.items) > 0 { - i := randGen.Intn(len(r.items)) - - it := r.items[i] - - copy(r.items[i:], r.items[i+1:]) - r.items = r.items[:len(r.items)-1] - - return it, nil - } - - return -1, ErrNoItem - -} - -// NewRand create a ProgressiveRand instance -func NewRand(max int) Rand { - r := Rand{ - items: make([]int, max), - } - - for i := 0; i < max; i++ { - r.items[i] = i - } - - return r - -} diff --git a/core/util/rand_test.go b/core/util/rand_test.go deleted file mode 100644 index 04c7dc9bf..000000000 --- a/core/util/rand_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package util - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestGetRandomSlice(t *testing.T) { - s := []string{"hello", "world", "beuty"} - ns := GetRandom(s, 2) - if len(ns) != 2 { - t.Fatalf("Getrandom() failed") - } - ns = GetRandom(s, 4) - if len(ns) != 3 { - t.Fatalf("Getrandom() failed") - } - // Tests for when either len(in) = 0 or n = 0 - s = []string{} - ns = GetRandom(s, 2) - if len(ns) != 0 { - t.Fatalf("Getrandom() failed") - } - s = append(s, "hello") - ns = GetRandom(s, 0) - if len(ns) != 0 { - t.Fatalf("Getrandom() failed") - } -} - -func TestRand(t *testing.T) { - s := []string{"a", "b", "c", "d", "e", "f", "h", "i", "j", "k"} - - r := NewRand(len(s)) - - selected := make(map[int]string) - - for i := 0; i < len(s); i++ { - index, err := r.Next() - - require.Equal(t, nil, err) - - _, ok := selected[index] - - require.Equal(t, false, ok) - - selected[index] = s[index] - } - - for i := 0; i < len(s); i++ { - require.Equal(t, s[i], selected[i]) - } - - _, err := r.Next() - - require.Equal(t, ErrNoItem, err) - -} diff --git a/core/util/secure_value.go b/core/util/secure_value.go deleted file mode 100644 index 6f17be5e9..000000000 --- a/core/util/secure_value.go +++ /dev/null @@ -1,72 +0,0 @@ -package util - -import ( - "encoding/hex" - "strings" - - "github.com/0chain/gosdk_common/core/encryption" -) - -// 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) -} - -/*Serializable interface */ -type Serializable interface { - Encode() []byte - Decode([]byte) error -} - -/*HashStringToBytes - convert a hex hash string to bytes */ -func HashStringToBytes(hash string) []byte { - hashBytes, err := hex.DecodeString(hash) - if err != nil { - return nil - } - return hashBytes -} - -/*SecureSerializableValueI an interface that makes a serializable value secure with hashing */ -type SecureSerializableValueI interface { - Serializable - Hashable -} - -/*SecureSerializableValue - a proxy persisted value that just tracks the encoded bytes of a persisted value */ -type SecureSerializableValue struct { - Buffer []byte -} - -/*GetHash - implement interface */ -func (spv *SecureSerializableValue) GetHash() string { - return ToHex(spv.GetHashBytes()) -} - -/*ToHex - converts a byte array to hex encoding with upper case */ -func ToHex(buf []byte) string { - return strings.ToUpper(hex.EncodeToString(buf)) -} - -/*GetHashBytes - implement interface */ -func (spv *SecureSerializableValue) GetHashBytes() []byte { - return encryption.RawHash(spv.Buffer) -} - -/*Encode - implement interface */ -func (spv *SecureSerializableValue) Encode() []byte { - return spv.Buffer -} - -/*Decode - implement interface */ -func (spv *SecureSerializableValue) Decode(buf []byte) error { - spv.Buffer = buf - return nil -} diff --git a/core/util/transport.go b/core/util/transport.go deleted file mode 100644 index 28c39947b..000000000 --- a/core/util/transport.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package util - -import ( - "net" - "net/http" - "time" -) - -// Run the HTTP request in a goroutine and pass the response to f. -var transport = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - MaxIdleConns: 1000, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: 5, - ForceAttemptHTTP2: true, - - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, -} diff --git a/core/util/transport_wasm.go b/core/util/transport_wasm.go deleted file mode 100644 index 9e90f4f60..000000000 --- a/core/util/transport_wasm.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package util - -import ( - "net/http" - "time" -) - -// Run the HTTP request in a goroutine and pass the response to f. -var transport = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - MaxIdleConns: 1000, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: 5, - ForceAttemptHTTP2: true, -} diff --git a/core/util/uint64.go b/core/util/uint64.go deleted file mode 100644 index 414293c25..000000000 --- a/core/util/uint64.go +++ /dev/null @@ -1,19 +0,0 @@ -package util - -import ( - "fmt" - "strconv" -) - -func ParseCoinStr(vs string) (uint64, error) { - if vs == "" { - return 0, nil - } - - v, err := strconv.ParseUint(vs, 10, 64) - if err != nil { - return 0, fmt.Errorf("invalid token value: %v, err: %v", vs, err) - } - - return v, nil -} diff --git a/core/util/uuid.go b/core/util/uuid.go deleted file mode 100644 index b64b41481..000000000 --- a/core/util/uuid.go +++ /dev/null @@ -1,24 +0,0 @@ -package util - -import ( - "github.com/google/uuid" -) - -// GetSHA1Uuid will give version 5 uuid. It depends on already existing uuid. -// The main idea is to synchronize uuid among blobbers. So for example, if -// a file is being uploaded to 4 blobbers then we require that file in each blobber -// have same uuid. All the goroutine that assigns uuid, calculates hashes and commits to blobber -// will use initial version 1 uuid and updates the uuid with recently calculated uuid so that -// the file will get same uuid in all blobbers. -func GetSHA1Uuid(u uuid.UUID, name string) uuid.UUID { - return uuid.NewSHA1(u, []byte(name)) -} - -// GetNewUUID will give new version1 uuid. It will panic if any error occurred -func GetNewUUID() uuid.UUID { - uid, err := uuid.NewUUID() - if err != nil { - panic("could not get new uuid. Error: " + err.Error()) - } - return uid -} diff --git a/core/util/validation_tree.go b/core/util/validation_tree.go deleted file mode 100644 index db97880a9..000000000 --- a/core/util/validation_tree.go +++ /dev/null @@ -1,342 +0,0 @@ -package util - -import ( - "bytes" - "encoding/hex" - "errors" - "fmt" - "hash" - "math" - "sync" - - "github.com/minio/sha256-simd" -) - -const ( - // Left tree node chile - Left = iota - - // Right tree node child - Right -) - -const ( - START_LENGTH = 64 - ADD_LENGTH = 320 -) - -// ValidationTree is a merkle tree that is used to validate the data -type ValidationTree struct { - writeLock sync.Mutex - writeCount int - dataSize int64 - writtenSize int64 - leafIndex int - leaves [][]byte - isFinalized bool - h hash.Hash - 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 - } - v.calculateRoot() - 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() - - if v.isFinalized { - return 0, fmt.Errorf("tree is already finalized") - } - - if len(b) == 0 { - return 0, nil - } - - if v.dataSize > 0 && v.writtenSize+int64(len(b)) > v.dataSize { - return 0, fmt.Errorf("data size overflow. expected %d, got %d", v.dataSize, v.writtenSize+int64(len(b))) - } - - byteLen := len(b) - shouldContinue := true - // 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. - for i, j := 0, MaxMerkleLeavesSize-v.writeCount; shouldContinue; i, j = j, j+MaxMerkleLeavesSize { - if j > byteLen { - j = byteLen - shouldContinue = false - } - - n, _ := v.h.Write(b[i:j]) - v.writeCount += n // update write count - if v.writeCount == MaxMerkleLeavesSize { - if v.leafIndex >= len(v.leaves) { - // increase leaves size - leaves := make([][]byte, len(v.leaves)+ADD_LENGTH) - copy(leaves, v.leaves) - v.leaves = leaves - } - v.leaves[v.leafIndex] = v.h.Sum(nil) - v.leafIndex++ - v.writeCount = 0 // reset writeCount - v.h.Reset() // reset hasher - } - } - v.writtenSize += int64(byteLen) - 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 -} - -func (v *ValidationTree) calculateRoot() { - totalLeaves := len(v.leaves) - depth := v.CalculateDepth() - nodes := make([][]byte, totalLeaves) - copy(nodes, v.leaves) - h := sha256.New() - - for i := 0; i < depth; i++ { - if len(nodes) == 1 { - break - } - newNodes := make([][]byte, 0) - if len(nodes)%2 == 0 { - for j := 0; j < len(nodes); j += 2 { - h.Reset() - h.Write(nodes[j]) - h.Write(nodes[j+1]) - newNodes = append(newNodes, h.Sum(nil)) - } - } else { - for j := 0; j < len(nodes)-1; j += 2 { - h.Reset() - h.Write(nodes[j]) - h.Write(nodes[j+1]) - newNodes = append(newNodes, h.Sum(nil)) - } - h.Reset() - h.Write(nodes[len(nodes)-1]) - newNodes = append(newNodes, h.Sum(nil)) - } - nodes = newNodes - } - - 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() - - if v.isFinalized { - return errors.New("already finalized") - } - if v.dataSize > 0 && v.writtenSize != v.dataSize { - return fmt.Errorf("invalid size. Expected %d got %d", v.dataSize, v.writtenSize) - } - - v.isFinalized = true - - if v.writeCount > 0 { - if v.leafIndex == len(v.leaves) { - // increase leaves size - leaves := make([][]byte, len(v.leaves)+1) - copy(leaves, v.leaves) - v.leaves = leaves - } - v.leaves[v.leafIndex] = v.h.Sum(nil) - } else { - v.leafIndex-- - } - if v.leafIndex < len(v.leaves) { - v.leaves = v.leaves[:v.leafIndex+1] - } - 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 { - totalLeaves = START_LENGTH - } - return &ValidationTree{ - dataSize: dataSize, - h: sha256.New(), - leaves: make([][]byte, totalLeaves), - } -} - -// MerklePathForMultiLeafVerification is used to verify multiple blocks with single instance of -// merkle path. Usually client would request with counter incremented by 10. So if the block size -// is 64KB and counter is incremented by 10 then client is requesting 640 KB of data. Blobber can then -// provide sinlge merkle path instead of sending 10 merkle paths. -type MerklePathForMultiLeafVerification struct { - // RootHash that was signed by the client - RootHash []byte - // Nodes contains a slice for each merkle node level. Each slice contains hash that will - // be concatenated with the calculated hash from the level below. - // It is used together with field Index [][]int - // Length of Nodes will be according to number of blocks requested. If whole data is requested then - // blobber will send nil for Nodes i.e. length of Nodes will become zero. - Nodes [][][]byte `json:"nodes"` - // Index slice that determines whether to concatenate hash to left or right. - // It should have maximum of length 2 and minimum of 0. It is used together with field Nodes [][][]byte - Index [][]int `json:"index"` - // DataSize is size of data received by the blobber for the respective file. - // It is not same as actual file size - DataSize int64 - totalLeaves int - requiredDepth int -} - -/* -VerifyMultipleBlocks will verify merkle path for continuous data which is multiple of 64KB blocks - -There can be at most 2 hashes in the input for each depth i.e. of the format below: -h1, data1, data2, data3, data4, h2 -Note that data1, data2, data3,... should be continuous data - -i#3 h14 -i#2 h12 h13 -i#1 h7 h8 h9 h10 -i#0 h0, h1, h2, h3, h4, h5, h6 - -Consider there are 7 leaves(0...6) as shown above. Now if client wants data from -1-3 then blobber needs to provide: - -1. One node from i#0, [h0]; data1 will generate h1,data2 will generate h2 and so on... -2. Zero node from i#1; h0 and h1 will generate h7 and h2 and h3 will generate h8 -3. One node from i#2, h[13]; h7 and h8 will generate h12. Now to get h14, we need h13 -which will be provided by blobber - -i#5 h37 -i#4 h35 h36 -i#3 h32 h33 h34 -i#2 h27 h28 h29 h30 h31 -i#1 h18 h19 h20 h21 h22 h23 h24 h25, h26 -i#0 h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13, h14, h15, h16, h17 - -Consider there are 16 leaves(0..15) with total data = 16*64KB as shown above. -If client wants data from 3-10 then blobber needs to provide: -1. Two nodes from i#0, [h2, h11] -2. One node from i#1, [h16] -3. One node from i#2, [h27] - -If client had required data from 2-9 then blobber would have to provide: -1. Zero nodes from i#0 -2. Two nodes from i#1, [h16, h21] -3. One node from i#2, [h27] -*/ -func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) error { - - hashes := make([][]byte, 0) - h := sha256.New() - // Calculate hashes from the data responded from the blobber. - for i := 0; i < len(data); i += MaxMerkleLeavesSize { - endIndex := i + MaxMerkleLeavesSize - if endIndex > len(data) { - endIndex = len(data) - } - h.Reset() - h.Write(data[i:endIndex]) - hashes = append(hashes, h.Sum(nil)) - } - - if m.requiredDepth == 0 { - m.calculateRequiredLevels() - } - for i := 0; i < m.requiredDepth-1; i++ { - if len(m.Nodes) > i { - if len(m.Index[i]) == 2 { // has both nodes to append for - hashes = append([][]byte{m.Nodes[i][0]}, hashes...) - hashes = append(hashes, m.Nodes[i][1]) - } else if len(m.Index[i]) == 1 { // hash single node to append for - if m.Index[i][0] == Right { // append to right - hashes = append(hashes, m.Nodes[i][0]) - } else { - hashes = append([][]byte{m.Nodes[i][0]}, hashes...) - } - } - } - - hashes = m.calculateIntermediateHashes(hashes) - - } - - if len(hashes) == 0 { - return fmt.Errorf("no hashes to verify, data is empty") - } - - if !bytes.Equal(m.RootHash, hashes[0]) { - return fmt.Errorf("calculated root %s; expected %s", - hex.EncodeToString(hashes[0]), - hex.EncodeToString(m.RootHash)) - } - return nil -} - -func (m *MerklePathForMultiLeafVerification) calculateIntermediateHashes(hashes [][]byte) [][]byte { - newHashes := make([][]byte, 0) - h := sha256.New() - if len(hashes)%2 == 0 { - for i := 0; i < len(hashes); i += 2 { - h.Reset() - h.Write(hashes[i]) - h.Write(hashes[i+1]) - newHashes = append(newHashes, h.Sum(nil)) - } - } else { - for i := 0; i < len(hashes)-1; i += 2 { - h.Reset() - h.Write(hashes[i]) - h.Write(hashes[i+1]) - newHashes = append(newHashes, h.Sum(nil)) - } - h.Reset() - h.Write(hashes[len(hashes)-1]) - newHashes = append(newHashes, h.Sum(nil)) - } - return newHashes -} - -func (m *MerklePathForMultiLeafVerification) calculateTotalLeaves() { - m.totalLeaves = int((m.DataSize + MaxMerkleLeavesSize - 1) / MaxMerkleLeavesSize) -} - -func (m *MerklePathForMultiLeafVerification) calculateRequiredLevels() { - if m.totalLeaves == 0 { - m.calculateTotalLeaves() - } - m.requiredDepth = int(math.Ceil(math.Log2(float64(m.totalLeaves)))) + 1 // Add root hash to be a level -} diff --git a/core/util/validation_tree_test.go b/core/util/validation_tree_test.go deleted file mode 100644 index 149aba444..000000000 --- a/core/util/validation_tree_test.go +++ /dev/null @@ -1,331 +0,0 @@ -package util - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "math" - "testing" - - "github.com/minio/sha256-simd" - "github.com/stretchr/testify/require" -) - -const ( - HashSize = 32 -) - -func TestValidationTreeWrite(t *testing.T) { - dataSizes := []int64{ - MaxMerkleLeavesSize, - MaxMerkleLeavesSize - 24*KB, - MaxMerkleLeavesSize * 2, - MaxMerkleLeavesSize * 3, - MaxMerkleLeavesSize*10 - 1, - } - - for _, s := range dataSizes { - data := make([]byte, s) - n, err := rand.Read(data) - require.NoError(t, err) - require.EqualValues(t, s, n) - - root := calculateValidationMerkleRoot(data) - - vt := NewValidationTree(s) - diff := 1 - i := len(data) - diff - - _, err = vt.Write(data[0:i]) - require.NoError(t, err) - vt.calculateRoot() - - require.False(t, bytes.Equal(root, vt.validationRoot)) - - _, err = vt.Write(data[i:]) - require.NoError(t, err) - - err = vt.Finalize() - require.NoError(t, err) - - vt.calculateRoot() - require.True(t, bytes.Equal(root, vt.validationRoot)) - - require.Error(t, vt.Finalize()) - } -} - -func TestValidationTreeCalculateDepth(t *testing.T) { - in := map[int]int{ - 1: 1, - 2: 2, - 3: 3, - 4: 3, - 10: 5, - 100: 8, - } - - for k, d := range in { - v := ValidationTree{leaves: make([][]byte, k)} - require.Equal(t, v.CalculateDepth(), d) - } -} - -func TestMerklePathVerificationForValidationTree(t *testing.T) { - - type input struct { - dataSize int64 - startInd int - endInd int - } - - tests := []*input{ - { - dataSize: 24 * KB, - startInd: 0, - endInd: 0, - }, - { - dataSize: 340 * KB, - startInd: 1, - endInd: 3, - }, - { - dataSize: 640 * KB, - startInd: 1, - endInd: 4, - }, - { - dataSize: 640*KB + 1, - startInd: 1, - endInd: 5, - }, - } - - for _, test := range tests { - t.Run(fmt.Sprintf("Data size: %d KB, startInd: %d, endInd:%d", - test.dataSize/KB, - test.startInd, - test.endInd, - ), func(t *testing.T) { - - b := make([]byte, test.dataSize) - n, err := rand.Read(b) - - require.NoError(t, err) - require.EqualValues(t, test.dataSize, n) - - root, nodes, indexes, data, err := calculateValidationRootAndNodes(b, test.startInd, test.endInd) - require.NoError(t, err) - - t.Logf("nodes len: %d; index len: %d, indexes: %v", len(nodes), len(indexes), indexes) - vp := MerklePathForMultiLeafVerification{ - RootHash: root, - Nodes: nodes, - Index: indexes, - DataSize: test.dataSize, - } - - err = vp.VerifyMultipleBlocks(data) - require.NoError(t, err) - - err = vp.VerifyMultipleBlocks(data[1:]) - require.Error(t, err) - }) - - } -} - -func calculateValidationMerkleRoot(data []byte) []byte { - hashes := make([][]byte, 0) - for i := 0; i < len(data); i += MaxMerkleLeavesSize { - j := i + MaxMerkleLeavesSize - if j > len(data) { - j = len(data) - } - h := sha256.New() - _, _ = h.Write(data[i:j]) - hashes = append(hashes, h.Sum(nil)) - } - - if len(hashes) == 1 { - return hashes[0] - } - for len(hashes) != 1 { - newHashes := make([][]byte, 0) - if len(hashes)%2 == 0 { - for i := 0; i < len(hashes); i += 2 { - h := sha256.New() - _, _ = h.Write(hashes[i]) - _, _ = h.Write(hashes[i+1]) - newHashes = append(newHashes, h.Sum(nil)) - } - } else { - for i := 0; i < len(hashes)-1; i += 2 { - h := sha256.New() - _, _ = h.Write(hashes[i]) - _, _ = h.Write(hashes[i+1]) - newHashes = append(newHashes, h.Sum(nil)) - } - h := sha256.New() - _, _ = h.Write(hashes[len(hashes)-1]) - newHashes = append(newHashes, h.Sum(nil)) - } - - hashes = newHashes - } - return hashes[0] -} - -func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( - root []byte, nodes [][][]byte, indexes [][]int, data []byte, err error, -) { - - totalLeaves := int(math.Ceil(float64(len(b)) / float64(MaxMerkleLeavesSize))) - depth := int(math.Ceil(math.Log2(float64(totalLeaves)))) + 1 - - if endInd >= totalLeaves { - endInd = totalLeaves - 1 - } - - hashes := make([][]byte, 0) - nodesData := make([]byte, 0) - h := sha256.New() - for i := 0; i < len(b); i += MaxMerkleLeavesSize { - j := i + MaxMerkleLeavesSize - if j > len(b) { - j = len(b) - } - - _, _ = h.Write(b[i:j]) - leafHash := h.Sum(nil) - hashes = append(hashes, leafHash) - h.Reset() - } - - if len(hashes) == 1 { - return hashes[0], nil, nil, b, nil - } - - for len(hashes) != 1 { - newHashes := make([][]byte, 0) - if len(hashes)%2 == 0 { - for i := 0; i < len(hashes); i += 2 { - h := sha256.New() - _, _ = h.Write(hashes[i]) - _, _ = h.Write(hashes[i+1]) - nodesData = append(nodesData, hashes[i]...) - nodesData = append(nodesData, hashes[i+1]...) - newHashes = append(newHashes, h.Sum(nil)) - } - } else { - for i := 0; i < len(hashes)-1; i += 2 { - h := sha256.New() - _, _ = h.Write(hashes[i]) - _, _ = h.Write(hashes[i+1]) - nodesData = append(nodesData, hashes[i]...) - nodesData = append(nodesData, hashes[i+1]...) - newHashes = append(newHashes, h.Sum(nil)) - } - h := sha256.New() - _, _ = h.Write(hashes[len(hashes)-1]) - nodesData = append(nodesData, hashes[len(hashes)-1]...) - newHashes = append(newHashes, h.Sum(nil)) - } - - hashes = newHashes - } - - nodes, indexes, err = getMerkleProofOfMultipleIndexes(nodesData, totalLeaves, depth, startInd, endInd) - if err != nil { - return nil, nil, nil, nil, err - } - - startOffset := startInd * 64 * KB - endOffset := startOffset + (endInd-startInd+1)*64*KB - if endOffset > len(b) { - endOffset = len(b) - } - - return hashes[0], nodes, indexes, b[startOffset:endOffset], nil -} - -func getMerkleProofOfMultipleIndexes(nodesData []byte, totalLeaves, depth, startInd, endInd int) ( - [][][]byte, [][]int, error) { - - if endInd >= totalLeaves { - endInd = totalLeaves - 1 - } - - if endInd < startInd { - return nil, nil, errors.New("end index cannot be lesser than start index") - } - - offsets, leftRightIndexes := getFileOffsetsAndNodeIndexes(totalLeaves, depth, startInd, endInd) - - offsetInd := 0 - nodeHashes := make([][][]byte, len(leftRightIndexes)) - for i, indexes := range leftRightIndexes { - for range indexes { - b := make([]byte, HashSize) - off := offsets[offsetInd] - n := copy(b, nodesData[off:off+HashSize]) - if n != HashSize { - return nil, nil, errors.New("invalid hash length") - } - nodeHashes[i] = append(nodeHashes[i], b) - offsetInd++ - } - } - return nodeHashes, leftRightIndexes, nil -} - -func getFileOffsetsAndNodeIndexes(totalLeaves, depth, startInd, endInd int) ([]int, [][]int) { - - nodeIndexes, leftRightIndexes := getNodeIndexes(totalLeaves, depth, startInd, endInd) - offsets := make([]int, 0) - totalNodes := 0 - curNodesTot := totalLeaves - for i := 0; i < len(nodeIndexes); i++ { - for _, ind := range nodeIndexes[i] { - offsetInd := ind + totalNodes - offsets = append(offsets, offsetInd*HashSize) - } - totalNodes += curNodesTot - curNodesTot = (curNodesTot + 1) / 2 - } - - return offsets, leftRightIndexes -} - -func getNodeIndexes(totalLeaves, depth, startInd, endInd int) ([][]int, [][]int) { - - indexes := make([][]int, 0) - leftRightIndexes := make([][]int, 0) - totalNodes := totalLeaves - for i := depth - 1; i >= 0; i-- { - if startInd == 0 && endInd == totalNodes-1 { - break - } - - nodeOffsets := make([]int, 0) - lftRtInd := make([]int, 0) - if startInd&1 == 1 { - nodeOffsets = append(nodeOffsets, startInd-1) - lftRtInd = append(lftRtInd, Left) - } - - if endInd != totalNodes-1 && endInd&1 == 0 { - nodeOffsets = append(nodeOffsets, endInd+1) - lftRtInd = append(lftRtInd, Right) - } - - indexes = append(indexes, nodeOffsets) - leftRightIndexes = append(leftRightIndexes, lftRtInd) - startInd = startInd / 2 - endInd = endInd / 2 - totalNodes = (totalNodes + 1) / 2 - } - return indexes, leftRightIndexes -} diff --git a/core/version/.emptydir b/core/version/.emptydir deleted file mode 100644 index e69de29bb..000000000 diff --git a/core/version/doc.go b/core/version/doc.go deleted file mode 100644 index 04305704b..000000000 --- a/core/version/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// AUTOGENERATED! Do not use. -// Provide current version of the SDK -package version \ No newline at end of file diff --git a/core/version/version.go b/core/version/version.go deleted file mode 100644 index 9213a1e29..000000000 --- a/core/version/version.go +++ /dev/null @@ -1,5 +0,0 @@ -//====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== - -package version - -const VERSIONSTR = "v1.16.3-10-g66360b13" diff --git a/core/zcncrypto/bls.go b/core/zcncrypto/bls.go deleted file mode 100644 index 80ea65a4e..000000000 --- a/core/zcncrypto/bls.go +++ /dev/null @@ -1,66 +0,0 @@ -package zcncrypto - -import "io" - -var BlsSignerInstance BlsSigner - -type BlsSigner interface { - SetRandFunc(randReader io.Reader) - FrSub(out Fr, x Fr, y Fr) - - NewFr() Fr - NewSecretKey() SecretKey - NewPublicKey() PublicKey - NewSignature() Signature - NewID() ID -} - -// Fr -- -type Fr interface { - Serialize() []byte - - SetLittleEndian(buf []byte) error -} - -type SecretKey interface { - SerializeToHexStr() string - DeserializeHexStr(s string) error - - Serialize() []byte - - GetLittleEndian() []byte - SetLittleEndian(buf []byte) error - - SetByCSPRNG() - - GetPublicKey() PublicKey - - Sign(m string) Signature - Add(rhs SecretKey) - - GetMasterSecretKey(k int) (msk []SecretKey, err error) - Set(msk []SecretKey, id ID) error -} - -type PublicKey interface { - SerializeToHexStr() string - DeserializeHexStr(s string) error - - Serialize() []byte -} - -type Signature interface { - SerializeToHexStr() string - DeserializeHexStr(s string) error - - Add(rhs Signature) - - Verify(pk PublicKey, m string) bool -} - -type ID interface { - SetHexString(s string) error - GetHexString() string - - SetDecString(s string) error -} diff --git a/core/zcncrypto/bls0chain_herumi.go b/core/zcncrypto/bls0chain_herumi.go deleted file mode 100644 index 4c07bf5e7..000000000 --- a/core/zcncrypto/bls0chain_herumi.go +++ /dev/null @@ -1,310 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package zcncrypto - -import ( - "bytes" - "encoding/hex" - "fmt" - "time" - - "github.com/0chain/errors" - "github.com/tyler-smith/go-bip39" - - "github.com/0chain/gosdk_common/core/encryption" -) - -func init() { - -} - -// HerumiScheme - a signature scheme for BLS0Chain Signature -type HerumiScheme struct { - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` - Mnemonic string `json:"mnemonic"` - - id ID - Ids string `json:"threshold_scheme_id"` -} - -// NewHerumiScheme - create a MiraclScheme object -func NewHerumiScheme() *HerumiScheme { - return &HerumiScheme{ - id: BlsSignerInstance.NewID(), - } -} - -// GenerateKeys generate fresh keys -func (b0 *HerumiScheme) GenerateKeys() (*Wallet, error) { - return b0.generateKeys("0chain-client-split-key") -} - -// GenerateKeysWithEth generate fresh keys based on eth wallet -func (b0 *HerumiScheme) GenerateKeysWithEth(mnemonic, password string) (*Wallet, error) { - if len(mnemonic) == 0 { - return nil, fmt.Errorf("Mnemonic phase is mandatory.") - } - b0.Mnemonic = mnemonic - - _, err := bip39.NewSeedWithErrorChecking(b0.Mnemonic, password) - if err != nil { - return nil, fmt.Errorf("Wrong mnemonic phase.") - } - - return b0.generateKeys(password) -} - -// RecoverKeys recovery keys from mnemonic -func (b0 *HerumiScheme) RecoverKeys(mnemonic string) (*Wallet, error) { - if mnemonic == "" { - return nil, errors.New("recover_keys", "Set mnemonic key failed") - } - if b0.PublicKey != "" || b0.PrivateKey != "" { - return nil, errors.New("recover_keys", "Cannot recover when there are keys") - } - b0.Mnemonic = mnemonic - return b0.GenerateKeys() -} - -func (b0 *HerumiScheme) GetMnemonic() string { - if b0 == nil { - return "" - } - - return b0.Mnemonic -} - -// SetPrivateKey set private key to sign -func (b0 *HerumiScheme) SetPrivateKey(privateKey string) error { - if b0.PublicKey != "" { - return errors.New("set_private_key", "cannot set private key when there is a public key") - } - if b0.PrivateKey != "" { - return errors.New("set_private_key", "private key already exists") - } - b0.PrivateKey = privateKey - //ToDo: b0.publicKey should be set here? - return nil -} - -func (b0 *HerumiScheme) GetPrivateKey() string { - return b0.PrivateKey -} - -func (b0 *HerumiScheme) SplitKeys(numSplits int) (*Wallet, error) { - if b0.PrivateKey == "" { - return nil, errors.New("split_keys", "primary private key not found") - } - primaryFr := BlsSignerInstance.NewFr() - primarySk := BlsSignerInstance.NewSecretKey() - err := primarySk.DeserializeHexStr(b0.PrivateKey) - if err != nil { - return nil, err - } - err = primaryFr.SetLittleEndian(primarySk.GetLittleEndian()) - - if err != nil { - return nil, err - } - - // New Wallet - w := &Wallet{} - w.Keys = make([]KeyPair, numSplits) - sk := BlsSignerInstance.NewSecretKey() - for i := 0; i < numSplits-1; i++ { - tmpSk := BlsSignerInstance.NewSecretKey() - tmpSk.SetByCSPRNG() - w.Keys[i].PrivateKey = tmpSk.SerializeToHexStr() - pub := tmpSk.GetPublicKey() - w.Keys[i].PublicKey = pub.SerializeToHexStr() - sk.Add(tmpSk) - } - aggregateSk := BlsSignerInstance.NewFr() - err = aggregateSk.SetLittleEndian(sk.GetLittleEndian()) - - if err != nil { - return nil, err - } - - //Subtract the aggregated private key from the primary private key to derive the last split private key - lastSk := BlsSignerInstance.NewFr() - BlsSignerInstance.FrSub(lastSk, primaryFr, aggregateSk) - - // Last key - lastSecretKey := BlsSignerInstance.NewSecretKey() - err = lastSecretKey.SetLittleEndian(lastSk.Serialize()) - if err != nil { - return nil, err - } - w.Keys[numSplits-1].PrivateKey = lastSecretKey.SerializeToHexStr() - w.Keys[numSplits-1].PublicKey = lastSecretKey.GetPublicKey().SerializeToHexStr() - - // Generate client ID and public - w.ClientKey = primarySk.GetPublicKey().SerializeToHexStr() - w.ClientID = encryption.Hash(primarySk.GetPublicKey().Serialize()) - w.Mnemonic = b0.Mnemonic - w.Version = CryptoVersion - w.DateCreated = time.Now().Format(time.RFC3339) - - return w, nil -} - -// Sign sign message -func (b0 *HerumiScheme) Sign(hash string) (string, error) { - sig, err := b0.rawSign(hash) - if err != nil { - return "", err - } - return sig.SerializeToHexStr(), nil -} - -// SetPublicKey - implement interface -func (b0 *HerumiScheme) SetPublicKey(publicKey string) error { - if b0.PrivateKey != "" { - return errors.New("set_public_key", "cannot set public key when there is a private key") - } - if b0.PublicKey != "" { - return errors.New("set_public_key", "public key already exists") - } - b0.PublicKey = publicKey - return nil -} - -// GetPublicKey - implement interface -func (b0 *HerumiScheme) GetPublicKey() string { - return b0.PublicKey -} - -// Verify - implement interface -func (b0 *HerumiScheme) Verify(signature, msg string) (bool, error) { - if b0.PublicKey == "" { - return false, errors.New("verify", "public key does not exists for verification") - } - sig := BlsSignerInstance.NewSignature() - pk := BlsSignerInstance.NewPublicKey() - err := sig.DeserializeHexStr(signature) - if err != nil { - return false, err - } - rawHash, err := hex.DecodeString(msg) - if err != nil { - return false, err - } - if rawHash == nil { - return false, errors.New("verify", "failed hash while signing") - } - err = pk.DeserializeHexStr(b0.PublicKey) - if err != nil { - return false, err - } - - return sig.Verify(pk, string(rawHash)), nil -} - -func (b0 *HerumiScheme) Add(signature, msg string) (string, error) { - sign := BlsSignerInstance.NewSignature() - err := sign.DeserializeHexStr(signature) - if err != nil { - return "", err - } - signature1, err := b0.rawSign(msg) - if err != nil { - return "", errors.Wrap(err, "BLS signing failed") - } - sign.Add(signature1) - return sign.SerializeToHexStr(), nil -} - -// GetPrivateKeyAsByteArray - converts private key into byte array -func (b0 *HerumiScheme) GetPrivateKeyAsByteArray() ([]byte, error) { - if len(b0.PrivateKey) == 0 { - return nil, errors.New("get_private_key_as_byte_array", "cannot convert empty private key to byte array") - } - privateKeyBytes, err := hex.DecodeString(b0.PrivateKey) - if err != nil { - return nil, err - } - return privateKeyBytes, nil -} - -// SetID sets ID in HexString format -func (b0 *HerumiScheme) SetID(id string) error { - if b0.id == nil { - b0.id = BlsSignerInstance.NewID() - } - b0.Ids = id - return b0.id.SetHexString(id) -} - -// GetID gets ID in hex string format -func (b0 *HerumiScheme) GetID() string { - if b0.id == nil { - b0.id = BlsSignerInstance.NewID() - } - return b0.id.GetHexString() -} - -func (b0 *HerumiScheme) generateKeys(password string) (*Wallet, error) { - // Check for recovery - if len(b0.Mnemonic) == 0 { - entropy, err := bip39.NewEntropy(256) - if err != nil { - return nil, errors.Wrap(err, "Generating entropy failed") - } - b0.Mnemonic, err = bip39.NewMnemonic(entropy) - if err != nil { - return nil, errors.Wrap(err, "Generating mnemonic failed") - } - } - - // Generate a Bip32 HD wallet for the mnemonic and a user supplied password - seed := bip39.NewSeed(b0.Mnemonic, password) - r := bytes.NewReader(seed) - BlsSignerInstance.SetRandFunc(r) - - // New Wallet - w := &Wallet{} - w.Keys = make([]KeyPair, 1) - - // Generate pair - sk := BlsSignerInstance.NewSecretKey() - sk.SetByCSPRNG() - w.Keys[0].PrivateKey = sk.SerializeToHexStr() - pub := sk.GetPublicKey() - w.Keys[0].PublicKey = pub.SerializeToHexStr() - - b0.PrivateKey = w.Keys[0].PrivateKey - b0.PublicKey = w.Keys[0].PublicKey - w.ClientKey = w.Keys[0].PublicKey - w.ClientID = encryption.Hash(pub.Serialize()) - w.Mnemonic = b0.Mnemonic - w.Version = CryptoVersion - w.DateCreated = time.Now().Format(time.RFC3339) - - // Revert the Random function to default - BlsSignerInstance.SetRandFunc(nil) - return w, nil -} - -func (b0 *HerumiScheme) rawSign(hash string) (Signature, error) { - sk := BlsSignerInstance.NewSecretKey() - if b0.PrivateKey == "" { - return nil, errors.New("raw_sign", "private key does not exists for signing") - } - rawHash, err := hex.DecodeString(hash) - if err != nil { - return nil, err - } - if rawHash == nil { - return nil, errors.New("raw_sign", "failed hash while signing") - } - sk.SetByCSPRNG() - err = sk.DeserializeHexStr(b0.PrivateKey) - if err != nil { - return nil, err - } - sig := sk.Sign(string(rawHash)) - return sig, nil -} diff --git a/core/zcncrypto/bls0chain_herumi_test.go b/core/zcncrypto/bls0chain_herumi_test.go deleted file mode 100644 index f5a54ec56..000000000 --- a/core/zcncrypto/bls0chain_herumi_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package zcncrypto - -import ( - "fmt" - "testing" - - "github.com/0chain/errors" - "github.com/stretchr/testify/require" - - "github.com/0chain/gosdk_common/core/encryption" -) - -var verifyPublickey = `e8a6cfa7b3076ae7e04764ffdfe341632a136b52953dfafa6926361dd9a466196faecca6f696774bbd64b938ff765dbc837e8766a5e2d8996745b2b94e1beb9e` -var signPrivatekey = `5e1fc9c03d53a8b9a63030acc2864f0c33dffddb3c276bf2b3c8d739269cc018` -var data = `TEST` -var blsWallet *Wallet - -func TestSignatureScheme(t *testing.T) { - sigScheme := &HerumiScheme{} - - w, err := sigScheme.GenerateKeys() - if err != nil { - t.Fatalf("Generate Key failed %s", errors.Top(err)) - } - if w.ClientID == "" || w.ClientKey == "" || len(w.Keys) != 1 || w.Mnemonic == "" { - t.Fatalf("Invalid keys generated") - } - blsWallet = w - -} - -func TestSSSignAndVerify(t *testing.T) { - signScheme := NewSignatureScheme("bls0chain") - err := signScheme.SetPrivateKey(signPrivatekey) - - require.NoError(t, err) - - hash := Sha3Sum256(data) - signature, err := signScheme.Sign(hash) - if err != nil { - t.Fatalf("BLS signing failed") - } - verifyScheme := NewSignatureScheme("bls0chain") - err = verifyScheme.SetPublicKey(verifyPublickey) - require.NoError(t, err) - if ok, err := verifyScheme.Verify(signature, hash); err != nil || !ok { - t.Fatalf("Verification failed\n") - } -} - -func TestSSA(t *testing.T) { - signScheme := NewSignatureScheme("bls0chain") - err := signScheme.SetPrivateKey("f482aa19d3a3f6cebcd4f8a99de292bcf4bf07e937be1350634086f4aa02e704") - - require.NoError(t, err) - - hash := Sha3Sum256("hello") - signature, err := signScheme.Sign(hash) - if err != nil { - t.Fatalf("BLS signing failed") - } - fmt.Println(signature) - // verifyScheme := NewSignatureScheme("bls0chain") - // err = verifyScheme.SetPublicKey(verifyPublickey) - // require.NoError(t, err) - // if ok, err := verifyScheme.Verify(signature, hash); err != nil || !ok { - // t.Fatalf("Verification failed\n") - // } -} - -func TestVerify(t *testing.T) { - sk := "a931522f9949ff26b22db98b26e59cc92258457965f13ce6113cc2b5d2165513" - hash := "eb82aa875b3298ae7e625d8d8f13475004a4942bd8fcd7285e8ab9ad20651872" - sm := NewSignatureScheme("bls0chain") - if err2 := sm.SetPrivateKey(sk); err2 != nil { - t.Error(err2) - } - sig, _ := sm.Sign(hash) - fmt.Println("now sig:", sig) - - pk := "47e94b6c5399f8c0005c6f3202dec43e37d171b0eff24d75cdcf14861f088106cf88df15b3335dcd0806365db4d1b3e70579a8bd82eb665c881ef2273d6bdd03" - verifyScheme := NewSignatureScheme("bls0chain") - if err := verifyScheme.SetPublicKey(pk); err != nil { - t.Error(err) - } - ok, err := verifyScheme.Verify(sig, hash) - require.NoError(t, err) - fmt.Println("verify result:", ok) -} - -func BenchmarkBLSSign(b *testing.B) { - sigScheme := NewSignatureScheme("bls0chain") - err := sigScheme.SetPrivateKey(signPrivatekey) - require.NoError(b, err) - for i := 0; i < b.N; i++ { - _, err := sigScheme.Sign(encryption.Hash(data)) - if err != nil { - b.Fatalf("BLS signing failed") - } - } -} - -func TestRecoveryKeys(t *testing.T) { - - sigScheme := &HerumiScheme{} - - w, err := sigScheme.RecoverKeys(testMnemonic) - if err != nil { - t.Fatalf("set Recover Keys failed") - } - - require.Equal(t, testHerumiPrivateKey, w.Keys[0].PrivateKey, "Recover key didn't match with private key") - require.Equal(t, testHerumiPublicKey, w.Keys[0].PublicKey, "Recover key didn't match with public key") -} - -func TestCombinedSignAndVerify(t *testing.T) { - sk0 := `c36f2f92b673cf057a32e8bd0ca88888e7ace40337b737e9c7459fdc4c521918` - sk1 := `704b6f489583bf1118432fcfb38e63fc2d4b61e524fb196cbd95413f8eb91c12` - primaryKey := `f72fd53ee85e84157d3106053754594f697e0bfca1f73f91a41f7bb0797d901acefd80fcc2da98aae690af0ee9c795d6590c1808f26490306433b4e9c42f7b1f` - - hash := Sha3Sum256(data) - // Create signatue for 1 - sig0 := NewSignatureScheme("bls0chain") - err := sig0.SetPrivateKey(sk0) - if err != nil { - t.Fatalf("Set private key failed - %s", errors.Top(err)) - } - signature, err := sig0.Sign(hash) - if err != nil { - t.Fatalf("BLS signing failed") - } - // Create signature for second - sig1 := NewSignatureScheme("bls0chain") - err = sig1.SetPrivateKey(sk1) - if err != nil { - t.Fatalf("Set private key failed - %s", errors.Top(err)) - } - addSig, err := sig1.Add(signature, hash) - - require.NoError(t, err) - - verifyScheme := NewSignatureScheme("bls0chain") - err = verifyScheme.SetPublicKey(primaryKey) - if err != nil { - t.Fatalf("Set public key failed") - } - if ok, err := verifyScheme.Verify(addSig, hash); err != nil || !ok { - t.Fatalf("Verification failed\n") - } -} - -func TestSplitKey(t *testing.T) { - primaryKeyStr := `872eac6370c72093535fa395ad41a08ee90c9d0d46df9461eb2515451f389d1b` - // primaryKeyStr := `c36f2f92b673cf057a32e8bd0ca88888e7ace40337b737e9c7459fdc4c521918` - sig0 := NewSignatureScheme("bls0chain") - err := sig0.SetPrivateKey(primaryKeyStr) - if err != nil { - t.Fatalf("Set private key failed - %s", errors.Top(err)) - } - data = "823bb3dc0b80a6c86922a884e63908cb9e963ef488688b41e32cbf4d84471a1f" - hash := Sha3Sum256(data) - signature, err := sig0.Sign(hash) - if err != nil { - t.Fatalf("BLS signing failed") - } - numSplitKeys := int(2) - w, err := sig0.SplitKeys(numSplitKeys) - if err != nil { - t.Fatalf("Splitkeys key failed - %s", errors.Top(err)) - } - sigAggScheme := make([]SignatureScheme, numSplitKeys) - for i := 0; i < numSplitKeys; i++ { - sigAggScheme[i] = NewSignatureScheme("bls0chain") - err = sigAggScheme[i].SetPrivateKey(w.Keys[i].PrivateKey) - fmt.Println("seckey:", sigAggScheme[i].GetPrivateKey()) - - require.NoError(t, err) - } - var aggrSig string - for i := 1; i < numSplitKeys; i++ { - tmpSig, _ := sigAggScheme[i].Sign(hash) - fmt.Println("tmpSig:", tmpSig) - aggrSig, _ = sigAggScheme[0].Add(tmpSig, hash) - } - if aggrSig != signature { - t.Fatalf("split key signature failed") - } - fmt.Println("aggrSig:", aggrSig) -} diff --git a/core/zcncrypto/bls0chain_test.go b/core/zcncrypto/bls0chain_test.go deleted file mode 100644 index 77abeb500..000000000 --- a/core/zcncrypto/bls0chain_test.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package zcncrypto - -import ( - "testing" - - "github.com/herumi/bls-go-binary/bls" - "github.com/stretchr/testify/require" -) - -const ( - testMnemonic = "silent tape impulse glimpse state craft sheriff embody bonus clay confirm column swift kingdom door stove mad switch chalk theory pause canoe insane struggle" - - testHerumiPublicKey = "fd2f78b5988719434d6a0782231962934fe1a6f805f98e1bff2c90399a765500ffff9a1cc8c5826feea66d738a7e74ffba7f7dd23e499b5817d8a88e68185f95" - testHerumiPublicKeyStr = "1 55769a39902cff1b8ef905f8a6e14f9362192382076a4d43198798b5782ffd 155f18688ea8d817589b493ed27d7fbaff747e8a736da6ee6f82c5c81c9affff e72525d5dda83d7b169653d3a78bd6d6e36cee1f9974d8f30cbfac33a18efb9 19c1c219dbd76990330f778f18d472f10494a6811bb46e36d21bfdf273c03220" - testHerumiPrivateKey = "baa512aee00f5ff9eafcd82a16fa81d450b2a1a1e35f638cb7e4c2caf01bc407" -) - -func TestGenerateKeys(t *testing.T) { - herumi := &HerumiScheme{} - - w1, err := herumi.RecoverKeys(testMnemonic) - - require.NoError(t, err) - - require.Equal(t, testHerumiPublicKey, w1.Keys[0].PublicKey) - - var pk1 bls.PublicKey - err = pk1.DeserializeHexStr(w1.Keys[0].PublicKey) - require.NoError(t, err) - - require.Equal(t, testHerumiPublicKeyStr, pk1.GetHexString()) - - require.NoError(t, err) - -} - -func TestSignAndVerify(t *testing.T) { - signScheme := &HerumiScheme{} - - w, err := signScheme.RecoverKeys(testMnemonic) - require.Nil(t, err) - - var pk = w.Keys[0].PublicKey - var pk1 bls.PublicKey - - err = pk1.DeserializeHexStr(pk) - require.Nil(t, err) - - require.NoError(t, err) - - hash := Sha3Sum256(data) - signature, err := signScheme.Sign(hash) - if err != nil { - t.Fatalf("BLS signing failed") - } - verifyScheme := &HerumiScheme{} - err = verifyScheme.SetPublicKey(w.Keys[0].PublicKey) - require.NoError(t, err) - if ok, err := verifyScheme.Verify(signature, hash); err != nil || !ok { - t.Fatalf("Verification failed\n") - } -} diff --git a/core/zcncrypto/bls0chain_wasm.go b/core/zcncrypto/bls0chain_wasm.go deleted file mode 100644 index a7592ed08..000000000 --- a/core/zcncrypto/bls0chain_wasm.go +++ /dev/null @@ -1,109 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package zcncrypto - -import ( - "encoding/hex" - - "github.com/0chain/errors" -) - -var ( - Sign func(hash string) (string, error) -) - -// WasmScheme - a signature scheme for BLS0Chain Signature -type WasmScheme struct { - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` - Mnemonic string `json:"mnemonic"` - - id ID - Ids string `json:"threshold_scheme_id"` -} - -// NewWasmScheme - create a BLS0ChainScheme object -func NewWasmScheme() *WasmScheme { - return &WasmScheme{} -} - -func (b0 *WasmScheme) GenerateKeysWithEth(mnemonic, password string) (*Wallet, error) { - return nil, errors.New("wasm_not_support", "please generate keys by bls_wasm in js") -} - -// GenerateKeys - implement interface -func (b0 *WasmScheme) GenerateKeys() (*Wallet, error) { - return nil, errors.New("wasm_not_support", "please generate keys by bls_wasm in js") -} - -func (b0 *WasmScheme) RecoverKeys(mnemonic string) (*Wallet, error) { - return nil, errors.New("wasm_not_support", "please recover keys by bls_wasm in js") -} - -func (b0 *WasmScheme) GetMnemonic() string { - return "" -} - -// SetPrivateKey - implement interface -func (b0 *WasmScheme) SetPrivateKey(privateKey string) error { - return errors.New("wasm_not_support", "please set keys by bls_wasm in js") -} - -// SetPublicKey - implement interface -func (b0 *WasmScheme) SetPublicKey(publicKey string) error { - return errors.New("wasm_not_support", "please set keys by bls_wasm in js") -} - -// GetPublicKey - implement interface -func (b0 *WasmScheme) GetPublicKey() string { - return "please get key in js" -} - -func (b0 *WasmScheme) GetPrivateKey() string { - return "please get key in js" -} - -// Sign - implement interface -func (b0 *WasmScheme) Sign(hash string) (string, error) { - rawHash, err := hex.DecodeString(hash) - if err != nil { - return "", err - } - - if Sign != nil { - return Sign(string(rawHash)) - } - - return "", errors.New("wasm_not_initialized", "please init wasm sdk first") -} - -// Verify - implement interface -func (b0 *WasmScheme) Verify(signature, msg string) (bool, error) { - return false, errors.New("wasm_not_support", "please verify signature by bls_wasm in js") -} - -func (b0 *WasmScheme) Add(signature, msg string) (string, error) { - - return "", errors.New("wasm_not_support", "aggregate signature is not supported on wasm sdk") -} - -// SetID sets ID in HexString format -func (b0 *WasmScheme) SetID(id string) error { - return errors.New("wasm_not_support", "setid is not supported on wasm sdk") -} - -// GetID gets ID in hex string format -func (b0 *WasmScheme) GetID() string { - return "" -} - -// GetPrivateKeyAsByteArray - converts private key into byte array -func (b0 *WasmScheme) GetPrivateKeyAsByteArray() ([]byte, error) { - return nil, errors.New("wasm_not_support", "please get keys by bls_wasm in js") - -} - -func (b0 *WasmScheme) SplitKeys(numSplits int) (*Wallet, error) { - return nil, errors.New("wasm_not_support", "splitkeys is not supported on wasm sdk") -} diff --git a/core/zcncrypto/bls_herumi.go b/core/zcncrypto/bls_herumi.go deleted file mode 100644 index 54b4ce788..000000000 --- a/core/zcncrypto/bls_herumi.go +++ /dev/null @@ -1,210 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package zcncrypto - -import ( - "errors" - "io" - - "github.com/herumi/bls-go-binary/bls" -) - -func init() { - err := bls.Init(bls.CurveFp254BNb) - if err != nil { - panic(err) - } - BlsSignerInstance = &herumiBls{} -} - -type herumiBls struct { -} - -func (b *herumiBls) NewFr() Fr { - return &herumiFr{} -} -func (b *herumiBls) NewSecretKey() SecretKey { - return &herumiSecretKey{} -} - -func (b *herumiBls) NewPublicKey() PublicKey { - return &herumiPublicKey{ - PublicKey: &bls.PublicKey{}, - } -} - -func (b *herumiBls) NewSignature() Signature { - sg := &herumiSignature{ - Sign: &bls.Sign{}, - } - - return sg -} - -func (b *herumiBls) NewID() ID { - id := &herumiID{} - - return id -} - -func (b *herumiBls) SetRandFunc(randReader io.Reader) { - bls.SetRandFunc(randReader) -} - -func (b *herumiBls) FrSub(out Fr, x Fr, y Fr) { - o1, _ := out.(*herumiFr) - x1, _ := x.(*herumiFr) - y1, _ := y.(*herumiFr) - - bls.FrSub(&o1.Fr, &x1.Fr, &y1.Fr) -} - -type herumiFr struct { - bls.Fr -} - -func (fr *herumiFr) Serialize() []byte { - return fr.Fr.Serialize() -} - -func (fr *herumiFr) SetLittleEndian(buf []byte) error { - return fr.Fr.SetLittleEndian(buf) -} - -type herumiSecretKey struct { - bls.SecretKey -} - -func (sk *herumiSecretKey) SerializeToHexStr() string { - return sk.SecretKey.SerializeToHexStr() -} -func (sk *herumiSecretKey) DeserializeHexStr(s string) error { - return sk.SecretKey.DeserializeHexStr(s) -} - -func (sk *herumiSecretKey) Serialize() []byte { - return sk.SecretKey.Serialize() -} - -func (sk *herumiSecretKey) GetLittleEndian() []byte { - return sk.SecretKey.GetLittleEndian() -} -func (sk *herumiSecretKey) SetLittleEndian(buf []byte) error { - return sk.SecretKey.SetLittleEndian(buf) -} - -func (sk *herumiSecretKey) SetByCSPRNG() { - sk.SecretKey.SetByCSPRNG() -} - -func (sk *herumiSecretKey) GetPublicKey() PublicKey { - pk := sk.SecretKey.GetPublicKey() - return &herumiPublicKey{ - PublicKey: pk, - } -} - -func (sk *herumiSecretKey) Add(rhs SecretKey) { - i, _ := rhs.(*herumiSecretKey) - sk.SecretKey.Add(&i.SecretKey) -} - -func (sk *herumiSecretKey) Sign(m string) Signature { - sig := sk.SecretKey.Sign(m) - - return &herumiSignature{ - Sign: sig, - } -} - -func (sk *herumiSecretKey) GetMasterSecretKey(k int) ([]SecretKey, error) { - if k < 1 { - return nil, errors.New("cannot get master secret key for threshold less than 1") - } - - list := sk.SecretKey.GetMasterSecretKey(k) - - msk := make([]SecretKey, len(list)) - - for i, it := range list { - msk[i] = &herumiSecretKey{SecretKey: it} - - } - - return msk, nil -} - -func (sk *herumiSecretKey) Set(msk []SecretKey, id ID) error { - - blsMsk := make([]bls.SecretKey, len(msk)) - - for i, it := range msk { - k, ok := it.(*herumiSecretKey) - if !ok { - return errors.New("invalid herumi secret key") - } - - blsMsk[i] = k.SecretKey - } - - blsID, _ := id.(*herumiID) - - return sk.SecretKey.Set(blsMsk, &blsID.ID) -} - -type herumiPublicKey struct { - *bls.PublicKey -} - -func (pk *herumiPublicKey) SerializeToHexStr() string { - return pk.PublicKey.SerializeToHexStr() -} - -func (pk *herumiPublicKey) DeserializeHexStr(s string) error { - return pk.PublicKey.DeserializeHexStr(s) -} - -func (pk *herumiPublicKey) Serialize() []byte { - return pk.PublicKey.Serialize() -} - -type herumiSignature struct { - *bls.Sign -} - -// SerializeToHexStr -- -func (sg *herumiSignature) SerializeToHexStr() string { - return sg.Sign.SerializeToHexStr() -} - -func (sg *herumiSignature) DeserializeHexStr(s string) error { - return sg.Sign.DeserializeHexStr(s) -} - -func (sg *herumiSignature) Add(rhs Signature) { - sg2, _ := rhs.(*herumiSignature) - - sg.Sign.Add(sg2.Sign) -} - -func (sg *herumiSignature) Verify(pk PublicKey, m string) bool { - pub, _ := pk.(*herumiPublicKey) - - return sg.Sign.Verify(pub.PublicKey, m) -} - -type herumiID struct { - bls.ID -} - -func (id *herumiID) SetHexString(s string) error { - return id.ID.SetHexString(s) -} -func (id *herumiID) GetHexString() string { - return id.ID.GetHexString() -} - -func (id *herumiID) SetDecString(s string) error { - return id.ID.SetDecString(s) -} diff --git a/core/zcncrypto/ed255190chain.go b/core/zcncrypto/ed255190chain.go deleted file mode 100644 index dee2b1f39..000000000 --- a/core/zcncrypto/ed255190chain.go +++ /dev/null @@ -1,179 +0,0 @@ -package zcncrypto - -import ( - "bytes" - "encoding/hex" - "time" - - "github.com/0chain/errors" - - "github.com/0chain/gosdk_common/core/encryption" - "github.com/tyler-smith/go-bip39" - "golang.org/x/crypto/ed25519" -) - -//ED255190chainScheme - a signature scheme based on ED25519 -type ED255190chainScheme struct { - privateKey []byte - publicKey []byte - mnemonic string -} - -// NewED255190chainScheme - create a ED255190chainScheme object -func NewED255190chainScheme() *ED255190chainScheme { - return &ED255190chainScheme{} -} - -//GenerateKeys - implement interface -func (ed *ED255190chainScheme) GenerateKeys() (*Wallet, error) { - // Check for recovery - if len(ed.mnemonic) == 0 { - entropy, err := bip39.NewEntropy(256) - if err != nil { - return nil, errors.New("generate_keys", "Getting entropy failed") - } - ed.mnemonic, err = bip39.NewMnemonic(entropy) - if err != nil { - return nil, errors.New("generate_keys", "Getting mnemonic failed") - } - } - - seed := bip39.NewSeed(ed.mnemonic, "0chain-client-ed25519-key") - r := bytes.NewReader(seed) - public, private, err := ed25519.GenerateKey(r) - if err != nil { - return nil, errors.Wrap(err, "Generate keys failed") - } - // New Wallet - w := &Wallet{} - w.Keys = make([]KeyPair, 1) - w.Keys[0].PublicKey = hex.EncodeToString(public) - w.Keys[0].PrivateKey = hex.EncodeToString(private) - w.ClientKey = w.Keys[0].PublicKey - w.ClientID = encryption.Hash([]byte(public)) - w.Mnemonic = ed.mnemonic - w.Version = CryptoVersion - w.DateCreated = time.Now().Format(time.RFC3339) - return w, nil -} - -//GenerateKeysWithEth - not implemented -func (ed *ED255190chainScheme) GenerateKeysWithEth(mnemonic, password string) (*Wallet, error) { - return nil, errors.New("", "Not supported for this scheme") -} - -func (ed *ED255190chainScheme) RecoverKeys(mnemonic string) (*Wallet, error) { - if mnemonic == "" { - return nil, errors.New("chain_scheme_recover_keys", "Set mnemonic key failed") - } - if len(ed.privateKey) > 0 || len(ed.publicKey) > 0 { - return nil, errors.New("chain_scheme_recover_keys", "Cannot recover when there are keys") - } - ed.mnemonic = mnemonic - return ed.GenerateKeys() -} - -func (b0 *ED255190chainScheme) GetMnemonic() string { - if b0 == nil { - return "" - } - - return b0.mnemonic -} - -func (ed *ED255190chainScheme) SetPrivateKey(privateKey string) error { - if len(ed.privateKey) > 0 { - return errors.New("set_private_key", "cannot set private key when there is a public key") - } - if len(ed.publicKey) > 0 { - return errors.New("set_private_key", "private key already exists") - } - var err error - ed.privateKey, err = hex.DecodeString(privateKey) - return err -} - -func (ed *ED255190chainScheme) SetPublicKey(publicKey string) error { - if len(ed.privateKey) > 0 { - return errors.New("set_public_key", "cannot set public key when there is a private key") - } - if len(ed.publicKey) > 0 { - return errors.New("set_public_key", "public key already exists") - } - var err error - ed.publicKey, err = hex.DecodeString(publicKey) - return err -} - -func (b0 *ED255190chainScheme) SplitKeys(numSplits int) (*Wallet, error) { - return nil, errors.New("chain_scheme_splitkeys", "not implemented") -} - -func (ed *ED255190chainScheme) Sign(hash string) (string, error) { - if len(ed.privateKey) == 0 { - return "", errors.New("chain_scheme_sign", "private key does not exists for signing") - } - rawHash, err := hex.DecodeString(hash) - if err != nil { - return "", err - } - if rawHash == nil { - return "", errors.New("chain_scheme_sign", "Failed hash while signing") - } - return hex.EncodeToString(ed25519.Sign(ed.privateKey, rawHash)), nil -} - -func (ed *ED255190chainScheme) Verify(signature, msg string) (bool, error) { - if len(ed.publicKey) == 0 { - return false, errors.New("chain_scheme_verify", "public key does not exists for verification") - } - sign, err := hex.DecodeString(signature) - if err != nil { - return false, err - } - data, err := hex.DecodeString(msg) - if err != nil { - return false, err - } - return ed25519.Verify(ed.publicKey, data, sign), nil -} - -func (ed *ED255190chainScheme) Add(signature, msg string) (string, error) { - return "", errors.New("chain_scheme_add", "Not supported by signature scheme") -} - -//GetPublicKey - implement interface -func (ed *ED255190chainScheme) GetPublicKey() string { - return hex.EncodeToString(ed.publicKey) -} - -//GetPrivateKey - implement interface -func (ed *ED255190chainScheme) GetPrivateKey() string { - return hex.EncodeToString(ed.privateKey) -} - -//SetID sets ID in HexString format -func (ed *ED255190chainScheme) SetID(id string) error { - // b0.Ids = id - // return b0.id.SetHexString(id) - return errors.New("chain_scheme_set_id", "it is not implemented yet") -} - -//GetID gets ID in hex string format -func (ed *ED255190chainScheme) GetID() string { - //return b0.id.GetHexString() - return "" -} - -// GetPrivateKeyAsByteArray - converts private key into byte array -func (ed *ED255190chainScheme) GetPrivateKeyAsByteArray() ([]byte, error) { - // if len(b0.PrivateKey) == 0 { - // return nil, errors.New("get_private_key_as_byte_array", "cannot convert empty private key to byte array") - // } - // privateKeyBytes, err := hex.DecodeString(b0.PrivateKey) - // if err != nil { - // return nil, err - // } - // return privateKeyBytes, nil - return nil, errors.New("chain_scheme_get_private_key_as_byte_array", "it is not implemented yet") -} diff --git a/core/zcncrypto/ed25519_test.go b/core/zcncrypto/ed25519_test.go deleted file mode 100644 index 5de8a40c9..000000000 --- a/core/zcncrypto/ed25519_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package zcncrypto - -import ( - "encoding/hex" - "testing" - - "github.com/0chain/errors" - "github.com/stretchr/testify/require" -) - -var edverifyPublickey = `b987071c14695caf340ea11560f5a3cb76ad1e709803a8b339826ab3964e470a` -var edsignPrivatekey = `62fc118369fb9dd1fa6065d4f8f765c52ac68ad5aced17a1e5c4f8b4301a9469b987071c14695caf340ea11560f5a3cb76ad1e709803a8b339826ab3964e470a` -var eddata = `TEST` - -//var edexpectedHash = `f4f08e9367e133dc42a4b9c9c665a9efbd4bf15db14d49c6ec51d0dc4c437ffb` -var edWallet *Wallet - -func TestEd25519GenerateKeys(t *testing.T) { - sigScheme := NewSignatureScheme("ed25519") - switch sigScheme.(type) { - case SignatureScheme: - // pass - default: - t.Fatalf("Signature scheme invalid") - } - w, err := sigScheme.GenerateKeys() - if err != nil { - t.Fatalf("Generate keys failed %s", errors.Top(err)) - } - if w.ClientID == "" || w.ClientKey == "" || len(w.Keys) != 1 || w.Mnemonic == "" { - t.Fatalf("Invalid keys generated") - } - edWallet = w -} - -func TestEd25519SignAndVerify(t *testing.T) { - signScheme := NewSignatureScheme("ed25519") - // Check failure without private key - _, err := signScheme.Sign(eddata) - if err == nil { - t.Fatalf("Sign passed without private key") - } - // Sign with valid private key - err = signScheme.SetPrivateKey(edsignPrivatekey) - require.NoError(t, err) - - signature, err := signScheme.Sign(hex.EncodeToString([]byte(eddata))) - if err != nil { - t.Fatalf("ed25519 signing failed") - } - verifyScheme := NewSignatureScheme("ed25519") - err = verifyScheme.SetPublicKey(edverifyPublickey) - require.NoError(t, err) - if ok, err := verifyScheme.Verify(signature, hex.EncodeToString([]byte(eddata))); err != nil || !ok { - t.Fatalf("Verification failed\n") - } -} - -func TestEd25519RecoveryKeys(t *testing.T) { - sigScheme := NewSignatureScheme("ed25519") - w, err := sigScheme.RecoverKeys(edWallet.Mnemonic) - if err != nil { - t.Fatalf("set Recover Keys failed") - } - if w.ClientID != edWallet.ClientID || w.ClientKey != edWallet.ClientKey { - t.Fatalf("Recover key didn't match with generated keys") - } -} - -func BenchmarkE25519Signandverify(b *testing.B) { - sigScheme := NewSignatureScheme("ed25519") - err := sigScheme.SetPrivateKey(edsignPrivatekey) - require.NoError(b, err) - for i := 0; i < b.N; i++ { - signature, err := sigScheme.Sign(eddata) - if err != nil { - b.Fatalf("BLS signing failed") - } - verifyScheme := NewSignatureScheme("ed25519") - err = verifyScheme.SetPublicKey(edverifyPublickey) - require.NoError(b, err) - if ok, err := verifyScheme.Verify(signature, eddata); err != nil || !ok { - b.Fatalf("Verification failed\n") - } - } -} diff --git a/core/zcncrypto/factory.go b/core/zcncrypto/factory.go deleted file mode 100644 index 92e287b50..000000000 --- a/core/zcncrypto/factory.go +++ /dev/null @@ -1,114 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package zcncrypto - -import ( - "encoding/hex" - "encoding/json" - "fmt" - - "github.com/0chain/errors" -) - -// NewSignatureScheme creates an instance for using signature functions -// - sigScheme signature scheme to be used -func NewSignatureScheme(sigScheme string) SignatureScheme { - switch sigScheme { - case "ed25519": - return NewED255190chainScheme() - case "bls0chain": - return NewHerumiScheme() - default: - panic(fmt.Sprintf("unknown signature scheme: %v", sigScheme)) - } -} - -// UnmarshalThresholdSignatureSchemes unmarshal SignatureScheme from json string -func UnmarshalSignatureSchemes(sigScheme string, obj interface{}) ([]SignatureScheme, error) { - switch sigScheme { - - case "bls0chain": - - if obj == nil { - return nil, nil - } - - buf, err := json.Marshal(obj) - if err != nil { - return nil, err - } - - var list []*HerumiScheme - - if err := json.Unmarshal(buf, &list); err != nil { - return nil, err - } - - ss := make([]SignatureScheme, len(list)) - - for i, v := range list { - // bls.ID from json - err = v.SetID(v.Ids) - if err != nil { - return nil, err - } - ss[i] = v - } - - return ss, nil - - default: - panic(fmt.Sprintf("unknown signature scheme: %v", sigScheme)) - } -} - -// 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 { - return nil, errors.New("bls0_generate_threshold_key_shares", "Invalid encryption scheme") - } - - b0original := BlsSignerInstance.NewSecretKey() - b0PrivateKeyBytes, err := b0ss.GetPrivateKeyAsByteArray() - if err != nil { - return nil, err - } - - err = b0original.SetLittleEndian(b0PrivateKeyBytes) - if err != nil { - return nil, err - } - - polynomial, err := b0original.GetMasterSecretKey(t) - if err != nil { - return nil, err - } - - var shares []SignatureScheme - for i := 1; i <= n; i++ { - id := BlsSignerInstance.NewID() - err = id.SetDecString(fmt.Sprint(i)) - if err != nil { - return nil, err - } - - sk := BlsSignerInstance.NewSecretKey() - err = sk.Set(polynomial, id) - if err != nil { - return nil, err - } - - share := &HerumiScheme{} - share.PrivateKey = hex.EncodeToString(sk.GetLittleEndian()) - share.PublicKey = sk.GetPublicKey().SerializeToHexStr() - - share.id = id - share.Ids = id.GetHexString() - - shares = append(shares, share) - } - - return shares, nil -} diff --git a/core/zcncrypto/factory_wasm.go b/core/zcncrypto/factory_wasm.go deleted file mode 100644 index bb8dae7d1..000000000 --- a/core/zcncrypto/factory_wasm.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package zcncrypto - -import ( - "encoding/json" - "fmt" - - "github.com/0chain/errors" -) - -// NewSignatureScheme creates an instance for using signature functions -func NewSignatureScheme(sigScheme string) SignatureScheme { - switch sigScheme { - case "ed25519": - return NewED255190chainScheme() - case "bls0chain": - return NewWasmScheme() - default: - panic(fmt.Sprintf("unknown signature scheme: %v", sigScheme)) - } -} - -// UnmarshalSignatureSchemes unmarshal SignatureScheme from json string -func UnmarshalSignatureSchemes(sigScheme string, obj interface{}) ([]SignatureScheme, error) { - switch sigScheme { - - case "bls0chain": - - if obj == nil { - return nil, nil - } - - buf, err := json.Marshal(obj) - if err != nil { - return nil, err - } - - var list []*WasmScheme - - if err := json.Unmarshal(buf, &list); err != nil { - return nil, err - } - - ss := make([]SignatureScheme, len(list)) - - for i, v := range list { - // bls.ID from json - v.SetID(v.Ids) - ss[i] = v - } - - return ss, nil - - default: - panic(fmt.Sprintf("unknown signature scheme: %v", sigScheme)) - } -} - -//GenerateThresholdKeyShares given a signature scheme will generate threshold sig keys -func GenerateThresholdKeyShares(t, n int, originalKey SignatureScheme) ([]SignatureScheme, error) { - - return nil, errors.New("wasm_not_supported", "GenerateThresholdKeyShares") -} diff --git a/core/zcncrypto/signature_scheme.go b/core/zcncrypto/signature_scheme.go deleted file mode 100644 index c5ea09cd6..000000000 --- a/core/zcncrypto/signature_scheme.go +++ /dev/null @@ -1,112 +0,0 @@ -// Provides low-level functions and types to work with different cryptographic schemes with a unified interface and provide cryptographic operations. -package zcncrypto - -import ( - "encoding/json" - "fmt" - "os" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/tyler-smith/go-bip39" -) - -// CryptoVersion - version of the crypto library -const CryptoVersion = "1.0" - -// KeyPair private and publickey -type KeyPair struct { - PublicKey string `json:"public_key"` - PrivateKey string `json:"private_key"` -} - -// Wallet represents client wallet information -type Wallet struct { - ClientID string `json:"client_id"` - ClientKey string `json:"client_key"` - PeerPublicKey string `json:"peer_public_key"` // Peer public key exists only in split wallet - Keys []KeyPair `json:"keys"` - Mnemonic string `json:"mnemonics"` - Version string `json:"version"` - DateCreated string `json:"date_created"` - Nonce int64 `json:"nonce"` - IsSplit bool `json:"is_split"` -} - -// SignatureScheme - an encryption scheme for signing and verifying messages -type SignatureScheme interface { - // Generate fresh keys - GenerateKeys() (*Wallet, error) - // Generate fresh keys based on eth wallet - GenerateKeysWithEth(mnemonic, password string) (*Wallet, error) - - // Generate keys from mnemonic for recovery - RecoverKeys(mnemonic string) (*Wallet, error) - GetMnemonic() string - - // Signing - Set private key to sign - SetPrivateKey(privateKey string) error - Sign(hash string) (string, error) - - // Signature verification - Set public key to verify - SetPublicKey(publicKey string) error - GetPublicKey() string - GetPrivateKey() string - Verify(signature string, msg string) (bool, error) - - // Combine signature for schemes BLS - Add(signature, msg string) (string, error) - - // implement SplitSignatureScheme - - SplitKeys(numSplits int) (*Wallet, error) - - GetPrivateKeyAsByteArray() ([]byte, error) - - // // implement ThresholdSignatureScheme - - SetID(id string) error - GetID() string -} - -// Marshal returns json string -func (w *Wallet) Marshal() (string, error) { - ws, err := json.Marshal(w) - if err != nil { - return "", errors.New("wallet_marshal", "Invalid Wallet") - } - return string(ws), nil -} - -func (w *Wallet) Sign(hash, scheme string) (string, error) { - sigScheme := NewSignatureScheme(scheme) - err := sigScheme.SetPrivateKey(w.Keys[0].PrivateKey) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} - -// SetSplitKeys sets split keys and wipes out mnemonic and original primary keys -func (w *Wallet) SetSplitKeys(sw *Wallet) { - *w = *sw -} - -func (w *Wallet) SaveTo(file string) error { - d, err := json.Marshal(w) - if err != nil { - return err - } - - fmt.Println("Saving wallet to file: ", string(d)) - - return os.WriteFile(file, d, 0644) -} - -func IsMnemonicValid(mnemonic string) bool { - return bip39.IsMnemonicValid(mnemonic) -} - -func Sha3Sum256(data string) string { - return encryption.Hash(data) -} diff --git a/dev/blobber/handlers.go b/dev/blobber/handlers.go deleted file mode 100644 index 4dd68cf17..000000000 --- a/dev/blobber/handlers.go +++ /dev/null @@ -1,98 +0,0 @@ -package blobber - -import ( - "encoding/json" - "net/http" - - "github.com/0chain/gosdk_common/dev/blobber/model" - "github.com/gorilla/mux" -) - -func uploadAndUpdateFile(w http.ResponseWriter, req *http.Request) { - uploadMeta := req.FormValue("uploadMeta") - - var form *model.UploadFormData - err := json.Unmarshal([]byte(uploadMeta), &form) - - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - //nolint: errcheck - json.NewEncoder(w).Encode(&model.UploadResult{ - Filename: form.Filename, - ValidationRoot: form.ValidationRoot, - FixedMerkleRoot: form.FixedMerkleRoot, - }) - -} - -func getReference(w http.ResponseWriter, req *http.Request) { - - var vars = mux.Vars(req) - - alloctionID := vars["allocation"] - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - result, ok := referencePathResults[alloctionID] - - if ok { - buf, _ := json.Marshal(result) - //nolint: errcheck - w.Write(buf) - return - } - - rootRefs := `{"meta_data":{"chunk_size":0,"created_at":0,"hash":"","lookup_hash":"","name":"/","num_of_blocks":0,"path":"/","path_hash":"","size":0,"type":"d","updated_at":0},"Ref":{"ID":0,"Type":"d","AllocationID":"` + vars["allocation"] + `","LookupHash":"","Name":"/","Path":"/","Hash":"","NumBlocks":0,"PathHash":"","ParentPath":"","PathLevel":1,"CustomMeta":"","ValidationRoot":"","Size":0,"FixedMerkleRoot":"","ActualFileSize":0,"ActualFileHash":"","MimeType":"","WriteMarker":"","ThumbnailSize":0,"ThumbnailHash":"","ActualThumbnailSize":0,"ActualThumbnailHash":"","EncryptedKey":"","Children":null,"OnCloud":false,"CreatedAt":0,"UpdatedAt":0,"ChunkSize":0},"latest_write_marker":null}` - - //nolint: errcheck - w.Write([]byte(rootRefs)) -} - -func commitWrite(w http.ResponseWriter, req *http.Request) { - - // var vars = mux.Vars(req) - - writeMarker := &model.WriteMarker{} - err := json.Unmarshal([]byte(req.FormValue("write_marker")), writeMarker) - - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - result := &model.CommitResult{} - result.AllocationRoot = writeMarker.AllocationRoot - result.Success = true - result.WriteMarker = writeMarker - - err = json.NewEncoder(w).Encode(result) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } -} - -func mockRespone(w http.ResponseWriter, statusCode int, respBody []byte) { - w.Header().Set("Content-Type", "application/json") - if respBody != nil { - _, err := w.Write(respBody) - if err != nil { - statusCode = http.StatusInternalServerError - } - } - - w.WriteHeader(statusCode) -} - -func rollback(w http.ResponseWriter, _ *http.Request) { - mockRespone(w, http.StatusOK, nil) -} - -func latestWriteMarker(w http.ResponseWriter, _ *http.Request) { - latestByte := `{"latest_write_marker":null,"prev_write_marker":null}` - mockRespone(w, http.StatusOK, []byte(latestByte)) -} diff --git a/dev/blobber/init.go b/dev/blobber/init.go deleted file mode 100644 index 12fcff5d8..000000000 --- a/dev/blobber/init.go +++ /dev/null @@ -1,29 +0,0 @@ -package blobber - -import ( - "net/http" - - "github.com/0chain/gosdk_common/dev/mock" - "github.com/gorilla/mux" -) - -func RegisterHandlers(r *mux.Router, m mock.ResponseMap) { - r.HandleFunc("/v1/file/upload/{allocation}", uploadAndUpdateFile).Methods(http.MethodPut, http.MethodPost) - r.HandleFunc("/v1/file/referencepath/{allocation}", getReference).Methods(http.MethodGet) - r.HandleFunc("/v1/file/latestwritemarker/{allocation}", latestWriteMarker).Methods(http.MethodGet) - r.HandleFunc("/v1/connection/commit/{allocation}", commitWrite).Methods(http.MethodPost) - r.HandleFunc("/v1/connection/rollback/{allocation}", rollback).Methods(http.MethodPost) - - r.HandleFunc("/v1/writemarker/lock/{allocation}", mock.WithResponse(m)).Methods(http.MethodPost) - r.HandleFunc("/v1/writemarker/lock/{allocation}", mock.WithResponse(m)).Methods(http.MethodDelete) - r.HandleFunc("/v1/hashnode/root/{allocation}", mock.WithResponse(m)).Methods(http.MethodGet) - - r.HandleFunc("/v1/file/meta/{allocation}", mock.WithResponse(m)).Methods(http.MethodPost) - - r.NotFoundHandler = Handle404(m) -} - -// Handle404 ... -func Handle404(m mock.ResponseMap) http.Handler { - return http.HandlerFunc(mock.WithResponse(m)) -} diff --git a/dev/blobber/model/commit_result.go b/dev/blobber/model/commit_result.go deleted file mode 100644 index 702b6f535..000000000 --- a/dev/blobber/model/commit_result.go +++ /dev/null @@ -1,10 +0,0 @@ -package model - -type CommitResult struct { - AllocationRoot string `json:"allocation_root"` - WriteMarker *WriteMarker `json:"write_marker"` - Success bool `json:"success"` - ErrorMessage string `json:"error_msg,omitempty"` - // Changes []*allocation.AllocationChange `json:"-"` - //Result []*UploadResult `json:"result"` -} diff --git a/dev/blobber/model/ref.go b/dev/blobber/model/ref.go deleted file mode 100644 index 1ed563b0a..000000000 --- a/dev/blobber/model/ref.go +++ /dev/null @@ -1,179 +0,0 @@ -package model - -import ( - "context" - "math" - "reflect" - "strconv" - "strings" - - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/pathutil" -) - -const ( - // FileRef represents a file - FILE = "f" - - // FileRef represents a directory - DIRECTORY = "d" - - CHUNK_SIZE = 64 * 1024 - - DIR_LIST_TAG = "dirlist" - FILE_LIST_TAG = "filelist" -) - -type Ref struct { - Type string `gorm:"column:type" dirlist:"type" filelist:"type"` - AllocationID string `gorm:"column:allocation_id"` - LookupHash string `gorm:"column:lookup_hash" dirlist:"lookup_hash" filelist:"lookup_hash"` - Name string `gorm:"column:name" dirlist:"name" filelist:"name"` - Path string `gorm:"column:path" dirlist:"path" filelist:"path"` - Hash string `gorm:"column:hash" dirlist:"hash" filelist:"hash"` - NumBlocks int64 `gorm:"column:num_of_blocks" dirlist:"num_of_blocks" filelist:"num_of_blocks"` - PathHash string `gorm:"column:path_hash" dirlist:"path_hash" filelist:"path_hash"` - ParentPath string `gorm:"column:parent_path"` - PathLevel int `gorm:"column:level"` - ValidationRoot string `gorm:"column:validation_root" filelist:"validation_root"` - Size int64 `gorm:"column:size" dirlist:"size" filelist:"size"` - FixedMerkleRoot string `gorm:"column:fixed_merkle_root" filelist:"fixed_merkle_root"` - ActualFileSize int64 `gorm:"column:actual_file_size" filelist:"actual_file_size"` - ActualFileHash string `gorm:"column:actual_file_hash" filelist:"actual_file_hash"` - - Children []*Ref `gorm:"-"` - childrenLoaded bool - - ChunkSize int64 `gorm:"column:chunk_size" dirlist:"chunk_size" filelist:"chunk_size"` -} - -func (r *Ref) CalculateHash(ctx context.Context) (string, error) { - if r.Type == DIRECTORY { - return r.CalculateDirHash(ctx) - } - return r.CalculateFileHash(ctx) -} - -// GetListingData reflect and convert all fields into map[string]interface{} -func (r *Ref) GetListingData(ctx context.Context) map[string]interface{} { - if r == nil { - return make(map[string]interface{}) - } - - if r.Type == FILE { - return GetListingFieldsMap(*r, FILE_LIST_TAG) - } - return GetListingFieldsMap(*r, DIR_LIST_TAG) -} - -func GetListingFieldsMap(refEntity interface{}, tagName string) map[string]interface{} { - result := make(map[string]interface{}) - t := reflect.TypeOf(refEntity) - v := reflect.ValueOf(refEntity) - // Iterate over all available fields and read the tag value - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - - // Get the field tag value - tag := field.Tag.Get(tagName) - // Skip if tag is not defined or ignored - if !field.Anonymous && (tag == "" || tag == "-") { - continue - } - - if field.Anonymous { - listMap := GetListingFieldsMap(v.FieldByName(field.Name).Interface(), tagName) - if len(listMap) > 0 { - for k, v := range listMap { - result[k] = v - } - - } - } else { - fieldValue := v.FieldByName(field.Name).Interface() - if fieldValue == nil { - continue - } - result[tag] = fieldValue - } - - } - return result -} - -func GetSubDirsFromPath(p string) []string { - path := p - parent, cur := pathutil.Split(path) - subDirs := make([]string, 0) - for len(cur) > 0 { - if cur == "." { - break - } - subDirs = append([]string{cur}, subDirs...) - parent, cur = pathutil.Split(parent) - } - return subDirs -} - -func (r *Ref) CalculateDirHash(ctx context.Context) (string, error) { - // empty directory, return hash directly - if len(r.Children) == 0 && !r.childrenLoaded { - return r.Hash, nil - } - childHashes := make([]string, len(r.Children)) - childPathHashes := make([]string, len(r.Children)) - var refNumBlocks int64 - var size int64 - for index, childRef := range r.Children { - _, err := childRef.CalculateHash(ctx) - if err != nil { - return "", err - } - childHashes[index] = childRef.Hash - childPathHashes[index] = childRef.PathHash - refNumBlocks += childRef.NumBlocks - size += childRef.Size - } - - r.Hash = encryption.Hash(strings.Join(childHashes, ":")) - r.NumBlocks = refNumBlocks - r.Size = size - r.PathHash = encryption.Hash(strings.Join(childPathHashes, ":")) - r.PathLevel = len(GetSubDirsFromPath(r.Path)) + 1 - r.LookupHash = GetReferenceLookup(r.AllocationID, r.Path) - - return r.Hash, nil -} - -// 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) -} - -func (fr *Ref) CalculateFileHash(ctx context.Context) (string, error) { - fr.Hash = encryption.Hash(fr.GetFileHashData()) - fr.NumBlocks = int64(math.Ceil(float64(fr.Size*1.0) / float64(fr.ChunkSize))) - fr.PathHash = GetReferenceLookup(fr.AllocationID, fr.Path) - fr.PathLevel = len(GetSubDirsFromPath(fr.Path)) + 1 - fr.LookupHash = GetReferenceLookup(fr.AllocationID, fr.Path) - - return fr.Hash, nil -} - -func (fr *Ref) GetFileHashData() string { - hashArray := make([]string, 0, 11) - hashArray = append(hashArray, fr.AllocationID) - hashArray = append(hashArray, fr.Type) - hashArray = append(hashArray, fr.Name) - hashArray = append(hashArray, fr.Path) - hashArray = append(hashArray, strconv.FormatInt(fr.Size, 10)) - hashArray = append(hashArray, fr.ValidationRoot) - hashArray = append(hashArray, fr.FixedMerkleRoot) - hashArray = append(hashArray, strconv.FormatInt(fr.ActualFileSize, 10)) - hashArray = append(hashArray, fr.ActualFileHash) - hashArray = append(hashArray, strconv.FormatInt(fr.ChunkSize, 10)) - - return strings.Join(hashArray, ":") -} diff --git a/dev/blobber/model/reference_path.go b/dev/blobber/model/reference_path.go deleted file mode 100644 index aac5c365b..000000000 --- a/dev/blobber/model/reference_path.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type ReferencePath struct { - Meta map[string]interface{} `json:"meta_data"` - List []*ReferencePath `json:"list,omitempty"` - Ref *Ref -} diff --git a/dev/blobber/model/reference_path_result.go b/dev/blobber/model/reference_path_result.go deleted file mode 100644 index 9f346b715..000000000 --- a/dev/blobber/model/reference_path_result.go +++ /dev/null @@ -1,35 +0,0 @@ -package model - -import "context" - -type ReferencePathResult struct { - *ReferencePath - LatestWM *WriteMarker `json:"latest_write_marker"` -} - -func BuildReferencePathResult(rootRef *Ref) *ReferencePathResult { - rootRef.CalculateHash(context.TODO()) //nolint - - refPath := &ReferencePath{Ref: rootRef} - - refsToProcess := []*ReferencePath{refPath} - - //convert Ref tree to ReferencePath tree - for len(refsToProcess) > 0 { - refToProcess := refsToProcess[0] - refToProcess.Meta = refToProcess.Ref.GetListingData(context.TODO()) - if len(refToProcess.Ref.Children) > 0 { - refToProcess.List = make([]*ReferencePath, len(refToProcess.Ref.Children)) - } - for idx, child := range refToProcess.Ref.Children { - childRefPath := &ReferencePath{Ref: child} - refToProcess.List[idx] = childRefPath - refsToProcess = append(refsToProcess, childRefPath) - } - refsToProcess = refsToProcess[1:] - } - - return &ReferencePathResult{ - ReferencePath: refPath, - } -} diff --git a/dev/blobber/model/upload_form_data.go b/dev/blobber/model/upload_form_data.go deleted file mode 100644 index 89f1554f0..000000000 --- a/dev/blobber/model/upload_form_data.go +++ /dev/null @@ -1,38 +0,0 @@ -package model - -// UploadFormData form data of upload -type UploadFormData struct { - ConnectionID string `json:"connection_id,omitempty"` - // Filename remote file name - Filename string `json:"filename,omitempty"` - // Path remote path - Path string `json:"filepath,omitempty"` - - // ValidationRoot of shard data (encoded,encrypted) where leaf is sha256 hash of 64KB data - ValidationRoot string `json:"validation_root,omitempty"` - // Hash hash of shard thumbnail (encoded,encrypted) - ThumbnailContentHash string `json:"thumbnail_content_hash,omitempty"` - - // FixedMerkleRoot merkle root of shard data (encoded, encrypted) - FixedMerkleRoot string `json:"fixed_merkle_root,omitempty"` - - // ActualHash hash of orignial file (unencoded, unencrypted) - ActualHash string `json:"actual_hash,omitempty"` - // ActualSize total bytes of orignial file (unencoded, unencrypted) - ActualSize int64 `json:"actual_size,omitempty"` - // ActualThumbnailSize total bytes of orignial thumbnail (unencoded, unencrypted) - ActualThumbSize int64 `json:"actual_thumb_size,omitempty"` - // ActualThumbnailHash hash of orignial thumbnail (unencoded, unencrypted) - ActualThumbHash string `json:"actual_thumb_hash,omitempty"` - - MimeType string `json:"mimetype,omitempty"` - CustomMeta string `json:"custom_meta,omitempty"` - EncryptedKey string `json:"encrypted_key,omitempty"` - - IsFinal bool `json:"is_final,omitempty"` // current chunk is last or not - ChunkHash string `json:"chunk_hash"` // hash of current chunk - ChunkIndex int `json:"chunk_index,omitempty"` // the seq of current chunk. all chunks MUST be uploaded one by one because of streaming merkle hash - ChunkSize int64 `json:"chunk_size,omitempty"` // the size of a chunk. 64*1024 is default - UploadOffset int64 `json:"upload_offset,omitempty"` // It is next position that new incoming chunk should be append to - -} diff --git a/dev/blobber/model/upload_result.go b/dev/blobber/model/upload_result.go deleted file mode 100644 index 41a2f9855..000000000 --- a/dev/blobber/model/upload_result.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UploadResult struct { - Filename string `json:"filename"` - ShardSize int64 `json:"size"` - ValidationRoot string `json:"validation_root,omitempty"` - FixedMerkleRoot string `json:"fixed_merkle_root,omitempty"` -} diff --git a/dev/blobber/model/write_marker.go b/dev/blobber/model/write_marker.go deleted file mode 100644 index def6f8844..000000000 --- a/dev/blobber/model/write_marker.go +++ /dev/null @@ -1,22 +0,0 @@ -package model - -import ( - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/marker" -) - -type WriteMarker struct { - AllocationRoot string `gorm:"column:allocation_root;primary_key" json:"allocation_root"` - PreviousAllocationRoot string `gorm:"column:prev_allocation_root" json:"prev_allocation_root"` - AllocationID string `gorm:"column:allocation_id" json:"allocation_id"` - Size int64 `gorm:"column:size" json:"size"` - BlobberID string `gorm:"column:blobber_id" json:"blobber_id"` - Timestamp common.Timestamp `gorm:"column:timestamp" json:"timestamp"` - ClientID string `gorm:"column:client_id" json:"client_id"` - Signature string `gorm:"column:signature" json:"signature"` -} - -type LatestPrevWriteMarker struct { - LatestWM *marker.WriteMarker `json:"latest_write_marker"` - PrevWM *marker.WriteMarker `json:"prev_write_marker"` -} diff --git a/dev/blobber/ref.go b/dev/blobber/ref.go deleted file mode 100644 index 09a0f579b..000000000 --- a/dev/blobber/ref.go +++ /dev/null @@ -1,23 +0,0 @@ -package blobber - -import ( - "sync" - - "github.com/0chain/gosdk_common/dev/blobber/model" -) - -var referencePathResults = make(map[string]*model.ReferencePathResult) -var referencePathResultsMutex sync.Mutex - -func MockReferencePathResult(allocationId string, rootRef *model.Ref) func() { - result := model.BuildReferencePathResult(rootRef) - referencePathResultsMutex.Lock() - defer referencePathResultsMutex.Unlock() - referencePathResults[allocationId] = result - - return func() { - referencePathResultsMutex.Lock() - defer referencePathResultsMutex.Unlock() - delete(referencePathResults, allocationId) - } -} diff --git a/dev/mock/response.go b/dev/mock/response.go deleted file mode 100644 index ebce8f451..000000000 --- a/dev/mock/response.go +++ /dev/null @@ -1,34 +0,0 @@ -package mock - -import "net/http" - -type ResponseMap map[string]Response - -type Response struct { - StatusCode int - Body []byte -} - -// WithResponse mock respone -func WithResponse(m ResponseMap) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - defer w.Header().Set("Content-Type", "application/json") - - if m != nil { - key := r.Method + ":" + r.URL.Path - resp, ok := m[key] - - if ok { - - w.WriteHeader(resp.StatusCode) - if resp.Body != nil { - w.Write(resp.Body) //nolint: errcheck - } - - return - } - } - - w.WriteHeader(http.StatusNotFound) - } -} diff --git a/dev/server.go b/dev/server.go deleted file mode 100644 index 1d7956076..000000000 --- a/dev/server.go +++ /dev/null @@ -1,36 +0,0 @@ -// Providers tools for local development - do not use. -package dev - -import ( - "net/http/httptest" - - "github.com/0chain/gosdk_common/dev/blobber" - "github.com/0chain/gosdk_common/dev/mock" - "github.com/gorilla/mux" -) - -// Server a local dev server to mock server APIs -type Server struct { - *httptest.Server - *mux.Router -} - -// NewServer create a local dev server -func NewServer() *Server { - router := mux.NewRouter() - s := &Server{ - Router: router, - Server: httptest.NewServer(router), - } - - return s -} - -// NewBlobberServer create a local dev blobber server -func NewBlobberServer(m mock.ResponseMap) *Server { - s := NewServer() - - blobber.RegisterHandlers(s.Router, m) - - return s -} diff --git a/go.mod b/go.mod index 3314d30b7..ebdc38d8c 100644 --- a/go.mod +++ b/go.mod @@ -44,7 +44,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd + github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606 github.com/hack-pad/go-webworkers v0.1.0 github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/minio/sha256-simd v1.0.1 diff --git a/go.sum b/go.sum index 2d346f6af..87035ac38 100644 --- a/go.sum +++ b/go.sum @@ -46,6 +46,8 @@ github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd h1:zeLdGO7e5Ovd4w/g/sHvg+0+Zu0gI7mhpznSsGbB3lI= github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd/go.mod h1:A6zAa6S8jWML2razteUYtk9aINjHW4u8MjFKITgIdp4= +github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606 h1:/pEJYnH04BoG5UJsQ+k74F/rJOtehXOgMVbB44h1gAY= +github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 2b195db8d..68c956763 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -21,8 +21,8 @@ import ( l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk/mobilesdk/zbox" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/mobilesdk/zboxapi" + "github.com/0chain/gosdk_common/zcncore" ) var nonce = int64(0) @@ -47,6 +47,8 @@ type ChainConfig struct { type StorageSDK struct { chainconfig *ChainConfig client *client.Client + // chainconfig *ChainConfig +} } // SetLogFile setup log level for core libraries @@ -67,7 +69,12 @@ func SetLogLevel(logLevel int) { // Init init the sdk with chain config // - chainConfigJson: chain config json string func Init(chainConfigJson string) error { - return zcncore.Init(chainConfigJson) + cfg := conf.Config{} + err := json.Unmarshal([]byte(chainConfigJson), &cfg) + if err != nil { + return err + } + return client.Init(context.Background(), cfg) } // InitStorageSDK init storage sdk from config @@ -108,7 +115,7 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { l.Logger.Error(err) return nil, err } - err = zcncore.InitZCNSDK(configObj.BlockWorker, configObj.SignatureScheme) + err = Init(configObj.BlockWorker) if err != nil { l.Logger.Error(err) return nil, err @@ -118,12 +125,11 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { l.Logger.Info(configObj.ChainID) l.Logger.Info(configObj.SignatureScheme) l.Logger.Info(configObj.PreferredBlobbers) - if err = sdk.InitStorageSDK(clientJson, + if err = client.InitSDK(clientJson, configObj.BlockWorker, configObj.ChainID, configObj.SignatureScheme, - configObj.PreferredBlobbers, - 0); err != nil { + 0, false, true); err != nil { l.Logger.Error(err) return nil, err } @@ -139,7 +145,7 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { l.Logger.Info("Init successful") - return &StorageSDK{client: client.GetClient(), chainconfig: configObj}, nil + return &StorageSDK{}, nil } // CreateAllocation creating new allocation @@ -319,21 +325,6 @@ func (s *StorageSDK) CancelAllocation(allocationID string) (string, error) { 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 { - return "", err - } - - retBytes, err := json.Marshal(readPool) - if err != nil { - return "", err - } - return string(retBytes), nil -} - // WRITE POOL METHODS // WritePoolLock lock write pool with given number of tokens // - durInSeconds: duration in seconds @@ -341,10 +332,23 @@ func (s *StorageSDK) GetReadPoolInfo(clientID string) (string, error) { // - fee: fee of the transaction // - allocID: allocation ID func (s *StorageSDK) WritePoolLock(durInSeconds int64, tokens, fee float64, allocID string) error { + formattedWpLock := strconv.FormatUint(zcncore.ConvertToValue(tokens), 10) + formattedFee := strconv.FormatUint(zcncore.ConvertToValue(fee), 10) + + wpLockUint, err := strconv.ParseUint(formattedWpLock, 10, 64) + if err != nil { + return errors.Errorf("Error parsing write pool lock: %v", err) + } + + feeUint, err := strconv.ParseUint(formattedFee, 10, 64) + + if err != nil { + return errors.Errorf("Error parsing fee: %v", err) + } _, _, err := sdk.WritePoolLock( allocID, - strconv.FormatUint(zcncore.ConvertTokenToSAS(tokens), 10), - strconv.FormatUint(zcncore.ConvertTokenToSAS(fee), 10)) + wpLockUint, + feeUint, return err } @@ -402,11 +406,11 @@ func (s *StorageSDK) RedeemFreeStorage(ticket string) (string, error) { return "", err } - if recipientPublicKey != client.GetClientPublicKey() { + if recipientPublicKey != client.PublicKey() { return "", fmt.Errorf("invalid_free_marker: free marker is not assigned to your wallet") } - hash, _, err := sdk.CreateFreeAllocation(marker, strconv.FormatUint(lock, 10)) + hash, _, err := sdk.CreateFreeAllocation(marker, lock) return hash, err } @@ -437,7 +441,7 @@ func decodeTicket(ticket string) (string, string, uint64, error) { markerStr, _ := json.Marshal(markerInput) s, _ := strconv.ParseFloat(string(fmt.Sprintf("%v", lock)), 64) - return string(recipientPublicKey), string(markerStr), zcncore.ConvertTokenToSAS(s), nil + return string(recipientPublicKey), string(markerStr), zcncore.ConvertToValue(s), nil } // RegisterAuthorizer Client can extend interface and FaSS implementation to this register like this: diff --git a/mobilesdk/sdk/sign.go b/mobilesdk/sdk/sign.go index 20dc633d3..b444b1b3b 100644 --- a/mobilesdk/sdk/sign.go +++ b/mobilesdk/sdk/sign.go @@ -3,10 +3,10 @@ package sdk import ( "errors" + _ "github.com/0chain/gosdk_common/core/client" //import it to initialize sys.Sign "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/zcncrypto" - _ "github.com/0chain/gosdk_common/zboxcore/client" //import it to initialize sys.Sign ) var ErrInvalidSignatureScheme = errors.New("invalid_signature_scheme") diff --git a/mobilesdk/zbox/m3u8.go b/mobilesdk/zbox/m3u8.go index d9aa8c174..bbf5a3c5f 100644 --- a/mobilesdk/zbox/m3u8.go +++ b/mobilesdk/zbox/m3u8.go @@ -6,6 +6,8 @@ import ( "sort" "strconv" "time" + + "github.com/0chain/gosdk/zboxcore/logger" ) // #EXTM3U @@ -86,10 +88,26 @@ func (m *MediaPlaylist) flush() { return } - m.Writer.Truncate(0) - m.Writer.Seek(0, 0) - m.Writer.Write(m.Encode()) - m.Writer.Sync() + err := m.Writer.Truncate(0) + if err != nil { + logger.Logger.Error("flush m3u8 error: ", err) + return + } + _, err = m.Writer.Seek(0, 0) + if err != nil { + logger.Logger.Error("flush m3u8 error: ", err) + return + } + _, err = m.Writer.Write(m.Encode()) + if err != nil { + logger.Logger.Error("flush m3u8 error: ", err) + return + } + err = m.Writer.Sync() + if err != nil { + logger.Logger.Error("flush m3u8 error: ", err) + return + } } // Encode encode m3u8 diff --git a/mobilesdk/zbox/util.go b/mobilesdk/zbox/util.go index a59d48634..52ae76bf3 100644 --- a/mobilesdk/zbox/util.go +++ b/mobilesdk/zbox/util.go @@ -1,103 +1,10 @@ package zbox import ( - "encoding/hex" - "encoding/json" - "fmt" "regexp" "strconv" - - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/0chain/gosdk/zcncore" ) -// GetClientEncryptedPublicKey - getting client encrypted pub key -func GetClientEncryptedPublicKey() (string, error) { - return sdk.GetClientEncryptedPublicKey() -} - -func TokensToEth(tokens int64) string { - return fmt.Sprintf("%f", zcncore.TokensToEth(tokens)) -} - -func GEthToTokens(tokens int64) string { - return fmt.Sprintf("%f", zcncore.GTokensToEth(tokens)) -} - -// ConvertZcnTokenToETH - converting Zcn tokens to Eth -func ConvertZcnTokenToETH(token float64) (string, error) { - res, err := zcncore.ConvertZcnTokenToETH(token) - return fmt.Sprintf("%f", res), err -} - -// SuggestEthGasPrice - return back suggested price for gas -func SuggestEthGasPrice() (string, error) { - res, err := zcncore.SuggestEthGasPrice() - return strconv.FormatInt(res, 10), err -} - -// Encrypt - encrypting text with key -func Encrypt(key, text string) (string, error) { - keyBytes := []byte(key) - textBytes := []byte(text) - response, err := zboxutil.Encrypt(keyBytes, textBytes) - if err != nil { - return "", err - } - return hex.EncodeToString(response), nil -} - -// Decrypt - decrypting text with key -func Decrypt(key, text string) (string, error) { - keyBytes := []byte(key) - textBytes, _ := hex.DecodeString(text) - response, err := zboxutil.Decrypt(keyBytes, textBytes) - if err != nil { - return "", err - } - return string(response), nil -} - -// GetNetwork - get current network -func GetNetwork() (string, error) { - networkDetails := sdk.GetNetwork() - networkDetailsBytes, err := json.Marshal(networkDetails) - if err != nil { - return "", err - } - return string(networkDetailsBytes), nil -} - -// GetBlobbers - get list of blobbers -func GetBlobbers() (string, error) { - blobbers, err := sdk.GetBlobbers(true, false) - if err != nil { - return "", err - } - - blobbersBytes, err := json.Marshal(blobbers) - if err != nil { - return "", err - } - return string(blobbersBytes), nil -} - -// Sign - sign hash -func Sign(hash string) (string, error) { - if len(hash) == 0 { - return "", fmt.Errorf("null sign") - } - return client.Sign(hash) -} - -// VerifySignatxure - verify message with signature -func VerifySignature(signature string, msg string) (bool, error) { - return sys.Verify(signature, msg) -} - func GetNumber(value string) int { re := regexp.MustCompile("[0-9]+") submatchall := re.FindAllString(value, -1) diff --git a/mobilesdk/zboxapi/client.go b/mobilesdk/zboxapi/client.go index 87a3af8d7..9fa9f1271 100644 --- a/mobilesdk/zboxapi/client.go +++ b/mobilesdk/zboxapi/client.go @@ -13,9 +13,9 @@ import ( "context" "errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/zboxapi" - "github.com/0chain/gosdk_common/zboxcore/client" "go.uber.org/zap" ) @@ -33,14 +33,9 @@ func Init(baseUrl, appType string) { zboxApiClient = zboxapi.NewClient() zboxApiClient.SetRequest(baseUrl, appType) - c := client.GetClient() - if c != nil { - err := SetWallet(client.GetClientID(), client.GetClientPrivateKey(), client.GetClientPublicKey()) //nolint: errcheck - if err != nil { - logging.Error("SetWallet", zap.Error(err)) - } - } else { - logging.Info("SetWallet: skipped") + err := SetWallet(client.Id(), client.PrivateKey(), client.PublicKey()) //nolint: errcheck + if err != nil { + logging.Error("SetWallet", zap.Error(err)) } } diff --git a/mobilesdk/zcn/readpool.go b/mobilesdk/zcn/readpool.go deleted file mode 100644 index d9d827e8e..000000000 --- a/mobilesdk/zcn/readpool.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build mobile -// +build mobile - -package zcn - -import ( - "github.com/0chain/gosdk/zboxcore/sdk" -) - -// ReadPoolLock locks given number of tokes for given duration in read pool. -// ## Inputs -// - tokens: sas tokens -// - fee: sas tokens -func ReadPoolLock(tokens, fee string) (string, error) { - hash, _, err := sdk.ReadPoolLock(tokens, fee) - - return hash, err -} - -// ReadPoolUnLock unlocks all the tokens in the readpool associated with the current wallet. -// ## Inputs -// - fee: sas tokens -func ReadPoolUnLock(fee string) (string, error) { - hash, _, err := sdk.ReadPoolUnlock(fee) - - return hash, err -} diff --git a/mobilesdk/zcn/smartcontract.go b/mobilesdk/zcn/smartcontract.go deleted file mode 100644 index 7df9025c8..000000000 --- a/mobilesdk/zcn/smartcontract.go +++ /dev/null @@ -1,96 +0,0 @@ -//go:build mobile -// +build mobile - -package zcn - -import ( - "encoding/json" - "fmt" - "sync" - - "github.com/0chain/gosdk/zcncore" -) - -// Faucet -func Faucet(methodName, jsonInput string, zcnToken float64) (string, error) { - return ExecuteSmartContract(zcncore.FaucetSmartContractAddress, methodName, jsonInput, zcncore.ConvertToValue(zcnToken)) -} - -func ExecuteSmartContract(address, methodName, input, sasToken string) (string, error) { - wg := &sync.WaitGroup{} - cb := &transactionCallback{wg: wg} - txn, err := zcncore.NewTransaction(cb, "0", 0) - if err != nil { - return "", err - } - - wg.Add(1) - - err = txn.ExecuteSmartContract(address, methodName, input, sasToken) - if err != nil { - return "", err - - } - - wg.Wait() - - if !cb.success { - return "", fmt.Errorf("smartcontract: %s", cb.errMsg) - } - - cb.success = false - wg.Add(1) - err = txn.Verify() - if err != nil { - return "", err - } - - wg.Wait() - - if !cb.success { - return "", fmt.Errorf("smartcontract: %s", cb.errMsg) - } - - switch txn.GetVerifyConfirmationStatus() { - case zcncore.ChargeableError: - return "", fmt.Errorf("smartcontract: %s", txn.GetVerifyOutput()) - case zcncore.Success: - js, _ := json.Marshal(cb.txn) - return string(js), nil - } - - return "", fmt.Errorf("smartcontract: %v", txn.GetVerifyConfirmationStatus()) -} - -type transactionCallback struct { - wg *sync.WaitGroup - success bool - errMsg string - - txn *zcncore.Transaction -} - -func (cb *transactionCallback) OnTransactionComplete(t *zcncore.Transaction, status int) { - defer cb.wg.Done() - cb.txn = t - if status == zcncore.StatusSuccess { - cb.success = true - } else { - cb.errMsg = t.GetTransactionError() - } -} - -func (cb *transactionCallback) OnVerifyComplete(t *zcncore.Transaction, status int) { - defer cb.wg.Done() - cb.txn = t - if status == zcncore.StatusSuccess { - cb.success = true - } else { - cb.errMsg = t.GetVerifyError() - } -} - -func (cb *transactionCallback) OnAuthComplete(t *zcncore.Transaction, status int) { - cb.txn = t - fmt.Println("Authorization complete on zauth.", status) -} diff --git a/mobilesdk/zcn/transaction_query.go b/mobilesdk/zcn/transaction_query.go index 981f2755d..c5d081254 100644 --- a/mobilesdk/zcn/transaction_query.go +++ b/mobilesdk/zcn/transaction_query.go @@ -4,7 +4,7 @@ package zcn import ( - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // GetUserLockedTotal get total token user locked diff --git a/mobilesdk/zcn/writepool.go b/mobilesdk/zcn/writepool.go index e21418db5..7d78d7292 100644 --- a/mobilesdk/zcn/writepool.go +++ b/mobilesdk/zcn/writepool.go @@ -4,6 +4,8 @@ package zcn import ( + "strconv" + "github.com/0chain/gosdk/zboxcore/sdk" ) @@ -13,7 +15,22 @@ import ( // - tokens: sas tokens // - fee: sas tokens func WritePoolLock(allocID string, tokens, fee string) (string, error) { - hash, _, err := sdk.WritePoolLock(allocID, tokens, fee) + tokensUint, err := strconv.ParseUint(tokens, 10, 64) + + if err != nil { + return "", err + } + + feeUint, err := strconv.ParseUint(fee, 10, 64) + + if err != nil { + return "", err + } + hash, _, err := sdk.WritePoolLock( + allocID, + tokensUint, + feeUint, + ) return hash, err } diff --git a/sdks/blobber/blobber.go b/sdks/blobber/blobber.go deleted file mode 100644 index 89bbf424e..000000000 --- a/sdks/blobber/blobber.go +++ /dev/null @@ -1,23 +0,0 @@ -package blobber - -import ( - "github.com/0chain/gosdk_common/sdks" -) - -// Blobber blobber sdk client instance -type Blobber struct { - BaseURLs []string - *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, - ZBox: zbox, - } - - return b -} diff --git a/sdks/blobber/doc.go b/sdks/blobber/doc.go deleted file mode 100644 index 58580152e..000000000 --- a/sdks/blobber/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Provides sdk functions to be used by the blobber. -package blobber \ No newline at end of file diff --git a/sdks/blobber/endpoints.go b/sdks/blobber/endpoints.go deleted file mode 100644 index 319887d0e..000000000 --- a/sdks/blobber/endpoints.go +++ /dev/null @@ -1,12 +0,0 @@ -package blobber - -const ( - // EndpointWriteMarkerLock api endpoint of WriteMarkerLock - EndpointWriteMarkerLock = "/v1/writemarker/lock/" - - // EndpointRootHashnode api endpoint of getting root hashnode of an allocation - EndpointRootHashnode = "/v1/hashnode/root/" - - // EndpointFileMeta api endpoint of file meta - EndpointFileMeta = "/v1/file/meta/" -) diff --git a/sdks/client.go b/sdks/client.go deleted file mode 100644 index 6cc6e0445..000000000 --- a/sdks/client.go +++ /dev/null @@ -1,51 +0,0 @@ -package sdks - -import ( - "net/http" - "net/url" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/constants" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/client" -) - -// Client a client instance of restful api -type Client struct { - ClientID string - ClientPublicKey string - BaseURL string -} - -// create client instance -func NewClient(clientID, clientPublicKey, baseURL string) (Client, error) { - u, err := url.Parse(baseURL) - - c := Client{ - ClientID: clientID, - ClientPublicKey: clientPublicKey, - } - - if err != nil { - return c, errors.Throw(constants.ErrInvalidParameter, "baseURL") - } - - c.BaseURL = u.String() - - return c, nil -} - -func (c *Client) SignRequest(req *http.Request, allocation string) error { - - req.Header.Set("X-App-Client-ID", c.ClientID) - req.Header.Set("X-App-Client-Key", c.ClientPublicKey) - - sign, err := sys.Sign(encryption.Hash(allocation), client.GetClient().SignatureScheme, client.GetClientSysKeys()) - if err != nil { - return err - } - req.Header.Set("X-App-Client-Signature", sign) - - return nil -} diff --git a/sdks/doc.go b/sdks/doc.go deleted file mode 100644 index 1cb024dab..000000000 --- a/sdks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Miscellaneous provider-related SDKs. -package sdks \ No newline at end of file diff --git a/sdks/request.go b/sdks/request.go deleted file mode 100644 index 11d03fc5d..000000000 --- a/sdks/request.go +++ /dev/null @@ -1,21 +0,0 @@ -package sdks - -import ( - "io" -) - -// Request request payload -type Request struct { - - //AllocationID optional. allocation id - AllocationID string - //ConnectionID optional. session id - ConnectionID string - - // ContentType content-type in header - ContentType string - // Body form data - Body io.Reader - // QueryString query string - QueryString map[string]string -} diff --git a/sdks/zbox.go b/sdks/zbox.go deleted file mode 100644 index 4aa0d4fa4..000000000 --- a/sdks/zbox.go +++ /dev/null @@ -1,146 +0,0 @@ -package sdks - -import ( - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/url" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/constants" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/resty" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/zboxcore/client" -) - -// ZBox sdk client instance -type ZBox struct { - // ClientID client id - ClientID string - // ClientKey client key - ClientKey string - // SignatureScheme signature scheme - SignatureScheme string - - // Wallet wallet - Wallet *zcncrypto.Wallet - - // NewRequest create http request - NewRequest func(method, url string, body io.Reader) (*http.Request, error) -} - -// 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, - ClientKey: clientKey, - SignatureScheme: signatureScheme, - Wallet: wallet, - NewRequest: http.NewRequest, - } - - return s -} - -// 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 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 { - return errors.Throw(constants.ErrInvalidParameter, "req") - } - - req.Header.Set("X-App-Client-ID", z.ClientID) - req.Header.Set("X-App-Client-Key", z.ClientKey) - - hash := encryption.Hash(allocationID) - - sign, err := sys.Sign(hash, z.SignatureScheme, client.GetClientSysKeys()) - if err != nil { - return err - } - - // ClientSignatureHeader represents http request header contains signature. - req.Header.Set("X-App-Client-Signature", sign) - - return nil -} - -// CreateTransport create http.Transport with default dial timeout -func (z *ZBox) CreateTransport() *http.Transport { - return &http.Transport{ - Dial: (&net.Dialer{ - Timeout: resty.DefaultDialTimeout, - }).Dial, - TLSHandshakeTimeout: resty.DefaultDialTimeout, - } -} - -// 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 - if len(pathArgs) > 0 { - requestURL = fmt.Sprintf(pathFormat, pathArgs...) - } - - if len(queryString) > 0 { - requestQuery := make(url.Values) - for k, v := range queryString { - requestQuery.Add(k, v) - } - - requestURL += "?" + requestQuery.Encode() - } - - list := make([]string, len(baseURLs)) - for k, v := range baseURLs { - list[k] = v + requestURL - } - - 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) - - opts = append(opts, resty.WithRetry(resty.DefaultRetry)) - opts = append(opts, resty.WithRequestInterceptor(func(r *http.Request) error { - return z.SignRequest(r, req.AllocationID) //nolint - })) - - if len(req.ContentType) > 0 { - opts = append(opts, resty.WithHeader(map[string]string{ - "Content-Type": req.ContentType, - })) - } - - opts = append(opts, resty.WithTransport(z.CreateTransport())) - - r := resty.New(opts...).Then(handle) - - return r -} diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index ba62a18ab..4093ba667 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -13,9 +13,9 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) const TOKEN_UNIT int64 = 1e10 @@ -402,21 +402,6 @@ 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) @@ -444,17 +429,6 @@ func getSkatePoolInfo(providerType int, providerID string) (*sdk.StakePoolInfo, return info, err } -// 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 { - return nil, err - } - - return readPool, nil -} - // 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 diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 902f35ba3..42bac292a 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,9 +7,9 @@ import ( "fmt" "syscall/js" - "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zcncore" ) type AuthCallbackFunc func(msg string) string diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index ff69e5409..45a14ba60 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -6,14 +6,12 @@ import ( "encoding/json" "path" "strconv" - "time" - - "github.com/0chain/gosdk/zcnbridge" - "github.com/0chain/gosdk/zcnbridge/errors" - "github.com/0chain/gosdk/zcnbridge/log" - "github.com/0chain/gosdk/zcnbridge/transaction" - "github.com/0chain/gosdk/zcnbridge/wallet" - "github.com/0chain/gosdk/zcncore" + + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/zcnbridge" + "github.com/0chain/gosdk_common/zcnbridge/errors" + "github.com/0chain/gosdk_common/zcnbridge/log" + "github.com/0chain/gosdk_common/zcncore" "github.com/ethereum/go-ethereum/ethclient" ) @@ -37,7 +35,7 @@ func initBridge( gasLimit uint64, value int64, consensusThreshold float64) error { - if len(zcncore.GetWalletRaw().ClientID) == 0 { + if len(client.Id()) == 0 { return errors.New("wallet_error", "wallet is not set") } @@ -46,8 +44,6 @@ func initBridge( return errors.New("wallet_error", err.Error()) } - transactionProvider := transaction.NewTransactionProvider() - keyStore := zcnbridge.NewKeyStore( path.Join(".", zcnbridge.EthereumWalletStorageDir)) @@ -62,7 +58,6 @@ func initBridge( gasLimit, consensusThreshold, ethereumClient, - transactionProvider, keyStore, ) @@ -72,17 +67,17 @@ func initBridge( // 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 +func burnZCN(amount uint64) string { //nolint if bridge == nil { return errors.New("burnZCN", "bridge is not initialized").Error() } - tx, err := bridge.BurnZCN(context.Background(), amount, txnfee) + hash, _, err := bridge.BurnZCN(amount) if err != nil { return errors.Wrap("burnZCN", "failed to burn ZCN tokens", err).Error() } - return tx.GetHash() + return hash } // mintZCN Mints ZCN tokens and returns a hash of the mint transaction @@ -94,10 +89,7 @@ func mintZCN(burnTrxHash string, timeout int) string { //nolint return errors.Wrap("mintZCN", "failed to QueryZChainMintPayload", err).Error() } - c, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second) - defer cancel() - - hash, err := bridge.MintZCN(c, mintPayload) + hash, err := bridge.MintZCN(mintPayload) if err != nil { return errors.Wrap("mintZCN", "failed to MintZCN for txn "+hash, err).Error() } @@ -107,7 +99,7 @@ func mintZCN(burnTrxHash string, timeout int) string { //nolint // getMintWZCNPayload returns the mint payload for the given burn transaction hash // - burnTrxHash: hash of the burn transaction -func getMintWZCNPayload(burnTrxHash string) string { +func getMintWZCNPayload(burnTrxHash string) string { //nolint:unused mintPayload, err := bridge.QueryEthereumMintPayload(burnTrxHash) if err != nil { return errors.Wrap("getMintWZCNPayload", "failed to query ethereum mint payload", err).Error() @@ -123,21 +115,18 @@ func getMintWZCNPayload(burnTrxHash string) string { // getNotProcessedWZCNBurnEvents returns all not processed WZCN burn events from the Ethereum network func getNotProcessedWZCNBurnEvents() string { - var mintNonce int64 - cb := wallet.NewZCNStatus(&mintNonce) - - cb.Begin() - - if err := zcncore.GetMintNonce(cb); err != nil { - return errors.Wrap("getNotProcessedWZCNBurnEvents", "failed to retreive last ZCN processed mint nonce", err).Error() - } + var ( + mintNonce int64 + res []byte + err error + ) - if err := cb.Wait(); err != nil { + if res, err = zcncore.GetMintNonce(); err != nil { return errors.Wrap("getNotProcessedWZCNBurnEvents", "failed to retreive last ZCN processed mint nonce", err).Error() } - if !cb.Success { - return errors.New("getNotProcessedWZCNBurnEvents", "failed to retreive last ZCN processed mint nonce").Error() + if err = json.Unmarshal(res, &mintNonce); err != nil { + return errors.New("getNotProcessedWZCNBurnEvents", "failed to unmarshall last ZCN processed mint nonce").Error() } log.Logger.Debug("MintNonce = " + strconv.Itoa(int(mintNonce))) @@ -156,27 +145,24 @@ func getNotProcessedWZCNBurnEvents() string { } // getNotProcessedZCNBurnTickets Returns all not processed ZCN burn tickets burned for a certain ethereum address -func getNotProcessedZCNBurnTickets() string { +func getNotProcessedZCNBurnTickets() string { //nolint:unused userNonce, err := bridge.GetUserNonceMinted(context.Background(), bridge.EthereumAddress) if err != nil { return errors.Wrap("getNotProcessedZCNBurnTickets", "failed to retreive user nonce", err).Error() } - var burnTickets []zcncore.BurnTicket - cb := wallet.NewZCNStatus(&burnTickets) - cb.Begin() + var ( + res []byte + burnTickets []zcncore.BurnTicket + ) - err = zcncore.GetNotProcessedZCNBurnTickets(bridge.EthereumAddress, userNonce.String(), cb) + res, err = zcncore.GetNotProcessedZCNBurnTickets(bridge.EthereumAddress, userNonce.String()) if err != nil { return errors.Wrap("getNotProcessedZCNBurnTickets", "failed to retreive ZCN burn tickets", err).Error() } - if err := cb.Wait(); err != nil { - return errors.Wrap("getNotProcessedZCNBurnTickets", "failed to retreive ZCN burn tickets", err).Error() - } - - if !cb.Success { - return errors.New("getNotProcessedZCNBurnTickets", "failed to retreive ZCN burn tickets").Error() + if err = json.Unmarshal(res, &burnTickets); err != nil { + return errors.New("getNotProcessedZCNBurnTickets", "failed to unmarshall ZCN burn tickets").Error() } var result []byte diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 78e92236e..9e0d8c9e1 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -8,9 +8,9 @@ import ( "errors" "time" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/wasmsdk/common.go b/wasmsdk/common.go index 7c9f4f8ac..a5f22744c 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -7,8 +7,8 @@ import ( "errors" "syscall/js" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) // PrintError is to print to stderr diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index c8e988db4..02c903934 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,15 +7,13 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zcncore" "github.com/uptrace/bunrouter" ) func main() { - zcncore.InitSignatureScheme("bls0chain") - ctx, cf := context.WithCancel(context.Background()) router := bunrouter.New() @@ -36,7 +34,10 @@ func main() { } w.WriteHeader(http.StatusOK) - w.Write([]byte(wallet)) + _, err = w.Write([]byte(wallet)) + if err != nil { + return err + } return nil }) @@ -55,7 +56,7 @@ func main() { } -type statusBar struct { +type statusBar struct { //nolint:unused walletString string wg *sync.WaitGroup success bool diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index ade2924f7..f5ad11610 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -9,7 +9,7 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // JS does not have int64 so we must take a string instead of int64. @@ -115,7 +115,7 @@ func TransferEthTokens(this js.Value, p []js.Value) interface{} { return promiseConstructor.New(handler) } -// Exports public functions in github.com/0chain/gosdk/zcncore/ethwallet.go +// Exports public functions in github.com/0chain/gosdk_common/zcncore/ethwallet.go func IsValidEthAddress(this js.Value, p []js.Value) interface{} { ethAddr := p[0].String() success, err := zcncore.IsValidEthAddress(ethAddr) diff --git a/wasmsdk/jsbridge/async.go b/wasmsdk/jsbridge/async.go deleted file mode 100644 index 23d96910a..000000000 --- a/wasmsdk/jsbridge/async.go +++ /dev/null @@ -1,148 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "fmt" - "reflect" - "syscall/js" -) - -type AsyncInvoker func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) - -func Async(funcType reflect.Type) (AsyncInvoker, error) { - - outputBinder, err := NewOutputBuilder(funcType).Build() - if err != nil { - return nil, err - } - - switch funcType.NumOut() { - case 0: - return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - fmt.Println("[recover]", r) - } - }() - if err != nil { - jsErr := NewJsError(err.Error()) - resolve.Invoke(js.ValueOf(jsErr)) - return - } - - fn.Call(in) - resolve.Invoke() - - }, nil - case 1: - - outputType := funcType.Out(0) - //func(...)error - if outputType.String() == TypeError { - return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - fmt.Println("[recover]", r) - } - }() - if err != nil { - jsErr := NewJsError(err.Error()) - resolve.Invoke(js.ValueOf(jsErr)) - return - } - - output := fn.Call(in) - - if output[0].IsNil() { - resolve.Invoke() - } else { - args := outputBinder(output) - resolve.Invoke(args[0]) - } - }, nil - } else { //func(...) T - return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { - if err != nil { - jsErr := NewJsError(err.Error()) - resolve.Invoke(js.ValueOf(jsErr)) - return - } - - output := fn.Call(in) - args := outputBinder(output) - resolve.Invoke(args[0]) - }, nil - } - case 2: - - errOutputType := funcType.Out(1) - - if errOutputType.String() != TypeError { - return nil, ErrFuncNotSupported - } - //func(...) (T,error) - return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - fmt.Println("[recover]", r) - } - }() - if err != nil { - jsErr := NewJsError(err.Error()) - resolve.Invoke(js.ValueOf(jsErr)) - return - } - - output := fn.Call(in) - - args := outputBinder(output) - if output[1].IsNil() { - resolve.Invoke(args[0]) - } else { - resolve.Invoke(args[1]) - } - - }, nil - - default: - return nil, ErrFuncNotSupported - } - -} - -// This function try to execute wasm functions that are wrapped with "Promise" -// see: https://stackoverflow.com/questions/68426700/how-to-wait-a-js-async-function-from-golang-wasm/68427221#comment120939975_68427221 -func Await(awaitable js.Value) ([]js.Value, []js.Value) { - then := make(chan []js.Value) - defer close(then) - thenFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - then <- args - return nil - }) - defer thenFunc.Release() - - catch := make(chan []js.Value) - defer close(catch) - catchFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - errObj := args[0] - - // Print the error value - errValue := errObj.Get("message").String() - fmt.Println("catch error value:", errValue) - - catch <- args - return nil - }) - defer catchFunc.Release() - - awaitable.Call("then", thenFunc).Call("catch", catchFunc) - - select { - case result := <-then: - return result, []js.Value{js.Null()} - case err := <-catch: - return []js.Value{js.Null()}, err - } -} diff --git a/wasmsdk/jsbridge/bytes.go b/wasmsdk/jsbridge/bytes.go deleted file mode 100644 index 9a5d74972..000000000 --- a/wasmsdk/jsbridge/bytes.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "strconv" - "strings" -) - -type Bytes struct { - Buffer []byte -} - -func (bytes *Bytes) UnmarshalJSON(buf []byte) error { - - if len(buf) > 0 { - - src := strings.Trim(string(buf), "\"") - - if len(src) > 0 { - items := strings.Split(src, ",") - - bytes.Buffer = make([]byte, len(items)) - - for k, v := range items { - it, err := strconv.ParseUint(v, 10, 64) - if err != nil { - return err - } - - bytes.Buffer[k] = byte(it) - } - - } - - } - - return nil -} diff --git a/wasmsdk/jsbridge/doc.go b/wasmsdk/jsbridge/doc.go deleted file mode 100644 index 01fc635d3..000000000 --- a/wasmsdk/jsbridge/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// 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/jsbridge/error.go b/wasmsdk/jsbridge/error.go deleted file mode 100644 index 371f0e71a..000000000 --- a/wasmsdk/jsbridge/error.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import "errors" - -var ( - // ErrMismatchedInputLength the length of input are mismatched - ErrMismatchedInputLength = errors.New("binder: mismatched input length") - - // ErrMismatchedOutputLength the length of output are mismatched - ErrMismatchedOutputLength = errors.New("binder: mismatched output length") - - // ErrBinderNotImplemented the type binder is not implemented yet - ErrBinderNotImplemented = errors.New("binder: not impelmented") - - // ErrFuncNotSupported the type function is not supported yet - ErrFuncNotSupported = errors.New("func: not supported") - - // ErrIsNotFunc bind works with func only - ErrIsNotFunc = errors.New("func: bind works with func only") -) diff --git a/wasmsdk/jsbridge/file_reader.go b/wasmsdk/jsbridge/file_reader.go deleted file mode 100644 index 21b783917..000000000 --- a/wasmsdk/jsbridge/file_reader.go +++ /dev/null @@ -1,124 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "errors" - "io" - "syscall/js" - - "github.com/0chain/gosdk_common/core/common" - "github.com/valyala/bytebufferpool" -) - -type FileReader struct { - size int64 - offset int64 - readChunk js.Value - buf []byte - bufOffset int - chunkReadSize int64 - endOfFile bool -} - -const ( - bufferSize = 16 * 1024 * 1024 //16MB -) - -func NewFileReader(readChunkFuncName string, fileSize, chunkReadSize int64) (*FileReader, error) { - readChunk := js.Global().Get(readChunkFuncName) - return &FileReader{ - size: fileSize, - readChunk: readChunk, - chunkReadSize: chunkReadSize, - }, nil -} - -func (r *FileReader) Read(p []byte) (int, error) { - //js.Value doesn't work in parallel invoke - size := len(p) - if len(r.buf) == 0 && !r.endOfFile { - r.initBuffer() - } - - if len(r.buf)-r.bufOffset < size && !r.endOfFile { - r.bufOffset = 0 //reset buffer offset - result, err := Await(r.readChunk.Invoke(r.offset, len(r.buf))) - - if len(err) > 0 && !err[0].IsNull() { - return 0, errors.New("file_reader: " + err[0].String()) - } - - chunk := result[0] - - n := js.CopyBytesToGo(r.buf, chunk) - r.offset += int64(n) - if n < len(r.buf) { - r.buf = r.buf[:n] - r.endOfFile = true - } - } - - n := copy(p, r.buf[r.bufOffset:]) - r.bufOffset += n - if r.endOfFile && r.bufOffset == len(r.buf) { - buff := &bytebufferpool.ByteBuffer{ - B: r.buf, - } - common.MemPool.Put(buff) - return n, io.EOF - } - - return n, nil -} - -func (r *FileReader) initBuffer() error { - bufSize := r.size - if bufferSize < bufSize { - bufSize = (r.chunkReadSize * (bufferSize / r.chunkReadSize)) - } - buff := common.MemPool.Get() - if cap(buff.B) < int(bufSize) { - buff.B = make([]byte, bufSize) - } - r.buf = buff.B[:bufSize] - result, err := Await(r.readChunk.Invoke(0, len(r.buf))) - - if len(err) > 0 && !err[0].IsNull() { - return errors.New("file_reader: " + err[0].String()) - } - - chunk := result[0] - - n := js.CopyBytesToGo(r.buf, chunk) - r.offset += int64(n) - if n < len(r.buf) { - r.buf = r.buf[:n] - } - r.endOfFile = len(r.buf) == int(r.size) - return nil -} - -func (r *FileReader) Seek(offset int64, whence int) (int64, error) { - - var abs int64 - switch whence { - case io.SeekStart: - abs = offset - case io.SeekCurrent: - abs = r.offset + offset - case io.SeekEnd: - abs = r.size + offset - default: - return 0, errors.New("FileReader.Seek: invalid whence") - } - if abs < 0 { - return 0, errors.New("FileReader.Seek: negative position") - } - if abs > int64(len(r.buf)) { - return 0, errors.New("FileReader.Seek: position out of bounds") - } - r.bufOffset = int(abs) - return abs, nil -} diff --git a/wasmsdk/jsbridge/file_writer.go b/wasmsdk/jsbridge/file_writer.go deleted file mode 100644 index 3cb1cfa85..000000000 --- a/wasmsdk/jsbridge/file_writer.go +++ /dev/null @@ -1,241 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "errors" - "io/fs" - "syscall/js" - - "github.com/0chain/gosdk_common/core/common" - "github.com/valyala/bytebufferpool" -) - -type FileWriter struct { - writableStream js.Value - uint8Array js.Value - fileHandle js.Value - bufLen int - buf []byte - bufWriteOffset int - writeError bool -} - -const writeBlocks = 10 - -// len(p) will always be <= 64KB -func (w *FileWriter) Write(p []byte) (int, error) { - //init buffer if not initialized - if len(w.buf) == 0 { - w.buf = make([]byte, len(p)*writeBlocks) - } - - //copy bytes to buf - if w.bufWriteOffset+len(p) > len(w.buf) { - err := w.flush() - if err != nil { - return 0, err - } - } - n := copy(w.buf[w.bufWriteOffset:], p) - w.bufWriteOffset += n - if w.bufWriteOffset == len(w.buf) { - //write to file - err := w.flush() - if err != nil { - return 0, err - } - } - return len(p), nil -} - -func (w *FileWriter) flush() error { - if w.bufWriteOffset == 0 { - return nil - } - if w.bufLen != w.bufWriteOffset { - w.bufLen = w.bufWriteOffset - w.uint8Array = js.Global().Get("Uint8Array").New(w.bufLen) - } - js.CopyBytesToJS(w.uint8Array, w.buf[:w.bufWriteOffset]) - _, err := Await(w.writableStream.Call("write", w.uint8Array)) - if len(err) > 0 && !err[0].IsNull() { - w.writeError = true - return errors.New("file_writer: " + err[0].String()) - } - //reset buffer - w.bufWriteOffset = 0 - return nil -} - -// func (w *FileWriter) WriteAt(p []byte, offset int64) (int, error) { -// uint8Array := js.Global().Get("Uint8Array").New(len(p)) -// js.CopyBytesToJS(uint8Array, p) -// options := js.Global().Get("Object").New() -// options.Set("type", "write") -// options.Set("position", offset) -// options.Set("data", uint8Array) -// options.Set("size", len(p)) -// _, err := Await(w.writableStream.Call("write", options)) -// if len(err) > 0 && !err[0].IsNull() { -// return 0, errors.New("file_writer: " + err[0].String()) -// } -// return len(p), nil -// } - -func (w *FileWriter) Close() error { - - if w.bufWriteOffset > 0 && !w.writeError { - w.buf = w.buf[:w.bufWriteOffset] - uint8Array := js.Global().Get("Uint8Array").New(len(w.buf)) - js.CopyBytesToJS(uint8Array, w.buf) - _, err := Await(w.writableStream.Call("write", uint8Array)) - if len(err) > 0 && !err[0].IsNull() { - return errors.New("file_writer: " + err[0].String()) - } - } - - _, err := Await(w.writableStream.Call("close")) - if len(err) > 0 && !err[0].IsNull() { - return errors.New("file_writer: " + err[0].String()) - } - return nil -} - -func (w *FileWriter) Read(p []byte) (int, error) { - return 0, errors.New("file_writer: not supported") -} - -func (w *FileWriter) Seek(offset int64, whence int) (int64, error) { - return 0, nil -} - -func (w *FileWriter) Sync() error { - return nil -} - -func (w *FileWriter) Stat() (fs.FileInfo, error) { - return nil, nil -} - -func NewFileWriter(filename string) (*FileWriter, error) { - - if !js.Global().Get("window").Get("showSaveFilePicker").Truthy() || !js.Global().Get("window").Get("WritableStream").Truthy() { - return nil, errors.New("file_writer: not supported") - } - - showSaveFilePicker := js.Global().Get("window").Get("showSaveFilePicker") - //create options with suggested name - options := js.Global().Get("Object").New() - options.Set("suggestedName", filename) - - //request a file handle - fileHandle, err := Await(showSaveFilePicker.Invoke(options)) - if len(err) > 0 && !err[0].IsNull() { - return nil, errors.New("file_writer: " + err[0].String()) - } - //create a writable stream - writableStream, err := Await(fileHandle[0].Call("createWritable")) - if len(err) > 0 && !err[0].IsNull() { - return nil, errors.New("file_writer: " + err[0].String()) - } - return &FileWriter{ - writableStream: writableStream[0], - fileHandle: fileHandle[0], - }, nil -} - -func NewFileWriterFromHandle(dirHandler js.Value, name string) (*FileWriter, error) { - options := js.Global().Get("Object").New() - options.Set("create", true) - fileHandler, err := Await(dirHandler.Call("getFileHandle", name, options)) - if len(err) > 0 && !err[0].IsNull() { - return nil, errors.New("dir_picker: " + err[0].String()) - } - - writableStream, err := Await(fileHandler[0].Call("createWritable")) - if len(err) > 0 && !err[0].IsNull() { - return nil, errors.New("file_writer: " + err[0].String()) - } - return &FileWriter{ - writableStream: writableStream[0], - fileHandle: fileHandler[0], - }, nil -} - -type FileCallbackWriter struct { - writeChunk js.Value - buf []byte - offset int64 - lookupHash string -} - -const bufCallbackCap = 4 * 1024 * 1024 //4MB - -func NewFileCallbackWriter(writeChunkFuncName, lookupHash string) *FileCallbackWriter { - writeChunk := js.Global().Get(writeChunkFuncName) - if !writeChunk.Truthy() { - return nil - } - return &FileCallbackWriter{ - writeChunk: writeChunk, - lookupHash: lookupHash, - } -} - -func (wc *FileCallbackWriter) Write(p []byte) (int, error) { - if len(wc.buf) == 0 { - buff := common.MemPool.Get() - if cap(buff.B) < bufCallbackCap { - buff.B = make([]byte, 0, bufCallbackCap) - } - wc.buf = buff.B - } - if len(wc.buf)+len(p) > cap(wc.buf) { - uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) - js.CopyBytesToJS(uint8Array, wc.buf) - _, err := Await(wc.writeChunk.Invoke(wc.lookupHash, uint8Array, wc.offset)) - if len(err) > 0 && !err[0].IsNull() { - return 0, errors.New("file_writer: " + err[0].String()) - } - wc.offset += int64(len(wc.buf)) - wc.buf = wc.buf[:0] - } - wc.buf = append(wc.buf, p...) - return len(p), nil -} - -func (wc *FileCallbackWriter) Close() error { - if len(wc.buf) > 0 { - uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) - js.CopyBytesToJS(uint8Array, wc.buf) - _, err := Await(wc.writeChunk.Invoke(wc.lookupHash, uint8Array, wc.offset)) - if len(err) > 0 && !err[0].IsNull() { - return errors.New("file_writer: " + err[0].String()) - } - wc.offset += int64(len(wc.buf)) - wc.buf = wc.buf[:0] - } - buff := &bytebufferpool.ByteBuffer{ - B: wc.buf, - } - common.MemPool.Put(buff) - return nil -} - -func (wc *FileCallbackWriter) Read(p []byte) (int, error) { - return 0, errors.New("file_writer: not supported") -} - -func (wc *FileCallbackWriter) Seek(offset int64, whence int) (int64, error) { - return 0, nil -} - -func (wc *FileCallbackWriter) Sync() error { - return nil -} - -func (wc *FileCallbackWriter) Stat() (fs.FileInfo, error) { - return nil, nil -} diff --git a/wasmsdk/jsbridge/func.go b/wasmsdk/jsbridge/func.go deleted file mode 100644 index bc4f08429..000000000 --- a/wasmsdk/jsbridge/func.go +++ /dev/null @@ -1,171 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "fmt" - "log" - "reflect" - "syscall/js" -) - -// BindFunc bind go func to js func in global -// only support -// - func(...) -// - func(...) error -// - func(...) T -// - func(...) (T,error) -func BindFunc(global js.Value, jsFuncName string, fn interface{}) error { - - jsFunc, err := promise(fn) - if err != nil { - return err - } - - global.Set(jsFuncName, jsFunc) - - return nil -} - -func BindAsyncFuncs(global js.Value, fnList map[string]interface{}) { - - for jsFuncName, fn := range fnList { - if jsFuncName == "registerAuthorizer" || jsFuncName == "callAuth" || jsFuncName == "registerAuthCommon" { - global.Set(jsFuncName, fn) - } else { - jsFunc, err := promise(fn) - - if err != nil { - log.Println("bridge promise failed:", jsFuncName, err) - } - - global.Set(jsFuncName, jsFunc) - } - } -} - -func BindFuncs(global js.Value, fnList map[string]interface{}) { - - for jsFuncName, fn := range fnList { - jsFunc, err := invoke(fn) - - if err != nil { - log.Println("[", jsFuncName, "]", err) - continue - } - - global.Set(jsFuncName, jsFunc) - } - -} - -func invoke(fn interface{}) (js.Func, error) { - funcType := reflect.TypeOf(fn) - - if funcType.Kind() != reflect.Func { - return js.Func{}, ErrIsNotFunc - } - - numOut := funcType.NumOut() - - if numOut > 2 { - return js.Func{}, ErrFuncNotSupported - } - - syncInvoker, err := Sync(funcType) - - if err != nil { - return js.Func{}, err - } - - invoker := reflect.ValueOf(fn) - - if err != nil { - return js.Func{}, err - } - - inputBuilder, err := NewInputBuilder(funcType).Build() - - if err != nil { - return js.Func{}, err - } - - jsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - defer func() { - if r := recover(); r != nil { - fmt.Println("[recover]", r) - } - }() - - in, err := inputBuilder(args) - if err != nil { - return NewJsError(err.Error()) - } - - result := syncInvoker(invoker, in) - - return result - }) - - jsFuncList = append(jsFuncList, jsFunc) - - return jsFunc, nil -} - -func promise(fn interface{}) (js.Func, error) { - funcType := reflect.TypeOf(fn) - - if funcType.Kind() != reflect.Func { - return js.Func{}, ErrIsNotFunc - } - - numOut := funcType.NumOut() - - if numOut > 2 { - return js.Func{}, ErrFuncNotSupported - } - - awaiter, err := Async(funcType) - - if err != nil { - return js.Func{}, err - } - - inputBuilder, err := NewInputBuilder(funcType).Build() - - if err != nil { - return js.Func{}, err - } - - invoker := reflect.ValueOf(fn) - - jsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - - defer func() { - if r := recover(); r != nil { - fmt.Println("[recover]", r) - } - }() - - in, err := inputBuilder(args) - - handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - resolve := args[0] - reject := args[1] - - go awaiter(resolve, reject, invoker, in, err) - - return nil - }) - - jsFuncList = append(jsFuncList, handler) - - promise := js.Global().Get("Promise") - return promise.New(handler) - }) - - jsFuncList = append(jsFuncList, jsFunc) - - return jsFunc, nil -} diff --git a/wasmsdk/jsbridge/func_test.go b/wasmsdk/jsbridge/func_test.go deleted file mode 100644 index e1a41a72e..000000000 --- a/wasmsdk/jsbridge/func_test.go +++ /dev/null @@ -1,88 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "syscall/js" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestBindAsyncFunc(t *testing.T) { - tests := []struct { - Name string - Func func() js.Func - Output func(outputs []js.Value) interface{} - Result interface{} - }{ - {Name: "ReturnString", Func: func() js.Func { - fn, _ := promise(func() string { - return "ReturnString" - }) - - return fn - }, Output: func(outputs []js.Value) interface{} { - return outputs[0].String() - }, Result: "ReturnString"}, - {Name: "ReturnInt", Func: func() js.Func { - fn, _ := promise(func() int { - return 1 - }) - - return fn - }, Output: func(outputs []js.Value) interface{} { - return outputs[0].Int() - }, Result: 1}, - {Name: "ReturnInt32", Func: func() js.Func { - fn, _ := promise(func() int32 { - return int32(1) - }) - - return fn - }, Output: func(outputs []js.Value) interface{} { - return int32(outputs[0].Int()) - }, Result: int32(1)}, - {Name: "ReturnInt64", Func: func() js.Func { - fn, _ := promise(func() int64 { - return int64(1) - }) - - return fn - }, Output: func(outputs []js.Value) interface{} { - return int64(outputs[0].Int()) - }, Result: int64(1)}, - {Name: "ReturnFloat32", Func: func() js.Func { - fn, _ := promise(func() float32 { - return float32(1) - }) - - return fn - }, Output: func(outputs []js.Value) interface{} { - return float32(outputs[0].Float()) - }, Result: float32(1)}, - {Name: "ReturnFloat64", Func: func() js.Func { - fn, _ := promise(func() float64 { - return float64(1) - }) - - return fn - }, Output: func(outputs []js.Value) interface{} { - return outputs[0].Float() - }, Result: float64(1)}, - } - - for _, it := range tests { - t.Run(it.Name, func(test *testing.T) { - - jsFunc := it.Func() - - outputs, _ := Await(jsFunc.Invoke()) - - require.Equal(test, it.Result, it.Output(outputs)) - - }) - } - -} diff --git a/wasmsdk/jsbridge/input.go b/wasmsdk/jsbridge/input.go deleted file mode 100644 index 5b3fb5831..000000000 --- a/wasmsdk/jsbridge/input.go +++ /dev/null @@ -1,285 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "fmt" - "reflect" - "syscall/js" -) - -// InputBinder convert inputs from js.Value to reflect.Value -type InputBinder func([]js.Value) ([]reflect.Value, error) - -// InputBuilder binder builder -type InputBuilder struct { - fn reflect.Type - numIn int - IsVariadic bool - binders []func(jv js.Value) (reflect.Value, error) -} - -// NewInputBuilder create InputBuilder -func NewInputBuilder(fn reflect.Type) *InputBuilder { - return &InputBuilder{ - fn: fn, - numIn: fn.NumIn(), - IsVariadic: fn.IsVariadic(), - } -} - -// Build build InputBinder -// js.ValueOf returns x as a JavaScript value: -// -// | Go | JavaScript | -// | ---------------------- | ---------------------- | -// | js.Value | [its value] | -// | js.Func | function | -// | nil | null | -// | bool | boolean | -// | integers and floats | number | -// | string | string | -// | []interface{} | new array | -// | map[string]interface{} | new object | -// -// Panics if x is not one of the expected types. -func (b *InputBuilder) Build() (InputBinder, error) { - defer func() { - if r := recover(); r != nil { - fmt.Println("[recover]InputBuilder.Build: ", r) - } - }() - - b.binders = make([]func(jv js.Value) (reflect.Value, error), b.numIn) - - if b.IsVariadic { - b.numIn-- - } - - for i := 0; i < b.numIn; i++ { - inputType := b.fn.In(i) - - v := reflect.New(inputType).Interface() - - switch v.(type) { - case *string: - b.binders[i] = jsValueToString - - case *int: - b.binders[i] = jsValueToInt - case *int32: - b.binders[i] = jsValueToInt32 - case *int64: - b.binders[i] = jsValueToInt64 - case *uint64: - b.binders[i] = jsValueToUInt64 - case *float32: - b.binders[i] = jsValueToFloat32 - case *float64: - b.binders[i] = jsValueToFloat64 - case *bool: - b.binders[i] = jsValueToBool - case *[]string: - b.binders[i] = jsValueToStringSlice - case *[]byte: - b.binders[i] = jsValueToBytes - default: - fmt.Printf("TYPE: %#v\n", reflect.TypeOf(v)) - return nil, ErrBinderNotImplemented - } - - } - - return b.Bind, nil -} - -// Bind bind js inputs to reflect values -func (b *InputBuilder) Bind(args []js.Value) ([]reflect.Value, error) { - if len(args) != b.numIn { - fmt.Println("args:", args) - return nil, ErrMismatchedInputLength - } - - values := make([]reflect.Value, b.numIn) - for i := 0; i < b.numIn; i++ { - val, err := b.binders[i](args[i]) - if err != nil { - return nil, err - } - values[i] = val - } - - return values, nil -} - -func jsValueToString(jv js.Value) (val reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - - i := "" - if jv.Truthy() { - i = jv.String() - } - - val = reflect.ValueOf(i) - return -} - -func jsValueToInt(jv js.Value) (val reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - i := 0 - if jv.Truthy() { - i = jv.Int() - } - - val = reflect.ValueOf(i) - return -} - -func jsValueToInt32(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - i := 0 - if jv.Truthy() { - i = jv.Int() - } - - val = reflect.ValueOf(int32(i)) - return -} - -func jsValueToInt64(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - i := 0 - if jv.Truthy() { - i = jv.Int() - } - - val = reflect.ValueOf(int64(i)) - return -} - -func jsValueToUInt64(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - i := 0 - if jv.Truthy() { - i = jv.Int() - } - - val = reflect.ValueOf(uint64(i)) - return -} - -func jsValueToBool(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - i := false - if jv.Truthy() { - i = jv.Bool() - } - - val = reflect.ValueOf(i) - return -} - -func jsValueToFloat32(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - var i float64 - if jv.Truthy() { - i = jv.Float() - } - - val = reflect.ValueOf(float32(i)) - return -} - -func jsValueToFloat64(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - var i float64 - if jv.Truthy() { - i = jv.Float() - } - - val = reflect.ValueOf(i) - return -} - -func jsValueToStringSlice(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - var list []string - - if jv.Truthy() { - if js.Global().Get("Array").Call("isArray", jv).Bool() { - list = make([]string, jv.Length()) - for i := 0; i < len(list); i++ { - it := jv.Index(i) - if it.Truthy() { - list[i] = it.String() - } - } - } - } - - val = reflect.ValueOf(list) - return -} - -func jsValueToBytes(jv js.Value) (val reflect.Value, err error) { - - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("input: %s", r) - } - }() - - var buf []byte - - if jv.Truthy() { - buf = make([]byte, jv.Length()) - js.CopyBytesToGo(buf, jv) - } - - val = reflect.ValueOf(buf) - return -} diff --git a/wasmsdk/jsbridge/input_test.go b/wasmsdk/jsbridge/input_test.go deleted file mode 100644 index 36665bbc4..000000000 --- a/wasmsdk/jsbridge/input_test.go +++ /dev/null @@ -1,105 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "crypto/rand" - "encoding/hex" - "reflect" - "strings" - "syscall/js" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestInputBinder(t *testing.T) { - - buf := make([]byte, 100) - rand.Read(buf) //nolint - - tests := []struct { - Name string - In []js.Value - Out interface{} - Func func() reflect.Value - }{ - {Name: "string", Func: func() reflect.Value { - fn := func(i string) string { - return i - } - - return reflect.ValueOf(fn) - }, In: []js.Value{js.ValueOf("1")}, Out: "1"}, - - {Name: "int", Func: func() reflect.Value { - fn := func(i int) int { - return i - } - - return reflect.ValueOf(fn) - }, In: []js.Value{js.ValueOf(1)}, Out: 1}, - {Name: "int32", Func: func() reflect.Value { - fn := func(i int32) int32 { - return i - } - - return reflect.ValueOf(fn) - }, In: []js.Value{js.ValueOf(1)}, Out: int32(1)}, - {Name: "int64", Func: func() reflect.Value { - fn := func(i int64) int64 { - return i - } - - return reflect.ValueOf(fn) - }, In: []js.Value{js.ValueOf(1)}, Out: int64(1)}, - - {Name: "float32", Func: func() reflect.Value { - fn := func(i float32) float32 { - return i - } - - return reflect.ValueOf(fn) - }, In: []js.Value{js.ValueOf(1)}, Out: float32(1)}, - {Name: "float64", Func: func() reflect.Value { - fn := func(i float64) float64 { - return i - } - - return reflect.ValueOf(fn) - }, In: []js.Value{js.ValueOf(1)}, Out: float64(1)}, - {Name: "[]string", Func: func() reflect.Value { - fn := func(list []string) string { - return strings.Join(list, ",") - } - - return reflect.ValueOf(fn) - }, In: []js.Value{NewArray("a", "b")}, Out: "a,b"}, - {Name: "[]byte", Func: func() reflect.Value { - fn := func(buf []byte) string { - return hex.EncodeToString(buf) - } - - return reflect.ValueOf(fn) - }, In: []js.Value{NewBytes(buf)}, Out: hex.EncodeToString(buf)}, - } - - for _, it := range tests { - t.Run(it.Name, func(test *testing.T) { - fn := it.Func() - b, err := NewInputBuilder(fn.Type()).Build() - - require.NoError(test, err) - - in, err := b(it.In) - require.NoError(test, err) - - out := fn.Call(in) - - require.Equal(test, it.Out, out[0].Interface()) - - }) - } - -} diff --git a/wasmsdk/jsbridge/object.go b/wasmsdk/jsbridge/object.go deleted file mode 100644 index cdae12a86..000000000 --- a/wasmsdk/jsbridge/object.go +++ /dev/null @@ -1,74 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "encoding/json" - "fmt" - "syscall/js" -) - -func NewArray(items ...interface{}) js.Value { - - defer func() { - if r := recover(); r != nil { - fmt.Println("NewStrings: ", r) - } - }() - - list := js.Global().Get("Array").New() - - for _, it := range items { - list.Call("push", js.ValueOf(it)) - } - - return list -} - -func NewJsError(message interface{}) js.Value { - return js.ValueOf(map[string]interface{}{ - "error": fmt.Sprint(message), - }) -} - -func NewObject(obj interface{}) js.Value { - buf, err := json.Marshal(obj) - if err != nil { - return js.Null() - } - - j := js.Global().Get("JSON") - - return j.Call("parse", string(buf)) -} - -func NewBytes(buf []byte) js.Value { - - uint8Array := js.Global().Get("Uint8Array").New(len(buf)) - - js.CopyBytesToJS(uint8Array, buf) - - return uint8Array -} - -// var arrayBuffer = new ArrayBuffer(100); -// var uint8Array = new Uint8Array(arrayBuffer); -// for (var i = 0; i < 100; i++) { -// uint8Array[i] = i; -// } - -// var blob = new Blob([uint8Array], { type: "image/png" }); -// var blobVal = URL.createObjectURL(blob); -// func CreateObjectURL(buf []byte) string { -// j := js.Global().Get("URL") - -// options := js.Global().Get("Object").New() -// options.Set("type", "") - -// blob := js.Global().Get("Blob").New(args ...interface{}) - -// u := j.Call("createObjectURL", object) - -// return u.String() -// } diff --git a/wasmsdk/jsbridge/output.go b/wasmsdk/jsbridge/output.go deleted file mode 100644 index 6e2560523..000000000 --- a/wasmsdk/jsbridge/output.go +++ /dev/null @@ -1,100 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "reflect" - "syscall/js" -) - -// OutputBinder convert Outputs from js.Value to reflect.Value -type OutputBinder func([]reflect.Value) []js.Value - -// OutputBuilder binder builder -type OutputBuilder struct { - fn reflect.Type - numOut int - binders []func(rv reflect.Value) js.Value -} - -// NewOutputBuilder create OutputBuilder -func NewOutputBuilder(fn reflect.Type) *OutputBuilder { - return &OutputBuilder{ - fn: fn, - numOut: fn.NumOut(), - } -} - -// Build build OutputBinder -// js.ValueOf returns x as a JavaScript value: -// -// | Go | JavaScript | -// | ---------------------- | ---------------------- | -// | js.Value | [its value] | -// | js.Func | function | -// | nil | null | -// | bool | boolean | -// | integers and floats | number | -// | string | string | -// | []interface{} | new array | -// | map[string]interface{} | new object | -// -// Panics if x is not one of the expected types. -func (b *OutputBuilder) Build() (OutputBinder, error) { - - b.binders = make([]func(rv reflect.Value) js.Value, b.numOut) - - for i := 0; i < b.numOut; i++ { - outputType := b.fn.Out(i) - - // TODO: Fast path for basic types that do not require reflection. - switch outputType.String() { - case TypeError: - b.binders[i] = func(rv reflect.Value) js.Value { - if rv.IsNil() { - return js.Null() - } - - err := rv.Interface().(error) - if err != nil { - jsErr := NewJsError(err.Error()) - return js.ValueOf(jsErr) - } - return js.Null() - - } - case TypeBytes: - b.binders[i] = func(rv reflect.Value) js.Value { - if rv.IsNil() { - return js.Null() - } - - buf := rv.Interface().([]byte) - - return NewBytes(buf) - - } - default: - b.binders[i] = func(rv reflect.Value) js.Value { - - if rv.CanInterface() && rv.Interface() == nil { - return js.Null() - } - - return NewObject(rv.Interface()) - } - } - } - - return b.Bind, nil -} - -// Bind bind js Outputs to reflect values -func (b *OutputBuilder) Bind(args []reflect.Value) []js.Value { - values := make([]js.Value, b.numOut) - for i := 0; i < b.numOut; i++ { - values[i] = b.binders[i](args[i]) - } - return values -} diff --git a/wasmsdk/jsbridge/self.go b/wasmsdk/jsbridge/self.go deleted file mode 100644 index f3d979b91..000000000 --- a/wasmsdk/jsbridge/self.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "github.com/hack-pad/go-webworkers/worker" -) - -var ( - selfWorker *worker.GlobalSelf -) - -func NewSelfWorker() (*worker.GlobalSelf, error) { - worker, err := worker.Self() - if worker != nil { - selfWorker = worker - } - return selfWorker, err -} - -func GetSelfWorker() *worker.GlobalSelf { - return selfWorker -} diff --git a/wasmsdk/jsbridge/sync.go b/wasmsdk/jsbridge/sync.go deleted file mode 100644 index ca0c1a7b8..000000000 --- a/wasmsdk/jsbridge/sync.go +++ /dev/null @@ -1,103 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "reflect" - "syscall/js" -) - -type SyncInvoker func(fn reflect.Value, in []reflect.Value) js.Value - -func Sync(funcType reflect.Type) (SyncInvoker, error) { - outputBinder, err := NewOutputBuilder(funcType).Build() - if err != nil { - return nil, err - } - - switch funcType.NumOut() { - case 0: - return func(fn reflect.Value, in []reflect.Value) (result js.Value) { - - defer func() { - if r := recover(); r != nil { - result = NewJsError(r) - } - }() - - fn.Call(in) - - return - - }, nil - case 1: - outputType := funcType.Out(0) - //func(...)error - if outputType.String() == TypeError { - return func(fn reflect.Value, in []reflect.Value) (result js.Value) { - - defer func() { - if r := recover(); r != nil { - result = NewJsError(r) - } - }() - - err := fn.Call(in)[0] - - // err != nil - if !err.IsNil() { - result = NewJsError(err.Interface()) - } - - return - }, nil - } else { //func(...) T - return func(fn reflect.Value, in []reflect.Value) (result js.Value) { - - defer func() { - if r := recover(); r != nil { - result = NewJsError(r) - } - }() - - output := fn.Call(in) - - result = outputBinder(output)[0] - - return - - }, nil - } - case 2: - - errOutputType := funcType.Out(1) - - if errOutputType.String() != TypeError { - return nil, ErrFuncNotSupported - } - //func(...) (T,error) - return func(fn reflect.Value, in []reflect.Value) (result js.Value) { - defer func() { - if r := recover(); r != nil { - result = NewJsError(r) - } - }() - output := fn.Call(in) - - err := output[1] - - // err == nil - if err.IsNil() { - result = outputBinder(output)[0] - } else { - result = NewJsError(err.Interface()) - } - - return - }, nil - - default: - return nil, ErrFuncNotSupported - } -} diff --git a/wasmsdk/jsbridge/template_data.go b/wasmsdk/jsbridge/template_data.go deleted file mode 100644 index 80d18fd23..000000000 --- a/wasmsdk/jsbridge/template_data.go +++ /dev/null @@ -1,92 +0,0 @@ -//go:build js && wasm - -package jsbridge - -import ( - "bytes" - _ "embed" - "fmt" - "net/url" - "os" - "path" - "strings" - "syscall/js" - "text/template" - - "github.com/0chain/gosdk_common/core/version" -) - -//go:embed zcnworker.js.tpl -var WorkerJSTpl []byte - -func buildWorkerJS(args, env []string, path string) (string, error) { - return buildJS(args, env, path, WorkerJSTpl) -} - -func buildJS(args, env []string, wasmPath string, tpl []byte) (string, error) { - var workerJS bytes.Buffer - - if len(args) == 0 { - args = []string{wasmPath} - } - - if len(env) == 0 { - env = os.Environ() - } - var cachePath string - if uRL, err := url.ParseRequestURI(wasmPath); err != nil || !uRL.IsAbs() { - origin := js.Global().Get("location").Get("origin").String() - u, err := url.Parse(origin) - if err != nil { - return "", err - } - u.Path = path.Join(u.Path, wasmPath) - cachePath = u.String() - params := url.Values{} - params.Add("v", version.VERSIONSTR) - u.RawQuery = params.Encode() - wasmPath = u.String() - } - suffix := os.Getenv("SUFFIX") - if suffix == "" { - suffix = "dev" - } - cdnPath := fmt.Sprintf("https://webapps-staticfiles.s3.us-east-2.amazonaws.com/%s/enterprise-zcn.wasm", suffix) - data := templateData{ - Path: cdnPath, - Args: args, - Env: env, - FallbackPath: wasmPath, - CachePath: cachePath, - } - if err := template.Must(template.New("js").Parse(string(tpl))).Execute(&workerJS, data); err != nil { - return "", err - } - return workerJS.String(), nil -} - -type templateData struct { - Path string - Args []string - Env []string - FallbackPath string - CachePath string -} - -func (d templateData) ArgsToJS() string { - el := []string{} - for _, e := range d.Args { - el = append(el, `"`+e+`"`) - } - return "[" + strings.Join(el, ",") + "]" -} - -func (d templateData) EnvToJS() string { - el := []string{} - for _, entry := range d.Env { - if k, v, ok := strings.Cut(entry, "="); ok { - el = append(el, fmt.Sprintf(`"%s":"%s"`, k, v)) - } - } - return "{" + strings.Join(el, ",") + "}" -} diff --git a/wasmsdk/jsbridge/timer.go b/wasmsdk/jsbridge/timer.go deleted file mode 100644 index 289e2ad90..000000000 --- a/wasmsdk/jsbridge/timer.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "sync" - "syscall/js" - "time" -) - -type Timer struct { - sync.Mutex - id js.Value - enabled bool - interval time.Duration - callback func() -} - -func NewTimer(interval time.Duration, callback func()) *Timer { - return &Timer{ - interval: interval, - callback: callback, - } -} - -func (t *Timer) Start() { - t.Lock() - defer t.Unlock() - - if !t.enabled { - cb, _ := promise(t.updated) - t.id = js.Global().Call("setInterval", cb, t.interval.Milliseconds()) - t.enabled = true - } -} - -func (t *Timer) Stop() { - if t.enabled { - js.Global().Call("clearInterval", t.id) - } - - t.enabled = false -} - -func (t *Timer) updated() { - if t.enabled { - t.callback() - } -} diff --git a/wasmsdk/jsbridge/vars.go b/wasmsdk/jsbridge/vars.go deleted file mode 100644 index 99d42a24e..000000000 --- a/wasmsdk/jsbridge/vars.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "reflect" - "syscall/js" -) - -var ( - jsFuncList = make([]js.Func, 0, 200) -) - -var ( - TypeFunc = reflect.TypeOf(func() {}).String() - TypeError = "error" - TypeString = reflect.TypeOf("string").String() - TypeBytes = reflect.TypeOf([]byte{}).String() -) - -func Close() { - for _, fn := range jsFuncList { - fn.Release() - } -} diff --git a/wasmsdk/jsbridge/webworker.go b/wasmsdk/jsbridge/webworker.go deleted file mode 100644 index 33d281ab7..000000000 --- a/wasmsdk/jsbridge/webworker.go +++ /dev/null @@ -1,320 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package jsbridge - -import ( - "context" - "errors" - "fmt" - "strconv" - "sync" - "syscall/js" - - "github.com/google/uuid" - "github.com/hack-pad/go-webworkers/worker" - "github.com/hack-pad/safejs" -) - -const ( - MsgTypeAuth = "auth" - MsgTypeAuthRsp = "auth_rsp" - MsgTypeUpload = "upload" - MsgTypeUpdateWallet = "update_wallet" -) - -type WasmWebWorker struct { - // Name specifies an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes. - // If this is not specified, `Start` will create a UUIDv4 for it and populate back. - Name string - - // Path is the path of the WASM to run as the Web Worker. - // This can be a relative path on the server, or an abosolute URL. - Path string - - // Args holds command line arguments, including the WASM as Args[0]. - // If the Args field is empty or nil, Run uses {Path}. - Args []string - - // Env specifies the environment of the process. - // Each entry is of the form "key=value". - // If Env is nil, the new Web Worker uses the current context's - // environment. - // If Env contains duplicate environment keys, only the last - // value in the slice for each duplicate key is used. - Env []string - worker *worker.Worker - - // For subscribing to events - ctx context.Context - cancelContext context.CancelFunc - subscribers map[string]chan worker.MessageEvent - numberOfSubs int - subMutex sync.Mutex - - //isTerminated bool - isTerminated bool -} - -var ( - workers = make(map[string]*WasmWebWorker) - gZauthServer string -) - -func NewWasmWebWorker(blobberID, blobberURL, clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) (*WasmWebWorker, bool, error) { - created := false - _, ok := workers[blobberID] - if ok { - return workers[blobberID], created, nil - } - - fmt.Println("New wasm web worker, zauth server:", gZauthServer) - w := &WasmWebWorker{ - Name: blobberURL, - Env: []string{"BLOBBER_URL=" + blobberURL, - "CLIENT_ID=" + clientID, - "CLIENT_KEY=" + clientKey, - "PEER_PUBLIC_KEY=" + peerPublicKey, - "PRIVATE_KEY=" + privateKey, - "MODE=worker", - "PUBLIC_KEY=" + publicKey, - "IS_SPLIT=" + strconv.FormatBool(isSplit), - "MNEMONIC=" + mnemonic, - "ZAUTH_SERVER=" + gZauthServer}, - Path: "enterprise-zcn.wasm", - subscribers: make(map[string]chan worker.MessageEvent), - } - - if err := w.Start(); err != nil { - return nil, created, err - } - workers[blobberID] = w - created = true - return w, created, nil -} - -func GetWorker(blobberID string) *WasmWebWorker { - return workers[blobberID] -} - -func RemoveWorker(blobberID string) { - worker, ok := workers[blobberID] - if ok { - worker.subMutex.Lock() - if worker.numberOfSubs == 0 { - worker.Terminate() - delete(workers, blobberID) - worker.isTerminated = true - } - worker.subMutex.Unlock() - } -} - -// pass a buffered channel to subscribe to events so that the caller is not blocked -func (ww *WasmWebWorker) SubscribeToEvents(remotePath string, ch chan worker.MessageEvent) error { - if ch == nil { - return errors.New("channel is nil") - } - ww.subMutex.Lock() - if ww.isTerminated { - ww.subMutex.Unlock() - return errors.New("worker is terminated") - } - ww.subscribers[remotePath] = ch - ww.numberOfSubs++ - //start the worker listener if there are subscribers - if ww.numberOfSubs == 1 { - ctx, cancel := context.WithCancel(context.Background()) - ww.ctx = ctx - ww.cancelContext = cancel - eventChan, err := ww.Listen(ctx) - if err != nil { - ww.subMutex.Unlock() - return err - } - go ww.ListenForEvents(eventChan) - } - ww.subMutex.Unlock() - return nil -} - -func (ww *WasmWebWorker) UnsubscribeToEvents(remotePath string) { - ww.subMutex.Lock() - ch, ok := ww.subscribers[remotePath] - if ok { - close(ch) - delete(ww.subscribers, remotePath) - ww.numberOfSubs-- - //stop the worker listener if there are no subscribers - if ww.numberOfSubs == 0 { - ww.cancelContext() - } - } - ww.subMutex.Unlock() -} - -func (ww *WasmWebWorker) ListenForEvents(eventChan <-chan worker.MessageEvent) { - for { - select { - case <-ww.ctx.Done(): - return - case event, ok := <-eventChan: - if !ok { - return - } - //get remote path from the event - data, err := event.Data() - // if above throws an error, pass it to all the subscribers - if err != nil { - ww.removeAllSubscribers() - return - } - remotePathObject, err := data.Get("remotePath") - if err != nil { - ww.removeAllSubscribers() - return - } - remotePath, _ := remotePathObject.String() - if remotePath == "" { - ww.removeAllSubscribers() - return - } - ww.subMutex.Lock() - ch, ok := ww.subscribers[remotePath] - if ok { - ch <- event - } - ww.subMutex.Unlock() - } - } -} - -func (ww *WasmWebWorker) removeAllSubscribers() { - ww.subMutex.Lock() - for path, ch := range ww.subscribers { - close(ch) - delete(ww.subscribers, path) - ww.numberOfSubs-- - } - ww.cancelContext() - ww.subMutex.Unlock() -} - -func (ww *WasmWebWorker) Start() error { - workerJS, err := buildWorkerJS(ww.Args, ww.Env, ww.Path) - if err != nil { - return err - } - - if ww.Name == "" { - ww.Name = uuid.New().String() - } - - wk, err := worker.NewFromScript(workerJS, worker.Options{Name: ww.Name}) - if err != nil { - return err - } - - ww.worker = wk - - return nil -} - -// PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers. -func (ww *WasmWebWorker) PostMessage(data safejs.Value, transfers []safejs.Value) error { - return ww.worker.PostMessage(data, transfers) -} - -// Terminate immediately terminates the Worker. -func (ww *WasmWebWorker) Terminate() { - ww.worker.Terminate() -} - -// Listen sends message events on a channel for events fired by self.postMessage() calls inside the Worker's global scope. -// Stops the listener and closes the channel when ctx is canceled. -func (ww *WasmWebWorker) Listen(ctx context.Context) (<-chan worker.MessageEvent, error) { - return ww.worker.Listen(ctx) -} - -func SetZauthServer(zauthServer string) { - gZauthServer = zauthServer -} - -type PostWorker interface { - PostMessage(data safejs.Value, transferables []safejs.Value) error -} - -func PostMessage(w PostWorker, msgType string, data map[string]string) error { - msgTypeUint8Array := js.Global().Get("Uint8Array").New(len(msgType)) - js.CopyBytesToJS(msgTypeUint8Array, []byte(msgType)) - - obj := js.Global().Get("Object").New() - obj.Set("msgType", msgTypeUint8Array) - - for k, v := range data { - if k == "msgType" { - return errors.New("msgType is key word reserved") - } - - dataUint8Array := js.Global().Get("Uint8Array").New(len(v)) - js.CopyBytesToJS(dataUint8Array, []byte(v)) - obj.Set(k, dataUint8Array) - } - - return w.PostMessage(safejs.Safe(obj), nil) -} - -func GetMsgType(event worker.MessageEvent) (string, *safejs.Value, error) { - data, err := event.Data() - if err != nil { - return "", nil, err - } - - mt, err := data.Get("msgType") - if err != nil { - return "", nil, err - } - msgTypeLen, err := mt.Length() - if err != nil { - return "", nil, err - } - - mstType := make([]byte, msgTypeLen) - safejs.CopyBytesToGo(mstType, mt) - - return string(mstType), &data, nil -} - -func SetMsgType(data *js.Value, msgType string) { - msgTypeUint8Array := js.Global().Get("Uint8Array").New(len(msgType)) - js.CopyBytesToJS(msgTypeUint8Array, []byte(msgType)) - data.Set("msgType", msgTypeUint8Array) -} - -func ParseEventDataField(data *safejs.Value, field string) (string, error) { - fieldUint8Array, err := data.Get(field) - if err != nil { - return "", err - } - fieldLen, err := fieldUint8Array.Length() - if err != nil { - return "", err - } - - fieldData := make([]byte, fieldLen) - safejs.CopyBytesToGo(fieldData, fieldUint8Array) - - return string(fieldData), nil -} - -func PostMessageToAllWorkers(msgType string, data map[string]string) error { - for id, worker := range workers { - fmt.Println("post message to worker", id) - err := PostMessage(worker, msgType, data) - if err != nil { - return fmt.Errorf("failed to post message to worker: %s, err: %v", id, err) - } - } - - return nil -} diff --git a/wasmsdk/jsbridge/zcnworker.js.tpl b/wasmsdk/jsbridge/zcnworker.js.tpl deleted file mode 100644 index d082ff1d9..000000000 --- a/wasmsdk/jsbridge/zcnworker.js.tpl +++ /dev/null @@ -1,101 +0,0 @@ -importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.22.5/misc/wasm/wasm_exec.js','https://cdn.jsdelivr.net/gh/herumi/bls-wasm@v1.1.1/browser/bls.js'); - -const go = new Go(); -go.argv = {{.ArgsToJS}} -go.env = {{.EnvToJS}} -const bls = self.bls -bls.init(bls.BN254).then(()=>{}) - -async function getWasmModule() { - const cache = await caches.open('wasm-cache'); - let response = await cache.match("{{.CachePath}}"); - if(!response?.ok) { - response = await fetch("{{.Path}}").then(res => res).catch(err => err); - if (!response?.ok) { - response = await fetch("{{.FallbackPath}}").then(res => res).catch(err => err); - } - if (!response.ok) { - throw new Error(`Failed to fetch WASM: ${response.statusText}`); - } - } - const bytes = await response.arrayBuffer(); - return WebAssembly.instantiate(bytes, go.importObject); -} - -getWasmModule().then(result => { - go.run(result.instance); -}).catch(error => { - console.error("Failed to load WASM:", error); -}); - -function hexStringToByte(str) { - if (!str) return new Uint8Array() - - const a = [] - for (let i = 0, len = str.length; i < len; i += 2) { - a.push(parseInt(str.substr(i, 2), 16)) - } - - return new Uint8Array(a) - } - -self.__zcn_worker_wasm__ = { - sign: async (hash, secretKey) => { - if (!secretKey){ - const errMsg = 'err: wasm blsSign function requires a secret key' - console.warn(errMsg) - throw new Error(errMsg) - } - const bytes = hexStringToByte(hash) - const sk = bls.deserializeHexStrToSecretKey(secretKey) - const sig = sk.sign(bytes) - - if (!sig) { - const errMsg = 'err: wasm blsSign function failed to sign transaction' - console.warn(errMsg) - throw new Error(errMsg) - } - - return sig.serializeToHexStr() - }, - initProxyKeys: initProxyKeys, - verify: blsVerify, - verifyWith: blsVerifyWith, - addSignature: blsAddSignature -} - -async function initProxyKeys(publicKey, privateKey) { - const pubKey = bls.deserializeHexStrToPublicKey(publicKey) - const privKey = bls.deserializeHexStrToSecretKey(privateKey) - bls.publicKey = pubKey - bls.secretKey = privKey -} - -async function blsVerify(signature, hash) { - const bytes = hexStringToByte(hash) - const sig = bls.deserializeHexStrToSignature(signature) - return jsProxy.publicKey.verify(sig, bytes) -} - -async function blsVerifyWith(pk, signature, hash) { - const publicKey = bls.deserializeHexStrToPublicKey(pk) - const bytes = hexStringToByte(hash) - const sig = bls.deserializeHexStrToSignature(signature) - return publicKey.verify(sig, bytes) -} - -async function blsAddSignature(secretKey, signature, hash) { - const privateKey = bls.deserializeHexStrToSecretKey(secretKey) - const sig = bls.deserializeHexStrToSignature(signature) - var sig2 = privateKey.sign(hexStringToByte(hash)) - if (!sig2) { - const errMsg = - 'err: wasm blsAddSignature function failed to sign transaction' - console.warn(errMsg) - throw new Error(errMsg) - } - - sig.add(sig2) - - return sig.serializeToHexStr() -} diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index 8af595d97..fa81be29d 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,9 +11,9 @@ import ( "sync" "time" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zboxcore/marker" ) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 3f5c7ae73..ed8db6774 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -13,13 +13,13 @@ import ( "sync" "time" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zcncore" "github.com/hack-pad/safejs" @@ -269,12 +269,6 @@ func main() { "createfreeallocation": createfreeallocation, "getUpdateAllocTicket": getUpdateAllocTicket, - // readpool - "getReadPoolInfo": getReadPoolInfo, - "lockReadPool": lockReadPool, - "unLockReadPool": unLockReadPool, - "createReadPool": createReadPool, - // claim rewards "collectRewards": collectRewards, @@ -290,10 +284,6 @@ func main() { "allocationRepair": allocationRepair, "repairSize": repairSize, - //smartcontract - "executeSmartContract": executeSmartContract, - "faucet": faucet, - // bridge "initBridge": initBridge, "burnZCN": burnZCN, @@ -479,8 +469,8 @@ func main() { setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic, isSplit) hideLogs() - debug.SetGCPercent(75) - debug.SetMemoryLimit(1 * 1024 * 1024 * 1024) //1GB + debug.SetGCPercent(40) + debug.SetMemoryLimit(300 * 1024 * 1024) //300MB err = startListener(respChan) if err != nil { fmt.Println("Error starting listener", err) @@ -489,8 +479,8 @@ func main() { } hideLogs() - debug.SetGCPercent(75) - debug.SetMemoryLimit(3.5 * 1024 * 1024 * 1024) //3.5 GB + debug.SetGCPercent(40) + debug.SetMemoryLimit(2.5 * 1024 * 1024 * 1024) //2.5 GB <-make(chan bool) diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index c194cd061..e00b46c5e 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -11,11 +11,11 @@ import ( "os" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/imageutil" "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/zcncore" ) var CreateObjectURL func(buf []byte, mimeType string) string @@ -34,25 +34,19 @@ func initSDKs(chainID, blockWorker, signatureScheme string, minConfirmation, minSubmit, confirmationChainLength int, zboxHost, zboxAppType string, sharderconsensous int) error { + // Print the parameters beautified + fmt.Printf("{ chainID: %s, blockWorker: %s, signatureScheme: %s, minConfirmation: %d, minSubmit: %d, + confirmationChainLength: %d, zboxHost: %s, zboxAppType: %s, sharderConsensous: %d, isSplit: %t }\n", chainID, + blockWorker, signatureScheme, minConfirmation, minSubmit, + confirmationChainLength, zboxHost, zboxAppType, + sharderConsensous, isSplit) zboxApiClient.SetRequest(zboxHost, zboxAppType) - err := sdk.InitStorageSDK("{}", blockWorker, chainID, signatureScheme, nil, 0) + err := client.InitSDK("{}", blockWorker, chainID, signatureScheme, 0, false, false, minConfirmation, minSubmit, confirmationChainLength, sharderConsensous) if err != nil { fmt.Println("wasm: InitStorageSDK ", err) return err } - - err = zcncore.InitZCNSDK(blockWorker, signatureScheme, - zcncore.WithChainID(chainID), - zcncore.WithMinConfirmation(minConfirmation), - zcncore.WithMinSubmit(minSubmit), - zcncore.WithConfirmationChainLength(confirmationChainLength), - zcncore.WithSharderConsensous(sharderconsensous), - ) - - if err != nil { - return err - } sdk.SetWasm() return nil } @@ -162,5 +156,10 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro // - fee is the transaction fee // - desc is the description of the transaction func send(toClientID string, tokens uint64, fee uint64, desc string) (string, error) { - return sdk.ExecuteSmartContractSend(toClientID, tokens, fee, desc) + hash, _, _, _, err := zcncore.Send(toClientID, tokens, desc) + if err != nil { + return "", err + } + + return hash, nil } diff --git a/wasmsdk/smartcontract.go b/wasmsdk/smartcontract.go deleted file mode 100644 index 87f7db20f..000000000 --- a/wasmsdk/smartcontract.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/transaction" -) - -func faucet(methodName, input string, token float64) (*transaction.Transaction, error) { - 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) { - return sdk.ExecuteSmartContract(address, - transaction.SmartContractTxnData{ - Name: methodName, - InputArgs: json.RawMessage([]byte(input)), - }, value, 0) -} diff --git a/wasmsdk/tokenrate.go b/wasmsdk/tokenrate.go index 3d3253715..456206331 100644 --- a/wasmsdk/tokenrate.go +++ b/wasmsdk/tokenrate.go @@ -7,6 +7,6 @@ import ( ) // getUSDRate gets the USD rate for the given crypto symbol -func getUSDRate(symbol string) (float64, error) { +func getUSDRate(symbol string) (float64, error) { //nolint:unused return tokenrate.GetUSD(context.TODO(), symbol) } diff --git a/wasmsdk/updateImage.go b/wasmsdk/updateImage.go index c3ffce2ad..d2bf6fff3 100644 --- a/wasmsdk/updateImage.go +++ b/wasmsdk/updateImage.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strings" ) @@ -302,7 +301,7 @@ func doHTTPRequest(method, url, authToken string, body io.Reader) ([]byte, int, return nil, 0, err } defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) return respBody, resp.StatusCode, err } diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index 8b088e9e4..c3f0ef305 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -10,11 +10,9 @@ import ( "os" "strconv" - "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zcncore" - coreClient "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error { @@ -30,14 +28,6 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon }, } - c := client.GetClient() - c.Mnemonic = mnemonic - c.ClientID = clientID - c.ClientKey = clientKey - c.PeerPublicKey = peerPublicKey - c.Keys = keys - c.IsSplit = isSplit - w := &zcncrypto.Wallet{ ClientID: clientID, ClientKey: clientKey, @@ -46,13 +36,9 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon Keys: keys, IsSplit: isSplit, } - coreClient.SetWallet(*w) + client.SetWallet(*w) fmt.Println("set Wallet, is split:", isSplit) - err := zcncore.SetWallet(*w, isSplit) - if err != nil { - return err - } zboxApiClient.SetWallet(clientID, privateKey, publicKey) if mode == "" { // main thread, need to notify the web worker to update wallet diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index 265beeed9..eb30044d7 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -1,7 +1,7 @@ package main import ( - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // Split keys from the primary master key @@ -23,7 +23,7 @@ func splitKeys(privateKey string, numSplits int) (string, error) { // // nolint: unused func setWalletInfo(jsonWallet string, splitKeyWallet bool) bool { - err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) + err := zcncore.SetWalletInfo(jsonWallet, "bls0chain", splitKeyWallet) if err == nil { return true } else { diff --git a/wasmsdk/zcn.go b/wasmsdk/zcn.go index 0fac9e39f..17dfe788e 100644 --- a/wasmsdk/zcn.go +++ b/wasmsdk/zcn.go @@ -4,8 +4,8 @@ package main import ( - "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/zcncore" ) type Balance struct { @@ -18,30 +18,24 @@ type Balance struct { // - clientId is the client id func getWalletBalance(clientId string) (*Balance, error) { - zcn, nonce, err := zcncore.GetWalletBalance(clientId) + bal, err := client.GetBalance(clientId) if err != nil { return nil, err } - zcnToken, err := zcn.ToToken() + balance, err := bal.ToToken() if err != nil { return nil, err } - usd, err := zcncore.ConvertTokenToUSD(zcnToken) + toUsd, err := zcncore.ConvertTokenToUSD(balance) if err != nil { return nil, err } return &Balance{ - ZCN: zcnToken, - USD: usd, - Nonce: nonce, + ZCN: balance, + USD: toUsd, + Nonce: bal.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/allocation.go b/winsdk/allocation.go index 9a0170773..2379ad94a 100644 --- a/winsdk/allocation.go +++ b/winsdk/allocation.go @@ -10,8 +10,8 @@ import ( "encoding/json" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk_common/zcncore" ) // GetAllocation get allocation info diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 32a47a8bb..8a79398cc 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -8,17 +8,18 @@ import ( ) import ( + "context" "encoding/json" "errors" "os" "path" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxapi" - "github.com/0chain/gosdk_common/zboxcore/client" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zcncore" "github.com/0chain/gosdk_common/core/conf" "github.com/0chain/gosdk_common/core/encryption" @@ -106,18 +107,7 @@ func InitSDKs(configJson *C.char) *C.char { return WithJSON(false, err) } - err = zcncore.InitZCNSDK(configObj.BlockWorker, configObj.SignatureScheme, func(cc *zcncore.ChainConfig) error { - cc.BlockWorker = configObj.BlockWorker - cc.ChainID = configObj.ChainID - cc.ConfirmationChainLength = configObj.ConfirmationChainLength - cc.MinConfirmation = configObj.MinConfirmation - cc.EthNode = configObj.EthereumNode - cc.MinSubmit = configObj.MinSubmit - cc.SharderConsensous = configObj.SharderConsensous - cc.SignatureScheme = configObj.SignatureScheme - - return nil - }) + err = client.Init(context.Background(), *configObj) if err != nil { l.Logger.Error(err, configJs) return WithJSON(false, err) @@ -161,32 +151,20 @@ func InitWallet(clientJson *C.char) *C.char { log.Error("win: crash ", r) } }() - l.Logger.Info("Start InitStorageSDK") + l.Logger.Info("Start InitWallet") clientJs := C.GoString(clientJson) - configObj, err := conf.GetClientConfig() + var w zcncrypto.Wallet + err := json.Unmarshal([]byte(clientJs), &w) if err != nil { l.Logger.Error(err) return WithJSON(false, err) } - err = sdk.InitStorageSDK(clientJs, configObj.BlockWorker, configObj.ChainID, configObj.SignatureScheme, nil, 0) - if err != nil { - l.Logger.Error(err, clientJs) - return WithJSON(false, err) - } - l.Logger.Info("InitStorageSDK success") - - c := client.GetClient() - if c != nil { - zboxApiClient.SetWallet(client.GetClientID(), client.GetClientPrivateKey(), client.GetClientPublicKey()) - l.Logger.Info("InitZboxApiClient success") - } else { - l.Logger.Info("InitZboxApiClient skipped") - } - - l.Logger.Info("InitSDKs successful") + l.Logger.Info("InitWallet success") + zboxApiClient.SetWallet(client.Wallet().ClientID, client.Wallet().Keys[0].PrivateKey, client.Wallet().ClientKey) + l.Logger.Info("InitZboxApiClient success") return WithJSON(true, nil) } diff --git a/winsdk/wallet.go b/winsdk/wallet.go index be185829e..fc2c815bb 100644 --- a/winsdk/wallet.go +++ b/winsdk/wallet.go @@ -11,7 +11,8 @@ import ( "os" "path/filepath" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/zcncore" ) // CreateWallet - create a new wallet, and save it to ~/.zcn/wallet.json @@ -86,7 +87,7 @@ func RecoverWallet(mnemonic *C.char) *C.char { // //export GetWalletBalance func GetWalletBalance(clientID *C.char) *C.char { - b, _, err := zcncore.GetWalletBalance(C.GoString(clientID)) + b, err := client.GetBalance(C.GoString(clientID)) if err != nil { log.Error("win: ", err) return WithJSON(0, err) diff --git a/winsdk/zboxapi.go b/winsdk/zboxapi.go index 96684a406..98419a8a5 100644 --- a/winsdk/zboxapi.go +++ b/winsdk/zboxapi.go @@ -13,9 +13,9 @@ import ( "encoding/json" "errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/zboxapi" - "github.com/0chain/gosdk_common/zboxcore/client" ) var ( @@ -40,12 +40,7 @@ func InitZBox(zboxHost, zboxAppType *C.char) { zboxApiClient.SetRequest(C.GoString(zboxHost), C.GoString(zboxAppType)) - c := client.GetClient() - if c != nil { - zboxApiClient.SetWallet(client.GetClientID(), client.GetClientPrivateKey(), client.GetClientPublicKey()) - } else { - logging.Info("SetWallet: skipped") - } + zboxApiClient.SetWallet(client.Id(), client.PrivateKey(), client.PublicKey()) } // SetZBoxWallet set wallet on zbox api diff --git a/zboxapi/doc.go b/zboxapi/doc.go deleted file mode 100644 index 173276726..000000000 --- a/zboxapi/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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/zboxapi/response.go b/zboxapi/response.go deleted file mode 100644 index 66a2662c4..000000000 --- a/zboxapi/response.go +++ /dev/null @@ -1,106 +0,0 @@ -package zboxapi - -import ( - "encoding/base64" - "encoding/json" - "errors" -) - -var ( - ErrInvalidJsonResponse = errors.New("zbox-srv: invalid json response") -) - -type ErrorResponse struct { - Error json.RawMessage `json:"error"` -} - -type CsrfTokenResponse struct { - Token string `json:"csrf_token"` -} - -type JwtTokenResponse struct { - Token string `json:"jwt_token"` -} - -type FreeStorageResponse struct { - Data string `json:"marker"` - FundingID int `json:"funding_id"` -} - -type MarkerData struct { - Marker string `json:"marker"` - RecipientPublicKey string `json:"recipient_public_key"` -} - -func (fs *FreeStorageResponse) ToMarker() (*FreeMarker, error) { - - buf, err := base64.StdEncoding.DecodeString(fs.Data) - - if err != nil { - return nil, err - } - - data := &MarkerData{} - err = json.Unmarshal(buf, &data) - if err != nil { - return nil, err - } - - buf, err = base64.StdEncoding.DecodeString(data.Marker) - if err != nil { - return nil, err - } - - fm := &FreeMarker{} - - err = json.Unmarshal(buf, fm) - if err != nil { - return nil, err - } - - return fm, nil -} - -type FreeMarker struct { - Assigner string `json:"assigner"` - Recipient string `json:"recipient"` - FreeTokens float64 `json:"free_tokens"` - Nonce int64 `json:"nonce"` - Signature string `json:"signature"` -} - -type JsonResult[T any] struct { - Message string `json:"message"` - Error string `json:"error"` - Data []T `json:"data"` -} - -type SharedInfo struct { - AuthTicket string `json:"auth_ticket"` - Message string `json:"message"` - ShareInfoType string `json:"share_info_type"` - Link string `json:"link"` -} - -type SharedInfoSent struct { - AuthTicket string `json:"auth_ticket"` - Message string `json:"message"` - ShareInfoType string `json:"share_info_type"` - Receiver string `json:"receiver_client_id"` - Link string `json:"link"` - ReceiverName string `json:"receiver_name"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` -} - -type SharedInfoReceived struct { - AuthTicket string `json:"auth_ticket"` - Message string `json:"message"` - ShareInfoType string `json:"share_info_type"` - ClientID string `json:"client_id"` - Receiver string `json:"receiver_client_id"` - LookupHash string `json:"lookup_hash"` - SenderName string `json:"sender_name"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` -} diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go deleted file mode 100644 index 311963a01..000000000 --- a/zboxapi/sdk.go +++ /dev/null @@ -1,374 +0,0 @@ -package zboxapi - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/0chain/gosdk/zcncore" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/core/resty" -) - -var log logger.Logger - -func GetLogger() *logger.Logger { - return &log -} - -type Client struct { - baseUrl string - appType string - clientID string - clientPublicKey string - clientPrivateKey string -} - -// NewClient create a zbox api client with wallet info -func NewClient() *Client { - return &Client{} -} - -// SetRequest set base url and app type of zbox api request -func (c *Client) SetRequest(baseUrl, appType string) { - c.baseUrl = baseUrl - c.appType = appType -} - -func (c *Client) SetWallet(clientID, clientPrivateKey, clientPublicKey string) { - c.clientID = clientID - c.clientPrivateKey = clientPrivateKey - c.clientPublicKey = clientPublicKey -} - -func (c *Client) parseResponse(resp *http.Response, respBody []byte, result interface{}) error { - - log.Info("zboxapi: ", resp.StatusCode, " ", string(respBody)) - if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { - if err := json.Unmarshal(respBody, result); err != nil { - return thrown.Throw(ErrInvalidJsonResponse, string(respBody)) - } - return nil - } - - if len(respBody) == 0 { - return errors.New(resp.Status) - } - - errResp := &ErrorResponse{} - if err := json.Unmarshal(respBody, errResp); err != nil { - return thrown.Throw(ErrInvalidJsonResponse, string(respBody)) - } - - return errors.New(string(errResp.Error)) -} - -// GetCsrfToken obtain a fresh csrf token from 0box api server -func (c *Client) GetCsrfToken(ctx context.Context) (string, error) { - r, err := c.createResty(ctx, "", "", nil) - if err != nil { - return "", err - } - result := &CsrfTokenResponse{} - r.DoGet(ctx, c.baseUrl+"/v2/csrftoken").Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - return c.parseResponse(resp, respBody, result) - }) - - if err := r.Wait(); len(err) > 0 { - return "", err[0] - } - - return result.Token, nil -} - -func (c *Client) createResty(ctx context.Context, csrfToken, userID string, headers map[string]string) (*resty.Resty, error) { - h := make(map[string]string) - h["X-App-Client-ID"] = c.clientID - h["X-App-Client-Key"] = c.clientPublicKey - h["X-App-User-ID"] = userID - - if c.clientPrivateKey != "" { - data := fmt.Sprintf("%v:%v:%v", c.clientID, userID, c.clientPublicKey) - hash := encryption.Hash(data) - - sign, err := zcncore.SignFn(hash) - if err != nil { - return nil, err - } - h["X-App-Client-Signature"] = sign - } - - h["X-CSRF-TOKEN"] = csrfToken - h["X-App-Timestamp"] = strconv.FormatInt(time.Now().Unix(), 10) - - if _, ok := h["X-App-ID-Token"]; !ok { - h["X-App-ID-Token"] = "*" - } - - h["X-App-Type"] = c.appType - - for k, v := range headers { - h[k] = v - } - - return resty.New(resty.WithHeader(h)), nil -} - -// CreateJwtToken create a jwt token with jwt session id and otp -func (c *Client) CreateJwtToken(ctx context.Context, userID, accessToken string) (string, error) { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return "", err - } - headers := map[string]string{ - "X-App-ID-Token": accessToken, - } - - r, err := c.createResty(ctx, csrfToken, userID, headers) - - if err != nil { - return "", err - } - - result := &JwtTokenResponse{} - r.DoPost(ctx, nil, c.baseUrl+"/v2/jwt/token"). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return "", errs[0] - } - - return result.Token, nil -} - -// RefreshJwtToken refresh jwt token -func (c *Client) RefreshJwtToken(ctx context.Context, userID string, token string) (string, error) { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return "", err - } - headers := map[string]string{ - "X-JWT-Token": token, - } - - r, err := c.createResty(ctx, csrfToken, userID, headers) - - if err != nil { - return "", err - } - - result := &JwtTokenResponse{} - r.DoPut(ctx, nil, c.baseUrl+"/v2/jwt/token"). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return "", errs[0] - } - - return result.Token, nil -} - -func (c *Client) GetFreeStorage(ctx context.Context, phoneNumber, token string) (*FreeMarker, error) { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return nil, err - } - headers := map[string]string{ - "X-App-ID-Token": token, - } - - r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) - - if err != nil { - return nil, err - } - - result := &FreeStorageResponse{} - r.DoGet(ctx, c.baseUrl+"/v2/freestorage"). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return nil, errs[0] - } - - return result.ToMarker() - -} - -func (c *Client) CreateSharedInfo(ctx context.Context, phoneNumber, token string, s SharedInfo) error { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return err - } - headers := map[string]string{ - "X-App-ID-Token": token, - "Content-Type": "application/json", - } - - r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) - - if err != nil { - return err - } - - buf, err := json.Marshal(s) - if err != nil { - return err - } - - result := &JsonResult[string]{} - r.DoPost(ctx, bytes.NewReader(buf), c.baseUrl+"/v2/shareinfo"). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, &result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return errs[0] - } - - return nil -} - -func (c *Client) DeleteSharedInfo(ctx context.Context, phoneNumber, token, authTicket string, lookupHash string) error { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return err - } - headers := map[string]string{ - "X-App-ID-Token": token, - } - - r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) - - if err != nil { - return err - } - - result := &JsonResult[string]{} - r.DoDelete(ctx, c.baseUrl+"/v2/shareinfo?auth_ticket="+authTicket+"&lookup_hash="+lookupHash). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, &result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return errs[0] - } - - return nil -} - -func (c *Client) GetSharedByPublic(ctx context.Context, phoneNumber, token string) ([]SharedInfoSent, error) { - return c.getShared(ctx, phoneNumber, token, false) -} - -func (c *Client) GetSharedByMe(ctx context.Context, phoneNumber, token string) ([]SharedInfoSent, error) { - return c.getShared(ctx, phoneNumber, token, true) -} - -func (c *Client) getShared(ctx context.Context, phoneNumber, token string, isPrivate bool) ([]SharedInfoSent, error) { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return nil, err - } - headers := map[string]string{ - "X-App-ID-Token": token, - } - - r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) - - if err != nil { - return nil, err - } - - shareInfoType := "public" - if isPrivate { - shareInfoType = "private" - } - - result := &JsonResult[SharedInfoSent]{} - r.DoGet(ctx, c.baseUrl+"/v2/shareinfo/shared?share_info_type="+shareInfoType). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, &result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return nil, errs[0] - } - - return result.Data, nil - -} - -func (c *Client) GetSharedToMe(ctx context.Context, phoneNumber, token string) ([]SharedInfoReceived, error) { - csrfToken, err := c.GetCsrfToken(ctx) - if err != nil { - return nil, err - } - headers := map[string]string{ - "X-App-ID-Token": token, - } - - r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) - - if err != nil { - return nil, err - } - - result := &JsonResult[SharedInfoReceived]{} - r.DoGet(ctx, c.baseUrl+"/v2/shareinfo/received?share_info_type=private"). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - return c.parseResponse(resp, respBody, &result) - }) - - if errs := r.Wait(); len(errs) > 0 { - return nil, errs[0] - } - - return result.Data, nil - -} diff --git a/zboxapi/sdk_test.go b/zboxapi/sdk_test.go deleted file mode 100644 index 10cbcf355..000000000 --- a/zboxapi/sdk_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package zboxapi - -import ( - "context" - "testing" - - "github.com/stretchr/testify/require" -) - -var ( - BaseURL = "https://0box.dev.zus.network" - AppType = "vult" - ClientID = "70e1318a9709786cf975f15ca941bee73d0f422305ecd78b0f358870ec17f41d" - ClientPublicKey = "4ec4b4dfb8c9ceb8fb6e84ef46e503c3445a0c6d770986a019cdbef4bc47b70dfadd5441f708f0df47df14e5cd6a0aa94ec31ca66e337692d9a92599d9456a81" - ClientPrivateKey = "982801f352e886eaaf61196d83373b4cc09e9a598ffe1f49bf5adf905174cb0c" - UserID = "lWVZRhERosYtXR9MBJh5yJUtweI4" - PhoneNumber = "+917777777777" -) - -func TestGetCsrfToken(t *testing.T) { - t.Skip("Only for local debugging") - - c := NewClient() - c.SetRequest(BaseURL, AppType) - c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) - - token, err := c.GetCsrfToken(context.TODO()) - - require.Nil(t, err) - require.True(t, len(token) > 0) -} diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index c450bf1f6..afb7220ec 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -18,9 +18,9 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" diff --git a/zboxcore/sdk/transaction.go b/zboxcore/sdk/transaction.go index 3603c9783..93131c0dc 100644 --- a/zboxcore/sdk/transaction.go +++ b/zboxcore/sdk/transaction.go @@ -9,9 +9,9 @@ import ( "errors" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/transaction" l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zcncore" ) type transactionCallback struct { diff --git a/zboxcore/sdk/transaction_mobile.go b/zboxcore/sdk/transaction_mobile.go index 6993242f6..cc426f19b 100644 --- a/zboxcore/sdk/transaction_mobile.go +++ b/zboxcore/sdk/transaction_mobile.go @@ -9,9 +9,9 @@ import ( "errors" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/transaction" l "github.com/0chain/gosdk_common/zboxcore/logger" + "github.com/0chain/gosdk_common/zcncore" ) type transactionCallback struct { diff --git a/zcnbridge/README.MD b/zcnbridge/README.MD deleted file mode 100644 index ecf6af832..000000000 --- a/zcnbridge/README.MD +++ /dev/null @@ -1,970 +0,0 @@ - - -# zcnbridge - -```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>) - - -## 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 -``` - -AccountExists checks if account exists - - -## 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) -``` - -GetAuthorizer returned authorizer by ID - - -## func [GetAuthorizers]() - -```go -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"` -} -``` - - -## type [AuthorizerNode]() - - - -```go -type AuthorizerNode struct { - ID string `json:"id"` - URL string `json:"url"` -} -``` - - -## type [AuthorizerNodesResponse]() - - - -```go -type AuthorizerNodesResponse struct { - Nodes []*AuthorizerNode `json:"nodes"` -} -``` - - -## 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"` - - // Stats - LastHealthCheck int64 `json:"last_health_check"` - - // 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"` -} -``` - - -## type [BancorTokenDetails]() - -BancorTokenDetails describes Bancor ZCN zcntoken pool details - -```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) -``` - - - -Generated by [gomarkdoc]() diff --git a/zcnbridge/authorizer/doc.go b/zcnbridge/authorizer/doc.go deleted file mode 100644 index 1f6be900b..000000000 --- a/zcnbridge/authorizer/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// 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/authorizer/proofBurnTicket.go b/zcnbridge/authorizer/proofBurnTicket.go deleted file mode 100644 index 10d05053a..000000000 --- a/zcnbridge/authorizer/proofBurnTicket.go +++ /dev/null @@ -1,83 +0,0 @@ -package authorizer - -import ( - "encoding/json" - "fmt" - - "github.com/0chain/gosdk/zcncore" - - "github.com/0chain/gosdk_common/core/zcncrypto" - - "github.com/0chain/gosdk/zcnbridge" - - "github.com/0chain/gosdk/zcnbridge/errors" - "github.com/0chain/gosdk_common/core/encryption" -) - -type ProofOfBurn struct { - TxnID string `json:"0chain_txn_id"` - Nonce int64 `json:"nonce"` - Amount int64 `json:"amount"` - EthereumAddress string `json:"ethereum_address"` - Signature []byte `json:"signature,omitempty"` -} - -func (pb *ProofOfBurn) Encode() []byte { - return encryption.RawHash(pb) -} - -func (pb *ProofOfBurn) Decode(input []byte) error { - return json.Unmarshal(input, pb) -} - -func (pb *ProofOfBurn) Verify() (err error) { - switch { - case pb.TxnID == "": - err = errors.NewError("failed to verify proof of burn ticket", "0chain txn id is required") - case pb.Nonce == 0: - err = errors.NewError("failed to verify proof of burn ticket", "Nonce is required") - case pb.Amount == 0: - err = errors.NewError("failed to verify proof of burn ticket", "Amount is required") - case pb.EthereumAddress == "": - err = errors.NewError("failed to verify proof of burn ticket", "Receiving client id is required") - } - return -} - -func (pb *ProofOfBurn) UnsignedMessage() string { - return fmt.Sprintf("%v:%v:%v:%v", pb.TxnID, pb.Amount, pb.Nonce, pb.EthereumAddress) -} - -func (pb *ProofOfBurn) SignWithEthereum(b *zcnbridge.BridgeClient) (err error) { - sig, err := b.SignWithEthereumChain(pb.UnsignedMessage()) - if err != nil { - return errors.Wrap("signature_ethereum", "failed to sign proof-of-burn ticket", err) - } - pb.Signature = sig - - return -} - -// Sign can sign if chain config is initialized -func (pb *ProofOfBurn) Sign() (err error) { - hash := zcncrypto.Sha3Sum256(pb.UnsignedMessage()) - sig, err := zcncore.Sign(hash) - if err != nil { - return errors.Wrap("signature_0chain", "failed to sign proof-of-burn ticket using walletString ID ", err) - } - pb.Signature = []byte(sig) - - return -} - -// SignWith0Chain can sign with the provided walletString -func (pb *ProofOfBurn) SignWith0Chain(w *zcncrypto.Wallet) (err error) { - hash := zcncrypto.Sha3Sum256(pb.UnsignedMessage()) - sig, err := zcncore.SignWith0Wallet(hash, w) - if err != nil { - return errors.Wrap("signature_0chain", "failed to sign proof-of-burn ticket using walletString ID "+w.ClientID, err) - } - pb.Signature = []byte(sig) - - return -} diff --git a/zcnbridge/authorizer/proofBurnTicket_test.go b/zcnbridge/authorizer/proofBurnTicket_test.go deleted file mode 100644 index d0d4a2537..000000000 --- a/zcnbridge/authorizer/proofBurnTicket_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package authorizer_test - -import ( - "encoding/json" - "testing" - - "github.com/0chain/gosdk/zcncore" - - "github.com/0chain/gosdk/zcnbridge/authorizer" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" -) - -const walletString = `{ - "client_id": "39ac4c04401762778de45d00c51934b2ff15d8168722585daa422195a1ebc5d5", - "client_key": "9cf22d230343a68a149a2ccea1137846dd6d0fe653985eb8bebfbe2583ab0e1e2281b78218f480a50cac78cd0c716c3aafa8d741af813a94ca0a5b4e0b8e7a22", - "keys": [ - { - "public_key": "9cf22d230343a68a149a2ccea1137846dd6d0fe653985eb8bebfbe2583ab0e1e2281b78218f480a50cac78cd0c716c3aafa8d741af813a94ca0a5b4e0b8e7a22", - "private_key": "9c6c9022bdbd05670c07eae339dbb5491b1c035c2287a83c56581c505b824623" - } - ], - "mnemonics": "fortune guitar marine bachelor ocean raven hunt silver pass hurt industry forget cradle shuffle render used used order chat shallow aerobic cry exercise junior", - "version": "1.0", - "date_created": "2022-07-17T16:12:25+05:00", - "nonce": 0 -} -` - -type TicketTestSuite struct { - suite.Suite - w *zcncrypto.Wallet -} - -func TestTicketTestSuite(t *testing.T) { - suite.Run(t, new(TicketTestSuite)) -} - -func (suite *TicketTestSuite) SetupTest() { - w := &zcncrypto.Wallet{} - err := json.Unmarshal([]byte(walletString), w) - require.NoError(suite.T(), err) - suite.w = w -} - -func (suite *TicketTestSuite) TestBasicSignature() { - hash := zcncrypto.Sha3Sum256("test") - signScheme := zcncrypto.NewSignatureScheme("bls0chain") - err := signScheme.SetPrivateKey(suite.w.Keys[0].PrivateKey) - require.NoError(suite.T(), err) - sign, err := signScheme.Sign(hash) - require.NoError(suite.T(), err) - require.NotEmpty(suite.T(), sign) -} - -func (suite *TicketTestSuite) TestTicketSignature() { - pb := &authorizer.ProofOfBurn{ - TxnID: "TxnID", - Nonce: 100, - Amount: 10, - EthereumAddress: "0xBEEF", - Signature: nil, - } - - zcncore.InitSignatureScheme("bls0chain") - err := pb.SignWith0Chain(suite.w) - require.NoError(suite.T(), err) - require.NotEmpty(suite.T(), pb.Signature) -} diff --git a/zcnbridge/authorizer_response.go b/zcnbridge/authorizer_response.go deleted file mode 100644 index 2253b3439..000000000 --- a/zcnbridge/authorizer_response.go +++ /dev/null @@ -1,124 +0,0 @@ -package zcnbridge - -import ( - "encoding/json" - "errors" -) - -type ( - // JobStatus = Ethereum transaction status - JobStatus uint - // JobResult = Authorizer task result, it wraps actual result of the query inside authorizer - 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 - } - // JobError result of internal request wrapped in authorizer job - JobError struct { - error - } - - // EthereumBurnEvents represents burn events returned by authorizers - 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"` - } - - // ProofEthereumBurn Authorizer returns this type for Ethereum transaction - 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"` - } - - // ProofZCNBurn Authorizer returns this type for ZCN transaction - 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 (e *JobError) UnmarshalJSON(buf []byte) error { - e.error = errors.New(string(buf)) - return nil -} - -func (e *JobError) MarshalJSON() ([]byte, error) { - return json.Marshal(e.Error()) -} - -// WZCNBurnEvent returned from burn ticket handler of: /v1/ether/burnticket/get -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 (r *WZCNBurnEvent) GetAuthorizerID() string { - return r.AuthorizerID -} - -func (r *WZCNBurnEvent) SetAuthorizerID(id string) { - r.AuthorizerID = id -} - -func (r *WZCNBurnEvent) Error() error { - return r.Err -} - -func (r *WZCNBurnEvent) Data() interface{} { - return r.BurnTicket -} - -func (r *EthereumBurnEvents) GetAuthorizerID() string { - return r.AuthorizerID -} - -func (r *EthereumBurnEvents) SetAuthorizerID(id string) { - r.AuthorizerID = id -} - -func (r *EthereumBurnEvents) Error() error { - return nil -} - -func (r *EthereumBurnEvents) Data() interface{} { - return r -} - -func (r *ProofZCNBurn) GetAuthorizerID() string { - return r.AuthorizerID -} - -func (r *ProofZCNBurn) SetAuthorizerID(id string) { - r.AuthorizerID = id -} - -func (r *ProofZCNBurn) Error() error { - return nil -} - -func (r *ProofZCNBurn) Data() interface{} { - return r -} diff --git a/zcnbridge/authorizers_query.go b/zcnbridge/authorizers_query.go deleted file mode 100644 index b5e3ad432..000000000 --- a/zcnbridge/authorizers_query.go +++ /dev/null @@ -1,351 +0,0 @@ -package zcnbridge - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "math" - "net/http" - "strings" - "sync" - - "github.com/0chain/gosdk/zcnbridge/errors" - "github.com/0chain/gosdk/zcnbridge/ethereum" - h "github.com/0chain/gosdk/zcnbridge/http" - "github.com/0chain/gosdk/zcnbridge/log" - "github.com/0chain/gosdk/zcnbridge/wallet" - "github.com/0chain/gosdk/zcnbridge/zcnsc" - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/common" - "go.uber.org/zap" -) - -type ( - // authorizerResponse is HTTP client response event - authorizerResponse struct { - // AuthorizerID is authorizer where the job was performed - AuthorizerID string - // event is server job event - event JobResult - // error describes an error occurred during event processing on client side during the call to server - error - } - - requestHandler struct { - path string - values map[string]string - bodyDecoder func([]byte) (JobResult, error) - } - - responseChannelType chan *authorizerResponse - eventsChannelType chan []JobResult -) - -var ( - client *http.Client -) - -// QueryEthereumMintPayload gets burn ticket and creates mint payload to be minted in the Ethereum chain -// zchainBurnHash - Ethereum burn transaction hash -func (b *BridgeClient) QueryEthereumMintPayload(zchainBurnHash string) (*ethereum.MintPayload, error) { - client = h.CleanClient() - authorizers, err := getAuthorizers(true) - - if err != nil || len(authorizers) == 0 { - return nil, errors.Wrap("get_authorizers", "failed to get authorizers", err) - } - - var ( - totalWorkers = len(authorizers) - values = map[string]string{ - "hash": zchainBurnHash, - } - ) - - handler := &requestHandler{ - path: wallet.BurnNativeTicketPath, - values: values, - bodyDecoder: func(body []byte) (JobResult, error) { - ev := &ProofZCNBurn{} - err := json.Unmarshal(body, ev) - return ev, err - }, - } - - thresh := b.ConsensusThreshold - results := queryAllAuthorizers(authorizers, handler) - numSuccess := len(results) - quorum := math.Ceil((float64(numSuccess) * 100) / float64(totalWorkers)) - - if numSuccess > 0 && quorum >= thresh { - burnTicket, ok := results[0].(*ProofZCNBurn) - if !ok { - return nil, errors.Wrap("type_cast", "failed to convert to *proofEthereumBurn", err) - } - - var sigs []*ethereum.AuthorizerSignature - for _, result := range results { - ticket := result.(*ProofZCNBurn) - sig := ðereum.AuthorizerSignature{ - ID: ticket.GetAuthorizerID(), - Signature: ticket.Signature, - } - sigs = append(sigs, sig) - } - - payload := ðereum.MintPayload{ - ZCNTxnID: burnTicket.TxnID, - Amount: burnTicket.Amount, - To: burnTicket.To, - Nonce: burnTicket.Nonce, - Signatures: sigs, - } - - return payload, nil - } - - text := fmt.Sprintf("failed to reach the quorum. #Success: %d from #Total: %d", numSuccess, totalWorkers) - return nil, errors.New("get_burn_ticket", text) -} - -// QueryEthereumBurnEvents gets ethereum burn events -func (b *BridgeClient) QueryEthereumBurnEvents(startNonce string) ([]*ethereum.BurnEvent, error) { - client = h.CleanClient() - authorizers, err := getAuthorizers(true) - - if err != nil || len(authorizers) == 0 { - return nil, errors.Wrap("get_authorizers", "failed to get authorizers", err) - } - - var ( - totalWorkers = len(authorizers) - values = map[string]string{ - "clientid": zcncore.GetClientWalletID(), - "ethereumaddress": b.EthereumAddress, - "startnonce": startNonce, - } - ) - - handler := &requestHandler{ - path: wallet.BurnWzcnBurnEventsPath, - values: values, - bodyDecoder: func(body []byte) (JobResult, error) { - ev := &EthereumBurnEvents{} - err := json.Unmarshal(body, ev) - return ev, err - }, - } - - thresh := b.ConsensusThreshold - results := queryAllAuthorizers(authorizers, handler) - numSuccess := len(results) - quorum := math.Ceil((float64(numSuccess) * 100) / float64(totalWorkers)) - - if numSuccess > 0 && quorum >= thresh { - burnEvents, ok := results[0].(*EthereumBurnEvents) - if !ok { - return nil, errors.Wrap("type_cast", "failed to convert to *ethereumBurnEvents", err) - } - - result := make([]*ethereum.BurnEvent, 0) - - for _, burnEvent := range burnEvents.BurnEvents { - result = append(result, ðereum.BurnEvent{ - Nonce: burnEvent.Nonce, - Amount: burnEvent.Amount, - TransactionHash: burnEvent.TransactionHash, - }) - } - - return result, nil - } - - text := fmt.Sprintf("failed to reach the quorum. #Success: %d from #Total: %d", numSuccess, totalWorkers) - return nil, errors.New("get_burn_events", text) -} - -// QueryZChainMintPayload gets burn ticket and creates mint payload to be minted in the ZChain -// ethBurnHash - Ethereum burn transaction hash -func (b *BridgeClient) QueryZChainMintPayload(ethBurnHash string) (*zcnsc.MintPayload, error) { - client = h.CleanClient() - authorizers, err := getAuthorizers(true) - log.Logger.Info("Got authorizers", zap.Int("amount", len(authorizers))) - - if err != nil || len(authorizers) == 0 { - return nil, errors.Wrap("get_authorizers", "failed to get authorizers", err) - } - - var ( - totalWorkers = len(authorizers) - values = map[string]string{ - "hash": ethBurnHash, - "clientid": zcncore.GetClientWalletID(), - } - ) - - handler := &requestHandler{ - path: wallet.BurnWzcnTicketPath, - values: values, - bodyDecoder: func(body []byte) (JobResult, error) { - ev := &WZCNBurnEvent{} - err := json.Unmarshal(body, ev) - return ev, err - }, - } - - thresh := b.ConsensusThreshold - results := queryAllAuthorizers(authorizers, handler) - numSuccess := len(results) - quorum := math.Ceil((float64(numSuccess) * 100) / float64(totalWorkers)) - - if numSuccess > 0 && quorum >= thresh { - burnTicket, ok := results[0].Data().(*ProofEthereumBurn) - if !ok { - return nil, errors.Wrap("type_cast", "failed to convert to *proofEthereumBurn", err) - } - - var sigs []*zcnsc.AuthorizerSignature - for _, result := range results { - ticket := result.Data().(*ProofEthereumBurn) - sig := &zcnsc.AuthorizerSignature{ - ID: result.GetAuthorizerID(), - Signature: ticket.Signature, - } - sigs = append(sigs, sig) - } - - payload := &zcnsc.MintPayload{ - EthereumTxnID: burnTicket.TxnID, - Amount: common.Balance(burnTicket.Amount), - Nonce: burnTicket.Nonce, - Signatures: sigs, - ReceivingClientID: burnTicket.ReceivingClientID, - } - - return payload, nil - } - - text := fmt.Sprintf("failed to reach the quorum. #Success: %d from #Total: %d", numSuccess, totalWorkers) - return nil, errors.New("get_burn_ticket", text) -} - -func queryAllAuthorizers(authorizers []*AuthorizerNode, handler *requestHandler) []JobResult { - var ( - totalWorkers = len(authorizers) - eventsChannel = make(eventsChannelType) - responseChannel = make(responseChannelType, totalWorkers) - ) - defer close(eventsChannel) - - var wg sync.WaitGroup - - for _, authorizer := range authorizers { - wg.Add(1) - go queryAuthorizer(authorizer, handler, responseChannel) - } - - go handleResponse(responseChannel, eventsChannel, &wg) - - wg.Wait() - close(responseChannel) - results := <-eventsChannel - - return results -} - -func handleResponse(responseChannel responseChannelType, eventsChannel eventsChannelType, wg *sync.WaitGroup) { - var events []JobResult - for job := range responseChannel { - if job.error == nil { - event := job.event - event.SetAuthorizerID(job.AuthorizerID) - events = append(events, event) - } - wg.Done() - } - eventsChannel <- events -} - -func queryAuthorizer(au *AuthorizerNode, request *requestHandler, responseChannel responseChannelType) { - Logger.Info("Query from authorizer", zap.String("ID", au.ID), zap.String("URL", au.URL)) - ticketURL := strings.TrimSuffix(au.URL, "/") + request.path - - req, err := http.NewRequest("GET", ticketURL, nil) - if err != nil { - log.Logger.Error("failed to create request", zap.Error(err)) - return - } - - q := req.URL.Query() - for k, v := range request.values { - q.Add(k, v) - } - req.URL.RawQuery = q.Encode() - Logger.Info(req.URL.String()) - resp, body := readResponse(client.Do(req)) - resp.AuthorizerID = au.ID - - if resp.error != nil { - Logger.Error( - "failed to process response", - zap.Error(resp.error), - zap.String("node.id", au.ID), - zap.String("node.url", au.URL), - ) - } - - event, errEvent := request.bodyDecoder(body) - event.SetAuthorizerID(au.ID) - - if errEvent != nil { - err := errors.Wrap("decode_message_body", "failed to decode message body", errEvent) - log.Logger.Error( - "failed to decode event body", - zap.Error(err), - zap.String("node.id", au.ID), - zap.String("node.url", au.URL), - zap.String("body", string(body)), - ) - } - - resp.event = event - - responseChannel <- resp -} - -func readResponse(response *http.Response, err error) (res *authorizerResponse, body []byte) { - res = &authorizerResponse{} - if err != nil { - err = errors.Wrap("authorizer_post_process", "failed to call the authorizer", err) - Logger.Error("request response error", zap.Error(err)) - } - - if response == nil { - res.error = err - Logger.Error("response is empty", zap.Error(err)) - return res, nil - } - - if response.StatusCode >= 400 { - err = errors.Wrap("authorizer_post_process", fmt.Sprintf("error %d", response.StatusCode), err) - Logger.Error("request response status", zap.Error(err)) - } - - body, er := ioutil.ReadAll(response.Body) - log.Logger.Debug("response", zap.String("response", string(body))) - defer response.Body.Close() - - if er != nil || len(body) == 0 { - var errstrings []string - er = errors.Wrap("authorizer_post_process", "failed to read body", er) - if err != nil { - errstrings = append(errstrings, err.Error()) - } - errstrings = append(errstrings, er.Error()) - err = fmt.Errorf(strings.Join(errstrings, ":")) - } - - res.error = err - - return res, body -} diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go deleted file mode 100644 index 9e9b1c35e..000000000 --- a/zcnbridge/bridge.go +++ /dev/null @@ -1,1189 +0,0 @@ -package zcnbridge - -import ( - "context" - "encoding/hex" - "fmt" - "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" - hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/spf13/viper" - - "gopkg.in/natefinch/lumberjack.v2" - - "github.com/0chain/gosdk/zcnbridge/ethereum" - "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" - "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" - "github.com/0chain/gosdk/zcnbridge/ethereum/nftconfig" - "github.com/0chain/gosdk/zcnbridge/log" - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/logger" - - "github.com/0chain/gosdk/zcnbridge/transaction" - "github.com/0chain/gosdk/zcnbridge/wallet" - "github.com/0chain/gosdk/zcnbridge/zcnsc" - eth "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/pkg/errors" - "go.uber.org/zap" -) - -var Logger logger.Logger -var defaultLogLevel = logger.DEBUG - -func init() { - Logger.Init(defaultLogLevel, "zcnbridge-sdk") - - Logger.SetLevel(logger.DEBUG) - ioWriter := &lumberjack.Logger{ - Filename: "bridge.log", - MaxSize: 100, // MB - MaxBackups: 5, // number of backups - MaxAge: 28, //days - LocalTime: false, - Compress: false, // disabled by default - } - Logger.SetLogFile(ioWriter, true) -} - -var ( - DefaultClientIDEncoder = func(id string) []byte { - result, err := hex.DecodeString(id) - if err != nil { - Logger.Fatal(err) - } - return result - } -) - -// 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) - password = b.Password - ) - - signer := accounts.Account{ - Address: signerAddress, - } - - signerAcc, err := b.keyStore.Find(signer) - if err != nil { - Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) - } - - chainID, err := client.ChainID(context.Background()) - if err != nil { - Logger.Fatal(errors.Wrap(err, "failed to get chain ID")) - } - - nonce, err := client.PendingNonceAt(context.Background(), signerAddress) - if err != nil { - Logger.Fatal(err) - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - Logger.Fatal(err) - } - - err = b.keyStore.TimedUnlock(signer, password, time.Second*2) - if err != nil { - Logger.Fatal(err) - } - - opts, err := bind.NewKeyStoreTransactorWithChainID(b.keyStore.GetEthereumKeyStore(), signerAcc, chainID) - if err != nil { - Logger.Fatal(err) - } - - opts.Nonce = big.NewInt(int64(nonce)) - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts -} - -// 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 { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - tran, err := instance.AddAuthorizers(transactOpts, address) - if err != nil { - msg := "failed to execute AddAuthorizers transaction to ClientID = %s with amount = %s" - return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), address.String()) - } - - return tran, err -} - -// 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 { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - tran, err := instance.RemoveAuthorizers(transactOpts, address) - if err != nil { - msg := "failed to execute RemoveAuthorizers transaction to ClientID = %s with amount = %s" - return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), address.String()) - } - - 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) - cfg.SetConfigName("authorizers") - if err := cfg.ReadInConfig(); err != nil { - fmt.Println(err) - return - } - - mnemonics := cfg.GetStringSlice("authorizers") - - for _, mnemonic := range mnemonics { - wallet, err := hdw.NewFromMnemonic(mnemonic) - if err != nil { - fmt.Printf("failed to read mnemonic: %v", err) - continue - } - - pathD := hdw.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := wallet.Derive(pathD, true) - if err != nil { - fmt.Println(err) - continue - } - - transaction, err := b.AddEthereumAuthorizer(context.TODO(), account.Address) - if err != nil || transaction == nil { - fmt.Printf("AddAuthorizer error: %v, Address: %s", err, account.Address.Hex()) - continue - } - - status, err := ConfirmEthereumTransaction(transaction.Hash().String(), 100, time.Second*10) - if err != nil { - fmt.Println(err) - } - - if status == 1 { - fmt.Printf("Authorizer has been added: %s\n", mnemonic) - } else { - fmt.Printf("Authorizer has failed to be added: %s\n", mnemonic) - } - } -} - -func (b *BridgeClient) prepareNFTConfig(ctx context.Context, method string, params ...interface{}) (*nftconfig.NFTConfig, *bind.TransactOpts, error) { - // To (contract) - contractAddress := common.HexToAddress(b.NFTConfigAddress) - - // Get ABI of the contract - abi, err := nftconfig.NFTConfigMetaData.GetAbi() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get nftconfig ABI") - } - - // Pack the method argument - pack, err := abi.Pack(method, params...) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") - } - - from := common.HexToAddress(b.EthereumAddress) - - // Gas limits in units - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: from, - Data: pack, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to estimate gas") - } - - // Update gas limits + 10% - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - - // NFTConfig instance - cfg, err := nftconfig.NewNFTConfig(contractAddress, b.ethereumClient) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to create nftconfig instance") - } - - return cfg, transactOpts, nil -} - -// 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), - common.LeftPadBytes(big.NewInt(param).Bytes(), 32), - ) -} - -// 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") - } - - v := big.NewInt(value) - Logger.Debug("NFT config setUint256", zap.String("key", key.String()), zap.Any("value", v)) - instance, transactOpts, err := b.prepareNFTConfig(ctx, "setUint256", key, v) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - tran, err := instance.SetUint256(transactOpts, key, v) - if err != nil { - msg := "failed to execute setUint256 transaction to ClientID = %s with key = %s, value = %v" - return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), key, v) - } - - 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 { - kkey = EncodePackInt64(key, keyParam[0]) - } - - contractAddress := common.HexToAddress(b.NFTConfigAddress) - - cfg, err := nftconfig.NewNFTConfig(contractAddress, b.ethereumClient) - if err != nil { - return "", 0, errors.Wrap(err, "failed to create NFT config instance") - } - - v, err := cfg.GetUint256(nil, kkey) - if err != nil { - Logger.Error("NFTConfig GetUint256 FAILED", zap.Error(err)) - msg := "failed to execute getUint256 call, key = %s" - return "", 0, errors.Wrapf(err, msg, kkey) - } - 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) - - Logger.Debug("NFT config setAddress", - zap.String("key", kkey.String()), - zap.String("address", address)) - - addr := common.HexToAddress(address) - instance, transactOpts, err := b.prepareNFTConfig(ctx, "setAddress", kkey, addr) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - tran, err := instance.SetAddress(transactOpts, kkey, addr) - if err != nil { - msg := "failed to execute setAddress transaction to ClientID = %s with key = %s, value = %v" - return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), key, address) - } - - 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)) - - contractAddress := common.HexToAddress(b.NFTConfigAddress) - - cfg, err := nftconfig.NewNFTConfig(contractAddress, b.ethereumClient) - if err != nil { - return "", "", errors.Wrap(err, "failed to create NFT config instance") - } - - v, err := cfg.GetAddress(nil, kkey) - if err != nil { - Logger.Error("NFTConfig GetAddress FAILED", zap.Error(err)) - msg := "failed to execute getAddress call, key = %s" - return "", "", errors.Wrapf(err, msg, kkey) - } - return kkey.String(), v.String(), err -} - -// 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)" -// - 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) { - if allowanceAmount <= 0 { - return nil, errors.New("amount must be greater than zero") - } - - // 1. Data Parameter (spender) - spenderAddress := common.HexToAddress(b.BridgeAddress) - - // 2. Data Parameter (amount) - amount := big.NewInt(int64(allowanceAmount)) - - tokenAddress := common.HexToAddress(b.TokenAddress) - - tokenInstance, transactOpts, err := b.prepareToken(ctx, "increaseApproval", tokenAddress, spenderAddress, amount) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare zcntoken") - } - - Logger.Info( - "Starting IncreaseApproval", - zap.String("zcntoken", tokenAddress.String()), - zap.String("spender", spenderAddress.String()), - zap.Int64("amount", amount.Int64()), - ) - - tran, err := tokenInstance.IncreaseApproval(transactOpts, spenderAddress, amount) - if err != nil { - Logger.Error( - "IncreaseApproval FAILED", - zap.String("zcntoken", tokenAddress.String()), - zap.String("spender", spenderAddress.String()), - zap.Int64("amount", amount.Int64()), - zap.Error(err)) - - return nil, errors.Wrapf(err, "failed to send `IncreaseApproval` transaction") - } - - Logger.Info( - "Posted IncreaseApproval", - zap.String("hash", tran.Hash().String()), - zap.String("zcntoken", tokenAddress.String()), - zap.String("spender", spenderAddress.String()), - zap.Int64("amount", amount.Int64()), - ) - - return tran, nil -} - -// GetTokenBalance returns balance of the current client for the zcntoken address -func (b *BridgeClient) GetTokenBalance() (*big.Int, error) { - // 1. Token address parameter - of := common.HexToAddress(b.TokenAddress) - - // 2. User's Ethereum wallet address parameter - from := common.HexToAddress(b.EthereumAddress) - - tokenInstance, err := zcntoken.NewToken(of, b.ethereumClient) - if err != nil { - return nil, errors.Wrap(err, "failed to initialize zcntoken instance") - } - - wei, err := tokenInstance.BalanceOf(&bind.CallOpts{}, from) - if err != nil { - return nil, errors.Wrapf(err, "failed to call `BalanceOf` for %s", b.EthereumAddress) - } - - return wei, nil -} - -// 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)) - - signer := accounts.Account{ - Address: common.HexToAddress(b.EthereumAddress), - } - - signerAcc, err := b.keyStore.Find(signer) - if err != nil { - Logger.Fatal(err) - } - - signature, err := b.keyStore.SignHash(signerAcc, hash.Bytes()) - if err != nil { - return nil, err - } - - if err != nil { - return []byte{}, errors.Wrap(err, "failed to sign the message") - } - - return signature, nil -} - -// 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) - - contractAddress := common.HexToAddress(b.BridgeAddress) - - bridgeInstance, err := bridge.NewBridge(contractAddress, b.ethereumClient) - if err != nil { - return nil, errors.Wrap(err, "failed to create bridge instance") - } - - var nonce *big.Int - - nonce, err = bridgeInstance.GetUserNonceMinted(nil, ethereumAddress) - if err != nil { - Logger.Error("GetUserNonceMinted FAILED", zap.Error(err)) - msg := "failed to execute GetUserNonceMinted call, ethereumAddress = %s" - return nil, errors.Wrapf(err, msg, rawEthereumAddress) - } - - return nonce, err -} - -// 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 { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - tran, err := bridgeInstance.ResetUserNonceMinted(transactOpts) - if err != nil { - Logger.Error("ResetUserNonceMinted FAILED", zap.Error(err)) - msg := "failed to execute ResetUserNonceMinted call, ethereumAddress = %s" - return nil, errors.Wrapf(err, msg, b.EthereumAddress) - } - - Logger.Info( - "Posted ResetUserMintedNonce", - zap.String("ethereumWallet", b.EthereumAddress), - ) - - return tran, err -} - -// MintWZCN Mint ZCN tokens on behalf of the 0ZCN client -// - 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") - } - - // 1. Burned amount parameter - amount := new(big.Int) - amount.SetInt64(payload.Amount) // wei - - // 2. Transaction ID Parameter of burn operation (zcnTxd string as []byte) - zcnTxd := DefaultClientIDEncoder(payload.ZCNTxnID) - - // 3. Nonce Parameter generated during burn operation - nonce := new(big.Int) - nonce.SetInt64(payload.Nonce) - - // 4. Signature - // For requirements from ERC20 authorizer, the signature length must be 65 - var sigs [][]byte - for _, signature := range payload.Signatures { - sigs = append(sigs, signature.Signature) - } - - // 5. To Ethereum address - - toAddress := common.HexToAddress(payload.To) - - bridgeInstance, transactOpts, err := b.prepareBridge(ctx, payload.To, "mint", toAddress, amount, zcnTxd, nonce, sigs) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - Logger.Info( - "Staring Mint WZCN", - zap.Int64("amount", amount.Int64()), - zap.String("zcnTxd", string(zcnTxd)), - zap.String("nonce", nonce.String())) - - var tran *types.Transaction - tran, err = bridgeInstance.Mint(transactOpts, toAddress, amount, zcnTxd, nonce, sigs) - if err != nil { - Logger.Error("Mint WZCN FAILED", zap.Error(err)) - msg := "failed to execute MintWZCN transaction, amount = %s, ZCN TrxID = %s" - return nil, errors.Wrapf(err, msg, amount, zcnTxd) - } - - Logger.Info( - "Posted Mint WZCN", - zap.String("hash", tran.Hash().String()), - zap.Int64("amount", amount.Int64()), - zap.String("zcnTxd", string(zcnTxd)), - zap.String("nonce", nonce.String()), - ) - - return tran, err -} - -// BurnWZCN Burns WZCN tokens on behalf of the 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 { - return nil, errors.New("DefaultClientIDEncoder must be setup") - } - - // 1. Data Parameter (amount to burn) - clientID := DefaultClientIDEncoder(zcncore.GetClientWalletID()) - - // 2. Data Parameter (signature) - amount := new(big.Int) - amount.SetInt64(int64(amountTokens)) - - bridgeInstance, transactOpts, err := b.prepareBridge(ctx, b.EthereumAddress, "burn", amount, clientID) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare bridge") - } - - Logger.Info( - "Staring Burn WZCN", - zap.Int64("amount", amount.Int64()), - ) - - tran, err := bridgeInstance.Burn(transactOpts, amount, clientID) - if err != nil { - msg := "failed to execute Burn WZCN transaction to ClientID = %s with amount = %s" - return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), amount) - } - - Logger.Info( - "Posted Burn WZCN", - zap.String("clientID", zcncore.GetClientWalletID()), - zap.Int64("amount", amount.Int64()), - ) - - return tran, err -} - -// 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 { - log.Logger.Fatal("failed to create new transaction", zap.Error(err)) - } - - Logger.Info( - "Starting MINT smart contract", - zap.String("sc address", wallet.ZCNSCSmartContractAddress), - zap.String("function", wallet.MintFunc), - zap.Int64("mint amount", int64(payload.Amount))) - - hash, err := trx.ExecuteSmartContract( - ctx, - wallet.ZCNSCSmartContractAddress, - wallet.MintFunc, - payload, - 0) - - if err != nil { - return "", errors.Wrap(err, fmt.Sprintf("failed to execute smart contract, hash = %s", hash)) - } - - Logger.Info( - "Mint ZCN transaction", - zap.String("hash", hash), - zap.Int64("mint amount", int64(payload.Amount))) - - return hash, nil -} - -// 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, - } - - trx, err := b.transactionProvider.NewTransactionEntity(txnfee) - if err != nil { - log.Logger.Fatal("failed to create new transaction", zap.Error(err)) - } - - Logger.Info( - "Starting BURN smart contract", - zap.String("sc address", wallet.ZCNSCSmartContractAddress), - zap.String("function", wallet.BurnFunc), - zap.Uint64("burn amount", amount), - ) - - var hash string - hash, err = trx.ExecuteSmartContract( - ctx, - wallet.ZCNSCSmartContractAddress, - wallet.BurnFunc, - payload, - amount, - ) - - if err != nil { - Logger.Error("Burn ZCN transaction FAILED", zap.Error(err)) - return trx, errors.Wrap(err, fmt.Sprintf("failed to execute smart contract, hash = %s", hash)) - } - - err = trx.Verify(context.Background()) - if err != nil { - return trx, errors.Wrap(err, fmt.Sprintf("failed to verify smart contract, hash = %s", hash)) - } - - Logger.Info( - "Burn ZCN transaction", - zap.String("hash", hash), - zap.Uint64("burn amount", amount), - zap.Uint64("amount", amount), - ) - - return trx, nil -} - -// 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) - - // 2. Swap source amount parameter. - sourceInt := big.NewInt(int64(source)) - - // 3. User's Ethereum wallet address parameter - spenderAddress := common.HexToAddress(b.UniswapAddress) - - tokenInstance, transactOpts, err := b.prepareToken(ctx, "approve", tokenAddress, spenderAddress, sourceInt) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare usdctoken") - } - - Logger.Info( - "Starting ApproveUSDCSwap", - zap.String("usdctoken", tokenAddress.String()), - zap.String("spender", spenderAddress.String()), - zap.Int64("source", sourceInt.Int64()), - ) - - var tran *types.Transaction - - tran, err = tokenInstance.Approve(transactOpts, spenderAddress, sourceInt) - if err != nil { - return nil, errors.Wrap(err, "failed to execute approve transaction") - } - - return tran, nil -} - -// 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) - - // 2. User's Ethereum wallet address parameter - from := common.HexToAddress(b.EthereumAddress) - - // 3. Swap source amount parameter. - sourceInt := big.NewInt(int64(source)) - - // 3. Swap path parameter. - path := []common.Address{ - common.HexToAddress(WethTokenAddress), - common.HexToAddress(b.TokenAddress)} - - uniswapRouterInstance, err := uniswaprouter.NewUniswaprouter(contractAddress, b.ethereumClient) - if err != nil { - return nil, errors.Wrap(err, "failed to initialize uniswaprouter instance") - } - - Logger.Info( - "Starting GetETHSwapAmount", - zap.Uint64("source", source)) - - var result []*big.Int - - result, err = uniswapRouterInstance.GetAmountsIn(&bind.CallOpts{From: from}, sourceInt, path) - if err != nil { - Logger.Error("GetAmountsIn FAILED", zap.Error(err)) - msg := "failed to execute GetAmountsIn call, ethereumAddress = %s" - - return nil, errors.Wrapf(err, msg, from) - } - - return result[0], nil -} - -// 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)) - - // 2. Swap target amount parameter. - targetInt := big.NewInt(int64(target)) - - uniswapNetworkInstance, transactOpts, err := b.prepareUniswapNetwork( - ctx, sourceInt, "swapETHForZCNExactAmountOut", targetInt) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare uniswapnetwork") - } - - Logger.Info( - "Starting SwapETH", - zap.Uint64("source", source), - zap.Uint64("target", target)) - - var tran *types.Transaction - - tran, err = uniswapNetworkInstance.SwapETHForZCNExactAmountOut(transactOpts, targetInt) - if err != nil { - return nil, errors.Wrap(err, "failed to execute swapETHForZCNExactAmountOut transaction") - } - - return tran, nil -} - -// 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)) - - // 2. Swap source amount parameter. - targetInt := big.NewInt(int64(target)) - - uniswapNetworkInstance, transactOpts, err := b.prepareUniswapNetwork( - ctx, big.NewInt(0), "swapUSDCForZCNExactAmountOut", targetInt, sourceInt) - if err != nil { - return nil, errors.Wrap(err, "failed to prepare uniswapnetwork") - } - - Logger.Info( - "Starting SwapUSDC", - zap.Uint64("source", source), - zap.Uint64("target", target)) - - var tran *types.Transaction - - tran, err = uniswapNetworkInstance.SwapUSDCForZCNExactAmountOut(transactOpts, targetInt, sourceInt) - if err != nil { - return nil, errors.Wrap(err, "failed to execute swapUSDCForZCNExactAmountOut transaction") - } - - return tran, nil -} - -// prepareUniswapNetwork performs uniswap network smart contract preparation actions. -func (b *BridgeClient) prepareUniswapNetwork(ctx context.Context, value *big.Int, method string, params ...interface{}) (*uniswapnetwork.Uniswap, *bind.TransactOpts, error) { - // 1. Uniswap smart contract address - contractAddress := common.HexToAddress(b.UniswapAddress) - - // 2. To address parameter. - to := common.HexToAddress(b.TokenAddress) - - // 3. From address parameter. - from := common.HexToAddress(b.EthereumAddress) - - abi, err := uniswapnetwork.UniswapMetaData.GetAbi() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get uniswaprouter abi") - } - - var pack []byte - - pack, err = abi.Pack(method, params...) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") - } - - opts := eth.CallMsg{ - To: &to, - From: from, - Data: pack, - } - - if value.Int64() != 0 { - opts.Value = value - } - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, 0) - if value.Int64() != 0 { - transactOpts.Value = value - } - - var uniswapNetworkInstance *uniswapnetwork.Uniswap - - uniswapNetworkInstance, err = uniswapnetwork.NewUniswap(contractAddress, b.ethereumClient) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to initialize uniswapnetwork instance") - } - - return uniswapNetworkInstance, transactOpts, nil -} - -func (b *BridgeClient) prepareToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*zcntoken.Token, *bind.TransactOpts, error) { - abi, err := zcntoken.TokenMetaData.GetAbi() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get zcntoken abi") - } - - pack, err := abi.Pack(method, params...) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") - } - - from := common.HexToAddress(b.EthereumAddress) - - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &tokenAddress, - From: from, - Data: pack, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to estimate gas limit") - } - - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - - var tokenInstance *zcntoken.Token - - tokenInstance, err = zcntoken.NewToken(tokenAddress, b.ethereumClient) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to initialize zcntoken instance") - } - - return tokenInstance, transactOpts, nil -} - -func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { - // To (contract) - contractAddress := common.HexToAddress(b.AuthorizersAddress) - - // Get ABI of the contract - abi, err := authorizers.AuthorizersMetaData.GetAbi() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get ABI") - } - - // Pack the method argument - pack, err := abi.Pack(method, params...) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") - } - - from := common.HexToAddress(b.EthereumAddress) - - // Gas limits in units - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: from, - Data: pack, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to estimate gas") - } - - // Update gas limits + 10% - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - - // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to create authorizers instance") - } - - return authorizersInstance, transactOpts, nil -} - -func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, method string, params ...interface{}) (*bridge.Bridge, *bind.TransactOpts, error) { - // To (contract) - contractAddress := common.HexToAddress(b.BridgeAddress) - - //Get ABI of the contract - abi, err := bridge.BridgeMetaData.GetAbi() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get ABI") - } - - //Pack the method argument - pack, err := abi.Pack(method, params...) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") - } - - //Gas limits in units - fromAddress := common.HexToAddress(ethereumAddress) - - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: fromAddress, - Data: pack, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to estimate gas") - } - - //Update gas limits + 10% - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - - // BridgeClient instance - bridgeInstance, err := bridge.NewBridge(contractAddress, b.ethereumClient) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to create bridge instance") - } - - return bridgeInstance, transactOpts, nil -} - -// getProviderType validates the provider url and exposes pre-defined type definition. -func (b *BridgeClient) getProviderType() int { - if strings.Contains(b.EthereumNodeURL, "g.alchemy.com") { - return AlchemyProvider - } else if strings.Contains(b.EthereumNodeURL, "rpc.tenderly.co") { - return TenderlyProvider - } else { - return UnknownProvider - } -} - -// estimateTenderlyGasAmount performs gas amount estimation for the given transaction using Tenderly provider. -func (b *BridgeClient) estimateTenderlyGasAmount(ctx context.Context, from, to string, value int64) (float64, error) { - return 8000000, nil -} - -// estimateAlchemyGasAmount performs gas amount estimation for the given transaction using Alchemy provider -func (b *BridgeClient) estimateAlchemyGasAmount(ctx context.Context, from, to, data string, value int64) (float64, error) { - client := jsonrpc.NewClient(b.EthereumNodeURL) - - valueHex := ConvertIntToHex(value) - - resp, err := client.Call(ctx, "eth_estimateGas", &AlchemyGasEstimationRequest{ - From: from, - To: to, - Value: valueHex, - Data: data}) - if err != nil { - return 0, errors.Wrap(err, "gas price estimation failed") - } - - if resp.Error != nil { - return 0, errors.Wrap(errors.New(resp.Error.Error()), "gas price estimation failed") - } - - gasAmountRaw, ok := resp.Result.(string) - if !ok { - return 0, errors.New("failed to parse gas amount") - } - - gasAmountInt := new(big.Float) - gasAmountInt.SetString(gasAmountRaw) - - gasAmountFloat, _ := gasAmountInt.Float64() - - return gasAmountFloat, nil -} - -// 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: - abi, err := bridge.BridgeMetaData.GetAbi() - if err != nil { - return 0, errors.Wrap(err, "failed to get ABI") - } - - clientID := DefaultClientIDEncoder(zcncore.GetClientWalletID()) - - amount := new(big.Int) - amount.SetString(amountTokens, 10) - - var packRaw []byte - packRaw, err = abi.Pack("burn", amount, clientID) - if err != nil { - return 0, errors.Wrap(err, "failed to pack arguments") - } - - pack := "0x" + hex.EncodeToString(packRaw) - - return b.estimateAlchemyGasAmount(ctx, from, to, pack, 0) - case TenderlyProvider: - return b.estimateTenderlyGasAmount(ctx, from, to, 0) - } - - return 0, errors.New("used json-rpc does not allow to estimate gas amount") -} - -// 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() { - case AlchemyProvider: - amount := new(big.Int) - amount.SetString(amountToken, 10) - - zcnTransaction := DefaultClientIDEncoder(zcnTransactionRaw) - - nonce := new(big.Int) - nonce.SetInt64(nonceRaw) - - fromRaw := common.HexToAddress(from) - - abi, err := bridge.BridgeMetaData.GetAbi() - if err != nil { - return 0, errors.Wrap(err, "failed to get ABI") - } - - var packRaw []byte - packRaw, err = abi.Pack("mint", fromRaw, amount, zcnTransaction, nonce, signaturesRaw) - if err != nil { - return 0, errors.Wrap(err, "failed to pack arguments") - } - - pack := "0x" + hex.EncodeToString(packRaw) - - return b.estimateAlchemyGasAmount(ctx, from, to, pack, 0) - case TenderlyProvider: - return b.estimateTenderlyGasAmount(ctx, from, to, 0) - } - - return 0, errors.New("used json-rpc does not allow to estimate gas amount") -} - -// estimateTenderlyGasPrice performs gas estimation for the given transaction using Tenderly API. -func (b *BridgeClient) estimateTenderlyGasPrice(ctx context.Context) (float64, error) { - return 1, nil -} - -// estimateAlchemyGasPrice performs gas estimation for the given transaction using Alchemy enhanced API returning -// approximate final gas fee. -func (b *BridgeClient) estimateAlchemyGasPrice(ctx context.Context) (float64, error) { - client := jsonrpc.NewClient(b.EthereumNodeURL) - - resp, err := client.Call(ctx, "eth_gasPrice") - if err != nil { - return 0, errors.Wrap(err, "gas price estimation failed") - } - - if resp.Error != nil { - return 0, errors.Wrap(errors.New(resp.Error.Error()), "gas price estimation failed") - } - - gasPriceRaw, ok := resp.Result.(string) - if !ok { - return 0, errors.New("failed to parse gas price") - } - - gasPriceInt := new(big.Float) - gasPriceInt.SetString(gasPriceRaw) - - gasPriceFloat, _ := gasPriceInt.Float64() - - return gasPriceFloat, nil -} - -// 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: - return b.estimateAlchemyGasPrice(ctx) - case TenderlyProvider: - return b.estimateTenderlyGasPrice(ctx) - } - - return 0, errors.New("used json-rpc does not allow to estimate gas price") -} diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go deleted file mode 100644 index 5af563264..000000000 --- a/zcnbridge/bridge_helper.go +++ /dev/null @@ -1,105 +0,0 @@ -package zcnbridge - -import ( - "fmt" - "math/big" - "time" - - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/sys" - "github.com/pkg/errors" -) - -// AlchemyGasEstimationRequest describes request used for Alchemy enhanced JSON-RPC API. -type AlchemyGasEstimationRequest struct { - From string `json:"from"` - To string `json:"to"` - Value string `json:"value"` - Data string `json:"data"` -} - -// GasEstimationRequest describes request used for Alchemy enhanced JSON-RPC API. -type GasEstimationRequest struct { - From string `json:"from"` - To string `json:"to"` - Value string `json:"value"` -} - -// GasPriceEstimationResult represents result of the gas price estimation operation execution. -type GasPriceEstimationResult struct { - Value float64 `json:"value"` -} - -// BancorTokenDetails describes Bancor ZCN zcntoken pool details -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"` -} - -func GetTransactionStatus(hash string) (int, error) { - _, err := zcncore.GetEthClient() - if err != nil { - return -1, err - } - - 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 - err error - ) - - if hash == "" { - return -1, errors.New("transaction hash should not be empty") - } - - for i := 0; i < times; i++ { - res, err = GetTransactionStatus(hash) - if err != nil { - Logger.Info(fmt.Sprintf("confirmation of Ethereum transaction %s [ERROR]", hash)) - return -1, err - } - if res == 1 { - Logger.Info(fmt.Sprintf("confirmation of Ethereum transaction %s [OK]", hash)) - return res, nil - } - if res == 0 { - Logger.Info(fmt.Sprintf("confirmation of Ethereum transaction %s [FAILED]", hash)) - return res, nil - } - Logger.Info(fmt.Sprintf("Try confirming Ethereum transaction %s # %d", hash, i)) - sys.Sleep(duration) - } - - Logger.Info(fmt.Sprintf("Verification of transaction %s is still pending after %d efforts, try checking it later", hash, times)) - - return res, nil -} - -func addPercents(gasLimitUnits uint64, percents int) *big.Int { - gasLimitBig := big.NewInt(int64(gasLimitUnits)) - factorBig := big.NewInt(int64(percents)) - deltaBig := gasLimitBig.Div(gasLimitBig, factorBig) - - origin := big.NewInt(int64(gasLimitUnits)) - gasLimitBig = origin.Add(origin, deltaBig) - - return gasLimitBig -} - -// ConvertIntToHex converts given int value to hex string. -func ConvertIntToHex(value int64) string { - return fmt.Sprintf("%#x", value) -} diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go deleted file mode 100644 index 90bd60f55..000000000 --- a/zcnbridge/bridge_test.go +++ /dev/null @@ -1,657 +0,0 @@ -package zcnbridge - -import ( - "context" - "encoding/hex" - "encoding/json" - "log" - "math/big" - "os" - "path" - "strconv" - "testing" - "time" - - "github.com/0chain/gosdk/zcnbridge/ethereum/uniswapnetwork" - "github.com/ethereum/go-ethereum/accounts/abi" - - "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" - - "github.com/0chain/gosdk/zcnbridge/ethereum" - "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" - binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" - bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" - "github.com/0chain/gosdk/zcnbridge/transaction" - transactionmocks "github.com/0chain/gosdk/zcnbridge/transaction/mocks" - "github.com/0chain/gosdk/zcnbridge/wallet" - "github.com/0chain/gosdk/zcnbridge/zcnsc" - "github.com/0chain/gosdk/zcncore" - sdkcommon "github.com/0chain/gosdk_common/core/common" - eth "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/common" - "github.com/spf13/viper" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -const ( - ethereumAddress = "0xD8c9156e782C68EE671C09b6b92de76C97948432" - - alchemyEthereumNodeURL = "https://eth-mainnet.g.alchemy.com/v2/9VanLUbRE0pLmDHwCHGJlhs9GHosrfD9" - tenderlyEthereumNodeURL = "https://rpc.tenderly.co/fork/835ecb4e-1f60-4129-adc2-b0c741193839" - infuraEthereumNodeURL = "https://mainnet.infura.io/v3/7238211010344719ad14a89db874158c" - - password = "02289b9" - - authorizerDelegatedAddress = "0xa149B58b7e1390D152383BB03dBc79B390F648e2" - - bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" - tokenAddress = "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78" - authorizersAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" - uniswapAddress = "0x4c12C2FeEDD86267d17dB64BaB2cFD12cD8611f5" - - zcnTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" - amount = 1 - txnFee = 1 - nonce = 1 - - ethereumTxnID = "0x3b59971c2aa294739cd73912f0c5a7996aafb796238cf44408b0eb4af0fbac82" - - clientId = "d6e9b3222434faa043c683d1a939d6a0fa2818c4d56e794974d64a32005330d3" -) - -var ( - uniswapSmartContractCode = "60806040526004361061002d5760003560e01c806318ae74a41461003957806397a40b341461006957610034565b3661003457005b600080fd5b610053600480360381019061004e9190610781565b6100a6565b60405161006091906107bd565b60405180910390f35b34801561007557600080fd5b50610090600480360381019061008b91906107d8565b61017e565b60405161009d91906107bd565b60405180910390f35b60008060008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663fb3bdb4134856100ef61061a565b33426040518663ffffffff1660e01b81526004016101109493929190610917565b60006040518083038185885af115801561012e573d6000803e3d6000fd5b50505050506040513d6000823e3d601f19601f820116820180604052508101906101589190610ad1565b90508060018151811061016e5761016d610b1a565b5b6020026020010151915050919050565b6000600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd3330856040518463ffffffff1660e01b81526004016101df93929190610b49565b6020604051808303816000875af11580156101fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102229190610bb8565b50600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663095ea7b360008054906101000a900473ffffffffffffffffffffffffffffffffffffffff16846040518363ffffffff1660e01b81526004016102a0929190610be5565b6020604051808303816000875af11580156102bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102e39190610bb8565b506060600367ffffffffffffffff81111561030157610300610979565b5b60405190808252806020026020018201604052801561032f5781602001602082028036833780820191505090505b50905073a0b86991c6218b36c1d19d4a2e9eb0ce3606eb488160008151811061035b5761035a610b1a565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2816001815181106103be576103bd610b1a565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505073b9ef770b6a5e12e45983c5d80545258aa38f3b788160028151811061042157610420610b1a565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505060008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638803dbee86868533426040518663ffffffff1660e01b81526004016104bf959493929190610c0e565b6000604051808303816000875af11580156104de573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906105079190610ad1565b9050838160008151811061051e5761051d610b1a565b5b602002602001015110156105f457600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb338360008151811061057f5761057e610b1a565b5b6020026020010151876105929190610c97565b6040518363ffffffff1660e01b81526004016105af929190610be5565b6020604051808303816000875af11580156105ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105f29190610bb8565b505b8060028151811061060857610607610b1a565b5b60200260200101519250505092915050565b60606000600267ffffffffffffffff81111561063957610638610979565b5b6040519080825280602002602001820160405280156106675781602001602082028036833780820191505090505b50905073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28160008151811061069357610692610b1a565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505073b9ef770b6a5e12e45983c5d80545258aa38f3b78816001815181106106f6576106f5610b1a565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250508091505090565b6000604051905090565b600080fd5b600080fd5b6000819050919050565b61075e8161074b565b811461076957600080fd5b50565b60008135905061077b81610755565b92915050565b60006020828403121561079757610796610741565b5b60006107a58482850161076c565b91505092915050565b6107b78161074b565b82525050565b60006020820190506107d260008301846107ae565b92915050565b600080604083850312156107ef576107ee610741565b5b60006107fd8582860161076c565b925050602061080e8582860161076c565b9150509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061086f82610844565b9050919050565b61087f81610864565b82525050565b60006108918383610876565b60208301905092915050565b6000602082019050919050565b60006108b582610818565b6108bf8185610823565b93506108ca83610834565b8060005b838110156108fb5781516108e28882610885565b97506108ed8361089d565b9250506001810190506108ce565b5085935050505092915050565b61091181610864565b82525050565b600060808201905061092c60008301876107ae565b818103602083015261093e81866108aa565b905061094d6040830185610908565b61095a60608301846107ae565b95945050505050565b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6109b182610968565b810181811067ffffffffffffffff821117156109d0576109cf610979565b5b80604052505050565b60006109e3610737565b90506109ef82826109a8565b919050565b600067ffffffffffffffff821115610a0f57610a0e610979565b5b602082029050602081019050919050565b600080fd5b600081519050610a3481610755565b92915050565b6000610a4d610a48846109f4565b6109d9565b90508083825260208201905060208402830185811115610a7057610a6f610a20565b5b835b81811015610a995780610a858882610a25565b845260208401935050602081019050610a72565b5050509392505050565b600082601f830112610ab857610ab7610963565b5b8151610ac8848260208601610a3a565b91505092915050565b600060208284031215610ae757610ae6610741565b5b600082015167ffffffffffffffff811115610b0557610b04610746565b5b610b1184828501610aa3565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b6000606082019050610b5e6000830186610908565b610b6b6020830185610908565b610b7860408301846107ae565b949350505050565b60008115159050919050565b610b9581610b80565b8114610ba057600080fd5b50565b600081519050610bb281610b8c565b92915050565b600060208284031215610bce57610bcd610741565b5b6000610bdc84828501610ba3565b91505092915050565b6000604082019050610bfa6000830185610908565b610c0760208301846107ae565b9392505050565b600060a082019050610c2360008301886107ae565b610c3060208301876107ae565b8181036040830152610c4281866108aa565b9050610c516060830185610908565b610c5e60808301846107ae565b9695505050505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000610ca28261074b565b9150610cad8361074b565b9250828203905081811115610cc557610cc4610c68565b5b9291505056fea26469706673582212207de082f4e5f623e928f9b99a8e233f194bacc23969b40ea49a470ecfd2a1fb8464736f6c63430008140033" -) - -var ( - testKeyStoreLocation = path.Join(".", EthereumWalletStorageDir) -) - -var ( - ethereumSignatures = []*ethereum.AuthorizerSignature{ - { - ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", - Signature: []byte("0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61"), - }, - } - - zcnScSignatures = []*zcnsc.AuthorizerSignature{ - { - ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", - Signature: "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61", - }, - } -) - -type ethereumClientMock struct { - mock.TestingT -} - -func (ecm *ethereumClientMock) Cleanup(callback func()) { - callback() -} - -type transactionMock struct { - mock.TestingT -} - -func (tem *transactionMock) Cleanup(callback func()) { - callback() -} - -type transactionProviderMock struct { - mock.TestingT -} - -func (tem *transactionProviderMock) Cleanup(callback func()) { - callback() -} - -type keyStoreMock struct { - mock.TestingT -} - -func (ksm *keyStoreMock) Cleanup(callback func()) { - callback() -} - -type authorizerConfigTarget struct { - Fee sdkcommon.Balance `json:"fee"` -} - -type authorizerNodeTarget struct { - ID string `json:"id"` - PublicKey string `json:"public_key"` - URL string `json:"url"` - Config *authorizerConfigTarget `json:"config"` -} - -type authorizerConfigSource struct { - Fee string `json:"fee"` -} - -type authorizerNodeSource struct { - ID string `json:"id"` - Config *authorizerConfigSource `json:"config"` -} - -func (an *authorizerNodeTarget) decode(input []byte) error { - var objMap map[string]*json.RawMessage - err := json.Unmarshal(input, &objMap) - if err != nil { - return err - } - - id, ok := objMap["id"] - if ok { - var idStr *string - err = json.Unmarshal(*id, &idStr) - if err != nil { - return err - } - an.ID = *idStr - } - - pk, ok := objMap["public_key"] - if ok { - var pkStr *string - err = json.Unmarshal(*pk, &pkStr) - if err != nil { - return err - } - an.PublicKey = *pkStr - } - - url, ok := objMap["url"] - if ok { - var urlStr *string - err = json.Unmarshal(*url, &urlStr) - if err != nil { - return err - } - an.URL = *urlStr - } - - rawCfg, ok := objMap["config"] - if ok { - var cfg = &authorizerConfigTarget{} - err = cfg.decode(*rawCfg) - if err != nil { - return err - } - - an.Config = cfg - } - - return nil -} - -func (c *authorizerConfigTarget) decode(input []byte) (err error) { - const ( - Fee = "fee" - ) - - var objMap map[string]*json.RawMessage - err = json.Unmarshal(input, &objMap) - if err != nil { - return err - } - - fee, ok := objMap[Fee] - if ok { - var feeStr *string - err = json.Unmarshal(*fee, &feeStr) - if err != nil { - return err - } - - var balance, err = strconv.ParseInt(*feeStr, 10, 64) - if err != nil { - return err - } - - c.Fee = sdkcommon.Balance(balance) - } - - return nil -} - -func getEthereumClient(t mock.TestingT) *bridgemocks.EthereumClient { - return bridgemocks.NewEthereumClient(ðereumClientMock{t}) -} - -func getBridgeClient(ethereumNodeURL string, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { - cfg := viper.New() - - tempConfigFile, err := os.CreateTemp(".", "config.yaml") - if err != nil { - log.Fatalln(err) - } - - defer func(name string) { - err := os.Remove(name) - if err != nil { - log.Fatalln(err) - } - }(tempConfigFile.Name()) - - cfg.SetConfigFile(tempConfigFile.Name()) - - cfg.SetDefault("bridge.bridge_address", bridgeAddress) - cfg.SetDefault("bridge.token_address", tokenAddress) - cfg.SetDefault("bridge.authorizers_address", authorizersAddress) - cfg.SetDefault("bridge.uniswap_address", uniswapAddress) - cfg.SetDefault("bridge.ethereum_address", ethereumAddress) - cfg.SetDefault("bridge.password", password) - cfg.SetDefault("bridge.gas_limit", 0) - cfg.SetDefault("bridge.consensus_threshold", 0) - - return NewBridgeClient( - cfg.GetString("bridge.bridge_address"), - cfg.GetString("bridge.token_address"), - cfg.GetString("bridge.authorizers_address"), - cfg.GetString("bridge.uniswap_address"), - cfg.GetString("bridge.ethereum_address"), - ethereumNodeURL, - cfg.GetString("bridge.password"), - cfg.GetUint64("bridge.gas_limit"), - cfg.GetFloat64("bridge.consensus_threshold"), - - ethereumClient, - transactionProvider, - keyStore, - ) -} - -func prepareEthereumClientGeneralMockCalls(ethereumClient *mock.Mock) { - ethereumClient.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) - ethereumClient.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) - ethereumClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(nonce), nil) - ethereumClient.On("SuggestGasPrice", mock.Anything).Return(big.NewInt(400000), nil) - ethereumClient.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) -} - -func getTransaction(t mock.TestingT) *transactionmocks.Transaction { - return transactionmocks.NewTransaction(&transactionMock{t}) -} - -func prepareTransactionGeneralMockCalls(transaction *mock.Mock) { - transaction.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(zcnTxnID, nil) - transaction.On("Verify", mock.Anything).Return(nil) -} - -func getTransactionProvider(t mock.TestingT) *transactionmocks.TransactionProvider { - return transactionmocks.NewTransactionProvider(&transactionProviderMock{t}) -} - -func prepareTransactionProviderGeneralMockCalls(transactionProvider *mock.Mock, transaction *transactionmocks.Transaction) { - transactionProvider.On("NewTransactionEntity", mock.Anything).Return(transaction, nil) -} - -func getKeyStore(t mock.TestingT) *bridgemocks.KeyStore { - return bridgemocks.NewKeyStore(&keyStoreMock{t}) -} - -func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { - ks := keystore.NewKeyStore(testKeyStoreLocation, keystore.StandardScryptN, keystore.StandardScryptP) - - keyStore.On("Find", mock.Anything).Return(accounts.Account{Address: common.HexToAddress(ethereumAddress)}, nil) - keyStore.On("TimedUnlock", mock.Anything, mock.Anything, mock.Anything).Run( - func(args mock.Arguments) { - err := ks.TimedUnlock(args.Get(0).(accounts.Account), args.Get(1).(string), args.Get(2).(time.Duration)) - if err != nil { - log.Fatalln(err) - } - }, - ).Return(nil) - keyStore.On("SignHash", mock.Anything, mock.Anything).Return([]byte(ethereumAddress), nil) - - keyStore.On("GetEthereumKeyStore").Return(ks) -} - -func Test_ZCNBridge(t *testing.T) { - ethereumClient := getEthereumClient(t) - prepareEthereumClientGeneralMockCalls(ðereumClient.Mock) - - tx := getTransaction(t) - prepareTransactionGeneralMockCalls(&tx.Mock) - - transactionProvider := getTransactionProvider(t) - prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, tx) - - keyStore := getKeyStore(t) - prepareKeyStoreGeneralMockCalls(keyStore) - - bridgeClient := getBridgeClient(alchemyEthereumNodeURL, ethereumClient, transactionProvider, keyStore) - - t.Run("should update authorizer config.", func(t *testing.T) { - source := &authorizerNodeSource{ - ID: "12345678", - Config: &authorizerConfigSource{ - Fee: "999", - }, - } - target := &authorizerNodeTarget{} - - bytes, err := json.Marshal(source) - require.NoError(t, err) - - err = target.decode(bytes) - require.NoError(t, err) - - require.Equal(t, "", target.URL) - require.Equal(t, "", target.PublicKey) - require.Equal(t, "12345678", target.ID) - require.Equal(t, sdkcommon.Balance(999), target.Config.Fee) - }) - - t.Run("should check configuration formating in MintWZCN", func(t *testing.T) { - _, err := bridgeClient.MintWZCN(context.Background(), ðereum.MintPayload{ - ZCNTxnID: zcnTxnID, - Amount: amount, - To: ethereumAddress, - Nonce: nonce, - Signatures: ethereumSignatures, - }) - require.NoError(t, err) - - var sigs [][]byte - for _, signature := range ethereumSignatures { - sigs = append(sigs, signature.Signature) - } - - to := common.HexToAddress(bridgeAddress) - fromAddress := common.HexToAddress(ethereumAddress) - - rawAbi, err := binding.BridgeMetaData.GetAbi() - require.NoError(t, err) - - pack, err := rawAbi.Pack("mint", common.HexToAddress(ethereumAddress), - big.NewInt(amount), - DefaultClientIDEncoder(zcnTxnID), - big.NewInt(nonce), - sigs) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: fromAddress, - Data: pack, - }, - )) - }) - - t.Run("should check configuration formating in BurnWZCN", func(t *testing.T) { - _, err := bridgeClient.BurnWZCN(context.Background(), amount) - require.NoError(t, err) - - to := common.HexToAddress(bridgeAddress) - fromAddress := common.HexToAddress(ethereumAddress) - - rawAbi, err := binding.BridgeMetaData.GetAbi() - require.NoError(t, err) - - pack, err := rawAbi.Pack("burn", big.NewInt(amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: fromAddress, - Data: pack, - }, - )) - }) - - t.Run("should check configuration used by MintZCN", func(t *testing.T) { - payload := &zcnsc.MintPayload{ - EthereumTxnID: ethereumTxnID, - Amount: sdkcommon.Balance(amount), - Nonce: nonce, - Signatures: zcnScSignatures, - ReceivingClientID: clientId, - } - - _, err := bridgeClient.MintZCN(context.Background(), payload) - require.NoError(t, err) - - require.True(t, tx.AssertCalled( - t, - "ExecuteSmartContract", - context.Background(), - wallet.ZCNSCSmartContractAddress, - wallet.MintFunc, - payload, - uint64(0), - )) - }) - - t.Run("should check configuration used by BurnZCN", func(t *testing.T) { - _, err := bridgeClient.BurnZCN(context.Background(), amount, txnFee) - require.NoError(t, err) - - require.True(t, tx.AssertCalled( - t, - "ExecuteSmartContract", - context.Background(), - wallet.ZCNSCSmartContractAddress, - wallet.BurnFunc, - zcnsc.BurnPayload{ - EthereumAddress: ethereumAddress, - }, - uint64(amount), - )) - }) - - t.Run("should check configuration used by AddEthereumAuthorizer", func(t *testing.T) { - _, err := bridgeClient.AddEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) - require.NoError(t, err) - - to := common.HexToAddress(authorizersAddress) - fromAddress := common.HexToAddress(ethereumAddress) - - rawAbi, err := authorizers.AuthorizersMetaData.GetAbi() - require.NoError(t, err) - - pack, err := rawAbi.Pack("addAuthorizers", common.HexToAddress(authorizerDelegatedAddress)) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: fromAddress, - Data: pack, - }, - )) - }) - - t.Run("should check configuration used by RemoveAuthorizer", func(t *testing.T) { - _, err := bridgeClient.RemoveEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) - require.NoError(t, err) - - to := common.HexToAddress(authorizersAddress) - fromAddress := common.HexToAddress(ethereumAddress) - - rawAbi, err := authorizers.AuthorizersMetaData.GetAbi() - require.NoError(t, err) - - pack, err := rawAbi.Pack("removeAuthorizers", common.HexToAddress(authorizerDelegatedAddress)) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: fromAddress, - Data: pack, - }, - )) - }) - - t.Run("should check configuration used by IncreaseBurnerAllowance", func(t *testing.T) { - _, err := bridgeClient.IncreaseBurnerAllowance(context.Background(), amount) - require.NoError(t, err) - - spenderAddress := common.HexToAddress(bridgeAddress) - - to := common.HexToAddress(tokenAddress) - fromAddress := common.HexToAddress(ethereumAddress) - - rawAbi, err := zcntoken.TokenMetaData.GetAbi() - require.NoError(t, err) - - pack, err := rawAbi.Pack("increaseApproval", spenderAddress, big.NewInt(amount)) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: fromAddress, - Data: pack, - }, - )) - }) - - t.Run("should check configuration used by SwapETH", func(t *testing.T) { - uniswapSmartContractCodeRaw, err := hex.DecodeString(uniswapSmartContractCode) - require.NoError(t, err) - - ethereumClient.On("PendingCodeAt", mock.Anything, mock.Anything).Return(uniswapSmartContractCodeRaw, nil) - - _, err = bridgeClient.SwapETH(context.Background(), amount, amount) - require.NoError(t, err) - - // 1. To address parameter. - to := common.HexToAddress(bridgeClient.UniswapAddress) - - // 2. From address parameter. - from := common.HexToAddress(bridgeClient.EthereumAddress) - - // 3. Swap amount parameter - swapAmount := big.NewInt(amount) - - var rawAbi *abi.ABI - - rawAbi, err = uniswapnetwork.UniswapMetaData.GetAbi() - require.NoError(t, err) - - var pack []byte - - pack, err = rawAbi.Pack("swapETHForZCNExactAmountOut", swapAmount) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: from, - Data: pack, - Value: swapAmount, - GasPrice: big.NewInt(400000), - }, - )) - }) - - t.Run("should check configuration used by SwapUSDC", func(t *testing.T) { - uniswapSmartContractCodeRaw, err := hex.DecodeString(uniswapSmartContractCode) - require.NoError(t, err) - - ethereumClient.On("PendingCodeAt", mock.Anything, mock.Anything).Return(uniswapSmartContractCodeRaw, nil) - - _, err = bridgeClient.SwapUSDC(context.Background(), amount, amount) - require.NoError(t, err) - - // 1. To address parameter. - to := common.HexToAddress(bridgeClient.UniswapAddress) - - // 2. From address parameter. - from := common.HexToAddress(bridgeClient.EthereumAddress) - - // 3. Swap amount parameter - swapAmount := big.NewInt(amount) - - var rawAbi *abi.ABI - - rawAbi, err = uniswapnetwork.UniswapMetaData.GetAbi() - require.NoError(t, err) - - var pack []byte - - pack, err = rawAbi.Pack("swapUSDCForZCNExactAmountOut", swapAmount, swapAmount) - require.NoError(t, err) - - require.True(t, ethereumClient.AssertCalled( - t, - "EstimateGas", - context.Background(), - eth.CallMsg{ - To: &to, - From: from, - Data: pack, - Value: big.NewInt(0), - GasPrice: big.NewInt(400000), - }, - )) - }) - - t.Run("should check configuration used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { - bridgeClient.CreateSignedTransactionFromKeyStore(ethereumClient, 400000) - - require.True(t, ethereumClient.AssertCalled( - t, - "PendingNonceAt", - context.Background(), - common.HexToAddress(ethereumAddress))) - - require.True(t, keyStore.AssertCalled( - t, - "TimedUnlock", - accounts.Account{ - Address: common.HexToAddress(ethereumAddress), - }, - password, - time.Second*2, - )) - }) - - t.Run("should check if gas price estimation works with correct alchemy ethereum node url", func(t *testing.T) { - bridgeClient = getBridgeClient(alchemyEthereumNodeURL, ethereumClient, transactionProvider, keyStore) - - _, err := bridgeClient.EstimateGasPrice(context.Background()) - require.Contains(t, err.Error(), "Must be authenticated!") - }) - - t.Run("should check if gas price estimation works with correct tenderly ethereum node url", func(t *testing.T) { - bridgeClient = getBridgeClient(tenderlyEthereumNodeURL, ethereumClient, transactionProvider, keyStore) - - _, err := bridgeClient.EstimateGasPrice(context.Background()) - require.NoError(t, err) - }) - - t.Run("should check if gas price estimation works with incorrect ethereum node url", func(t *testing.T) { - bridgeClient = getBridgeClient(infuraEthereumNodeURL, ethereumClient, transactionProvider, keyStore) - - _, err := bridgeClient.EstimateGasPrice(context.Background()) - require.Error(t, err) - }) -} diff --git a/zcnbridge/config.go b/zcnbridge/config.go deleted file mode 100644 index 09bae207a..000000000 --- a/zcnbridge/config.go +++ /dev/null @@ -1,174 +0,0 @@ -package zcnbridge - -import ( - "context" - "fmt" - "math/big" - "path" - - "github.com/ethereum/go-ethereum/accounts/abi/bind" - - "github.com/0chain/gosdk/zcnbridge/log" - "github.com/0chain/gosdk/zcnbridge/transaction" - "github.com/ethereum/go-ethereum/ethclient" - - "github.com/spf13/viper" -) - -const ( - TenderlyProvider = iota - AlchemyProvider - UnknownProvider -) - -const ( - EthereumWalletStorageDir = "wallets" -) - -const ( - UniswapRouterAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D" - UsdcTokenAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" - WethTokenAddress = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" -) - -// BridgeSDKConfig describes the configuration for the bridge SDK. -type BridgeSDKConfig struct { - LogLevel *string - LogPath *string - ConfigChainFile *string - ConfigDir *string - Development *bool -} - -// EthereumClient describes Ethereum JSON-RPC client generealized interface -type EthereumClient interface { - bind.ContractBackend - - 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 - ethereumClient EthereumClient - - BridgeAddress, - TokenAddress, - AuthorizersAddress, - UniswapAddress, - NFTConfigAddress, - EthereumAddress, - EthereumNodeURL, - Password string - - BancorAPIURL string - - ConsensusThreshold float64 - GasLimit uint64 -} - -// 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, - authorizersAddress, - uniswapAddress, - ethereumAddress, - ethereumNodeURL, - password string, - gasLimit uint64, - consensusThreshold float64, - ethereumClient EthereumClient, - transactionProvider transaction.TransactionProvider, - keyStore KeyStore) *BridgeClient { - return &BridgeClient{ - BridgeAddress: bridgeAddress, - TokenAddress: tokenAddress, - AuthorizersAddress: authorizersAddress, - UniswapAddress: uniswapAddress, - EthereumAddress: ethereumAddress, - EthereumNodeURL: ethereumNodeURL, - Password: password, - GasLimit: gasLimit, - ConsensusThreshold: consensusThreshold, - ethereumClient: ethereumClient, - transactionProvider: transactionProvider, - keyStore: keyStore, - } -} - -func initChainConfig(sdkConfig *BridgeSDKConfig) *viper.Viper { - cfg := readConfig(sdkConfig, func() string { - return *sdkConfig.ConfigChainFile - }) - - log.Logger.Info(fmt.Sprintf("Chain config has been initialized from %s", cfg.ConfigFileUsed())) - - return cfg -} - -func readConfig(sdkConfig *BridgeSDKConfig, getConfigName func() string) *viper.Viper { - cfg := viper.New() - cfg.AddConfigPath(*sdkConfig.ConfigDir) - cfg.SetConfigName(getConfigName()) - cfg.SetConfigType("yaml") - err := cfg.ReadInConfig() - if err != nil { - log.Logger.Fatal(fmt.Errorf("%w: can't read config", err).Error()) - } - return cfg -} - -// 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) - - chainCfg := initChainConfig(cfg) - - ethereumNodeURL := chainCfg.GetString("ethereum_node_url") - - ethereumClient, err := ethclient.Dial(ethereumNodeURL) - if err != nil { - Logger.Error(err) - } - - transactionProvider := transaction.NewTransactionProvider() - - homedir := path.Dir(chainCfg.ConfigFileUsed()) - if homedir == "" { - log.Logger.Fatal("err happened during home directory retrieval") - } - - keyStore := NewKeyStore(path.Join(homedir, EthereumWalletStorageDir)) - - return NewBridgeClient( - chainCfg.GetString("bridge.bridge_address"), - chainCfg.GetString("bridge.token_address"), - chainCfg.GetString("bridge.authorizers_address"), - chainCfg.GetString("bridge.uniswap_address"), - chainCfg.GetString("bridge.ethereum_address"), - ethereumNodeURL, - chainCfg.GetString("bridge.password"), - chainCfg.GetUint64("bridge.gas_limit"), - chainCfg.GetFloat64("bridge.consensus_threshold"), - ethereumClient, - transactionProvider, - keyStore, - ) -} diff --git a/zcnbridge/crypto/hash.go b/zcnbridge/crypto/hash.go deleted file mode 100644 index de4dc4304..000000000 --- a/zcnbridge/crypto/hash.go +++ /dev/null @@ -1,46 +0,0 @@ -// Methods and types to support cryptographic operations. -package crypto - -import ( - "encoding/hex" - - "golang.org/x/crypto/sha3" -) - -const HashLength = 32 - -type HashBytes [HashLength]byte - -// Hash computes hash of the given data using RawHash and returns result as hex decoded string. -func Hash(data interface{}) string { - return hex.EncodeToString(RawHash(data)) -} - -// RawHash computes SHA3-256 hash depending on data type and returns the hash bytes. -// -// RawHash panics if data type is unknown. -// -// Known types: -// -// - []byte -// -// - HashBytes -// -// - string -func RawHash(data interface{}) []byte { - var databuf []byte - switch dataImpl := data.(type) { - case []byte: - databuf = dataImpl - case HashBytes: - databuf = dataImpl[:] - case string: - databuf = []byte(dataImpl) - default: - panic("unknown type") - } - hash := sha3.New256() - hash.Write(databuf) - var buf []byte - return hash.Sum(buf) -} diff --git a/zcnbridge/doc.go b/zcnbridge/doc.go deleted file mode 100644 index 241d25f3d..000000000 --- a/zcnbridge/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// 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 deleted file mode 100644 index 2737754ee..000000000 --- a/zcnbridge/errors/errors.go +++ /dev/null @@ -1,109 +0,0 @@ -// Error struct and functions. -package errors - -import ( - "errors" - "fmt" - "os" -) - -const ( - delim = ": " -) - -type ( - // Error type for a new application error. - Error struct { - Code string `json:"code,omitempty"` - Msg string `json:"msg"` - } -) - -type ( - // ErrWrapper implements error wrapper interface. - ErrWrapper struct { - code string - text string - wrap error - } -) - -// Error implements error interface. -func (e *ErrWrapper) Error() string { - return e.code + delim + e.text -} - -// Unwrap implements error unwrap interface. -func (e *ErrWrapper) Unwrap() error { - return e.wrap -} - -// Wrap implements error wrapper interface. -func (e *ErrWrapper) Wrap(err error) *ErrWrapper { - return Wrap(e.code, e.text, err) -} - -// Any reports whether an error in error's chain -// matches to any error provided in list. -func Any(err error, targets ...error) bool { - for _, target := range targets { - if errors.Is(err, target) { - return true - } - } - - return false -} - -// ExitErr prints error to os.Stderr and call os.Exit with given code. -func ExitErr(text string, err error, code int) { - text = Wrap("exit", text, err).Error() - _, _ = os.Stderr.Write([]byte(text)) - os.Exit(code) -} - -// ExitMsg prints message to os.Stderr and call os.Exit with given code. -func ExitMsg(text string, code int) { - text = New("exit", text).Error() - _, _ = os.Stderr.Write([]byte(text)) - os.Exit(code) -} - -// 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) -} - -// New returns constructed error wrapper interface. -func New(code, text string) *ErrWrapper { - return &ErrWrapper{code: code, text: text} -} - -// Wrap wraps given error into a new error with format. -func Wrap(code, text string, err error) *ErrWrapper { - wrapper := &ErrWrapper{code: code, text: text} - if err != nil && !errors.Is(wrapper, err) { - wrapper.wrap = err - wrapper.text += delim + err.Error() - } - - return wrapper -} - -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} -} - -/*NewErrorf - create a new error with format */ -func NewErrorf(code string, format string, args ...interface{}) *Error { - return &Error{Code: code, Msg: fmt.Sprintf(format, args...)} -} diff --git a/zcnbridge/errors/errors_test.go b/zcnbridge/errors/errors_test.go deleted file mode 100644 index ab92ee410..000000000 --- a/zcnbridge/errors/errors_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package errors - -import ( - "reflect" - "testing" -) - -const ( - testCode = "test_code" - testText = "test text" - wrapCode = "wrap_code" - wrapText = "wrap text" -) - -func Test_errWrapper_Error(t *testing.T) { - t.Parallel() - - tests := [1]struct { - name string - err error - want string - }{ - { - name: "OK", - err: Wrap(wrapCode, wrapText, New(testCode, testText)), - want: wrapCode + delim + wrapText + delim + testCode + delim + testText, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.err.Error(); got != test.want { - t.Errorf("Error() got: %v | want: %v", got, test.want) - } - }) - } -} - -func Test_errWrapper_Unwrap(t *testing.T) { - t.Parallel() - - err := New(testCode, testText) - - tests := [1]struct { - name string - wrapper *ErrWrapper - want error - }{ - { - name: "OK", - wrapper: Wrap(wrapCode, wrapText, err), - want: err, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.wrapper.Unwrap(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Unwrap() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_errWrapper_Wrap(t *testing.T) { - t.Parallel() - - err := New(testCode, testText) - - tests := [1]struct { - name string - error error - wrapper *ErrWrapper - want *ErrWrapper - }{ - { - name: "OK", - error: New(testCode, testText), - wrapper: New(wrapCode, wrapText), - want: &ErrWrapper{code: wrapCode, text: wrapText + delim + err.Error(), wrap: err}, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.wrapper.Wrap(test.error); !reflect.DeepEqual(got, test.want) { - t.Errorf("Wrap() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_errAny(t *testing.T) { - t.Parallel() - - testErr := New(testCode, testText) - wrapErr := Wrap(wrapCode, wrapText, testErr) - - tests := [2]struct { - name string - list []error - wrapErr error - want bool - }{ - { - name: "TRUE", - list: []error{testErr}, - wrapErr: wrapErr, - want: true, - }, - { - name: "FALSE", - list: []error{testErr}, - wrapErr: Wrap(wrapCode, wrapText, New(testCode, testText)), - want: false, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := Any(test.wrapErr, test.list...); got != test.want { - t.Errorf("errIs() got: %v | want: %v", got, test.want) - } - }) - } -} - -func Test_errIs(t *testing.T) { - t.Parallel() - - testErr := New(testCode, testText) - wrapErr := Wrap(wrapCode, wrapText, testErr) - - tests := [2]struct { - name string - testErr error - wrapErr error - want bool - }{ - { - name: "TRUE", - testErr: testErr, - wrapErr: wrapErr, - want: true, - }, - { - name: "FALSE", - testErr: testErr, - wrapErr: Wrap(wrapCode, wrapText, New(testCode, testText)), - want: false, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := Is(test.wrapErr, test.testErr); got != test.want { - t.Errorf("errIs() got: %v | want: %v", got, test.want) - } - }) - } -} - -func Test_errNew(t *testing.T) { - t.Parallel() - - tests := [1]struct { - name string - code string - text string - want *ErrWrapper - }{ - { - name: "Equal", - code: testCode, - text: testText, - want: &ErrWrapper{code: testCode, text: testText}, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := New(test.code, test.text); !reflect.DeepEqual(got, test.want) { - t.Errorf("errNew() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_errWrap(t *testing.T) { - t.Parallel() - - tests := [2]struct { - name string - code string - text string - wrap error - want string - }{ - { - name: "OK", - code: wrapCode, - text: wrapText, - wrap: New(testCode, testText), - want: wrapCode + delim + wrapText + delim + testCode + delim + testText, - }, - { - name: "nil_Wrap_OK", - code: wrapCode, - text: wrapText, - wrap: nil, - want: wrapCode + delim + wrapText, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := Wrap(test.code, test.text, test.wrap).Error(); got != test.want { - t.Errorf("errWrap() got: %#v | want: %#v", got, test.want) - } - }) - } -} diff --git a/zcnbridge/ethereum/authorizers/authorizers.go b/zcnbridge/ethereum/authorizers/authorizers.go deleted file mode 100644 index 600816d4d..000000000 --- a/zcnbridge/ethereum/authorizers/authorizers.go +++ /dev/null @@ -1,639 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package authorizers - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// AuthorizersMetaData contains all meta data concerning the Authorizers contract. -var AuthorizersMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"authorizerCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"authorizers\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"isAuthorizer\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"minThreshold\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"message_\",\"type\":\"bytes32\"},{\"internalType\":\"bytes[]\",\"name\":\"signatures_\",\"type\":\"bytes[]\"}],\"name\":\"authorize\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to_\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount_\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"txid_\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"nonce_\",\"type\":\"uint256\"}],\"name\":\"messageHash\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"authorizer_\",\"type\":\"address\"}],\"name\":\"addAuthorizers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"authorizer_\",\"type\":\"address\"}],\"name\":\"removeAuthorizers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Bin: "0x6080604052600060025534801561001557600080fd5b5061001f33610024565b610074565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b610f33806100836000396000f3fe608060405234801561001057600080fd5b506004361061009e5760003560e01c80638da5cb5b116100665780638da5cb5b1461012e578063c85501bb14610149578063e304688f14610151578063f2fde38b14610174578063f36bf4011461018757600080fd5b806309c7a20f146100a35780630b249ae4146100e757806343ab2c9e14610108578063715018a61461011d5780637ac3d68d14610125575b600080fd5b6100cd6100b1366004610c17565b6001602081905260009182526040909120805491015460ff1682565b604080519283529015156020830152015b60405180910390f35b6100fa6100f5366004610c39565b61019a565b6040519081526020016100de565b61011b610116366004610c17565b6101dd565b005b61011b6103bd565b6100fa60025481565b6000546040516001600160a01b0390911681526020016100de565b6100fa6103d1565b61016461015f366004610cc8565b61040a565b60405190151581526020016100de565b61011b610182366004610c17565b6106f6565b61011b610195366004610c17565b61076c565b60006101d386868686866040516020016101b8959493929190610d47565b60405160208183030381529060405280519060200120610887565b9695505050505050565b6101e56108da565b6001600160a01b0381166102145760405162461bcd60e51b815260040161020b90610d7b565b60405180910390fd5b6001600160a01b0381166000908152600160208190526040909120015460ff161561029a5760405162461bcd60e51b815260206004820152603060248201527f417574686f72697a657220776974682074686520676976656e2061646472657360448201526f7320616c72656164792065786973747360801b606482015260840161020b565b6003541561035b576040518060400160405280600360016003805490506102c19190610dd5565b815481106102d1576102d1610dec565b600091825260208083209190910154835260019281018390526001600160a01b03851682528281526040909120835181559201519101805460ff1916911515919091179055600380548061032757610327610e02565b600190038181906000526020600020016000905590556001600260008282546103509190610e18565b909155506103ba9050565b604080518082018252600280548252600160208084018281526001600160a01b038716600090815291839052948120935184559351928101805460ff1916931515939093179092558054919290916103b4908490610e18565b90915550505b50565b6103c56108da565b6103cf6000610934565b565b60006003600160025460026103e69190610e30565b6103f09190610dd5565b6103fa9190610e4f565b610405906001610e18565b905090565b6000806002541161046b5760405162461bcd60e51b815260206004820152602560248201527f4e6f20617574686f72697a657220686173206265656e2072656769737465726560448201526419081e595d60da1b606482015260840161020b565b6104736103d1565b8210156104cd5760405162461bcd60e51b815260206004820152602260248201527f416d6f756e74206f66207369676e617475726573206973206e6f7420656e6f756044820152610ced60f31b606482015260840161020b565b600060025467ffffffffffffffff8111156104ea576104ea610e71565b604051908082528060200260200182016040528015610513578160200160208202803683370190505b50905060005b838110156106ea57600061059086868481811061053857610538610dec565b905060200281019061054a9190610e87565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061058a92508b91506108879050565b90610984565b6001600160a01b0381166000908152600160208190526040909120015490915060ff166105ff5760405162461bcd60e51b815260206004820152601f60248201527f476976656e206d657373616765206973206e6f7420617574686f72697a656400604482015260640161020b565b6001600160a01b0381166000908152600160205260409020548351849190811061062b5761062b610dec565b6020026020010151156106985760405162461bcd60e51b815260206004820152602f60248201527f476976656e207369676e61747572657320636f6e7461696e206475706c69636160448201526e74656420617574686f72697a65727360881b606482015260840161020b565b6001600160a01b038116600090815260016020819052604090912054845185919081106106c7576106c7610dec565b9115156020928302919091019091015250806106e281610ece565b915050610519565b50600195945050505050565b6106fe6108da565b6001600160a01b0381166107635760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161020b565b6103ba81610934565b6107746108da565b6001600160a01b03811661079a5760405162461bcd60e51b815260040161020b90610d7b565b6001600160a01b0381166000908152600160208190526040909120015460ff1661081f5760405162461bcd60e51b815260206004820152603060248201527f417574686f72697a657220776974682074686520676976656e2061646472657360448201526f1cc8191bd95cc81b9bdd08195e1a5cdd60821b606482015260840161020b565b6001600160a01b03811660009081526001602081905260408220808201805460ff19169055546003805480840182559084527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b015560028054919290916103b4908490610dd5565b6040517f19457468657265756d205369676e6564204d6573736167653a0a3332000000006020820152603c8101829052600090605c01604051602081830303815290604052805190602001209050919050565b6000546001600160a01b031633146103cf5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161020b565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b600080600061099385856109a8565b915091506109a0816109ed565b509392505050565b60008082516041036109de5760208301516040840151606085015160001a6109d287828585610b37565b945094505050506109e6565b506000905060025b9250929050565b6000816004811115610a0157610a01610ee7565b03610a095750565b6001816004811115610a1d57610a1d610ee7565b03610a6a5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604482015260640161020b565b6002816004811115610a7e57610a7e610ee7565b03610acb5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604482015260640161020b565b6003816004811115610adf57610adf610ee7565b036103ba5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b606482015260840161020b565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115610b6e5750600090506003610bf2565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015610bc2573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116610beb57600060019250925050610bf2565b9150600090505b94509492505050565b80356001600160a01b0381168114610c1257600080fd5b919050565b600060208284031215610c2957600080fd5b610c3282610bfb565b9392505050565b600080600080600060808688031215610c5157600080fd5b610c5a86610bfb565b945060208601359350604086013567ffffffffffffffff80821115610c7e57600080fd5b818801915088601f830112610c9257600080fd5b813581811115610ca157600080fd5b896020828501011115610cb357600080fd5b96999598505060200195606001359392505050565b600080600060408486031215610cdd57600080fd5b83359250602084013567ffffffffffffffff80821115610cfc57600080fd5b818601915086601f830112610d1057600080fd5b813581811115610d1f57600080fd5b8760208260051b8501011115610d3457600080fd5b6020830194508093505050509250925092565b6bffffffffffffffffffffffff198660601b1681528460148201528284603483013760349201918201526054019392505050565b60208082526024908201527f496e76616c696420617574686f72697a6572206164647265737320776173206760408201526334bb32b760e11b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b600082821015610de757610de7610dbf565b500390565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60008219821115610e2b57610e2b610dbf565b500190565b6000816000190483118215151615610e4a57610e4a610dbf565b500290565b600082610e6c57634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052604160045260246000fd5b6000808335601e19843603018112610e9e57600080fd5b83018035915067ffffffffffffffff821115610eb957600080fd5b6020019150368190038213156109e657600080fd5b600060018201610ee057610ee0610dbf565b5060010190565b634e487b7160e01b600052602160045260246000fdfea2646970667358221220d36512e87ac563a1b5880c9eb0c665cc8b3875c8c66d26ea6aa50ec191d4719364736f6c634300080f0033", -} - -// AuthorizersABI is the input ABI used to generate the binding from. -// Deprecated: Use AuthorizersMetaData.ABI instead. -var AuthorizersABI = AuthorizersMetaData.ABI - -// AuthorizersBin is the compiled bytecode used for deploying new contracts. -// Deprecated: Use AuthorizersMetaData.Bin instead. -var AuthorizersBin = AuthorizersMetaData.Bin - -// DeployAuthorizers deploys a new Ethereum contract, binding an instance of Authorizers to it. -func DeployAuthorizers(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *Authorizers, error) { - parsed, err := AuthorizersMetaData.GetAbi() - if err != nil { - return common.Address{}, nil, nil, err - } - if parsed == nil { - return common.Address{}, nil, nil, errors.New("GetABI returned nil") - } - - address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(AuthorizersBin), backend) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &Authorizers{AuthorizersCaller: AuthorizersCaller{contract: contract}, AuthorizersTransactor: AuthorizersTransactor{contract: contract}, AuthorizersFilterer: AuthorizersFilterer{contract: contract}}, nil -} - -// Authorizers is an auto generated Go binding around an Ethereum contract. -type Authorizers struct { - AuthorizersCaller // Read-only binding to the contract - AuthorizersTransactor // Write-only binding to the contract - AuthorizersFilterer // Log filterer for contract events -} - -// AuthorizersCaller is an auto generated read-only Go binding around an Ethereum contract. -type AuthorizersCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// AuthorizersTransactor is an auto generated write-only Go binding around an Ethereum contract. -type AuthorizersTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// AuthorizersFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type AuthorizersFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// AuthorizersSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type AuthorizersSession struct { - Contract *Authorizers // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// AuthorizersCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type AuthorizersCallerSession struct { - Contract *AuthorizersCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// AuthorizersTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type AuthorizersTransactorSession struct { - Contract *AuthorizersTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// AuthorizersRaw is an auto generated low-level Go binding around an Ethereum contract. -type AuthorizersRaw struct { - Contract *Authorizers // Generic contract binding to access the raw methods on -} - -// AuthorizersCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type AuthorizersCallerRaw struct { - Contract *AuthorizersCaller // Generic read-only contract binding to access the raw methods on -} - -// AuthorizersTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type AuthorizersTransactorRaw struct { - Contract *AuthorizersTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewAuthorizers creates a new instance of Authorizers, bound to a specific deployed contract. -func NewAuthorizers(address common.Address, backend bind.ContractBackend) (*Authorizers, error) { - contract, err := bindAuthorizers(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Authorizers{AuthorizersCaller: AuthorizersCaller{contract: contract}, AuthorizersTransactor: AuthorizersTransactor{contract: contract}, AuthorizersFilterer: AuthorizersFilterer{contract: contract}}, nil -} - -// NewAuthorizersCaller creates a new read-only instance of Authorizers, bound to a specific deployed contract. -func NewAuthorizersCaller(address common.Address, caller bind.ContractCaller) (*AuthorizersCaller, error) { - contract, err := bindAuthorizers(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &AuthorizersCaller{contract: contract}, nil -} - -// NewAuthorizersTransactor creates a new write-only instance of Authorizers, bound to a specific deployed contract. -func NewAuthorizersTransactor(address common.Address, transactor bind.ContractTransactor) (*AuthorizersTransactor, error) { - contract, err := bindAuthorizers(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &AuthorizersTransactor{contract: contract}, nil -} - -// NewAuthorizersFilterer creates a new log filterer instance of Authorizers, bound to a specific deployed contract. -func NewAuthorizersFilterer(address common.Address, filterer bind.ContractFilterer) (*AuthorizersFilterer, error) { - contract, err := bindAuthorizers(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &AuthorizersFilterer{contract: contract}, nil -} - -// bindAuthorizers binds a generic wrapper to an already deployed contract. -func bindAuthorizers(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(AuthorizersABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Authorizers *AuthorizersRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Authorizers.Contract.AuthorizersCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Authorizers *AuthorizersRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Authorizers.Contract.AuthorizersTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Authorizers *AuthorizersRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Authorizers.Contract.AuthorizersTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Authorizers *AuthorizersCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Authorizers.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Authorizers *AuthorizersTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Authorizers.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Authorizers *AuthorizersTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Authorizers.Contract.contract.Transact(opts, method, params...) -} - -// Authorize is a free data retrieval call binding the contract method 0xe304688f. -// -// Solidity: function authorize(bytes32 message_, bytes[] signatures_) view returns(bool) -func (_Authorizers *AuthorizersCaller) Authorize(opts *bind.CallOpts, message_ [32]byte, signatures_ [][]byte) (bool, error) { - var out []interface{} - err := _Authorizers.contract.Call(opts, &out, "authorize", message_, signatures_) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Authorize is a free data retrieval call binding the contract method 0xe304688f. -// -// Solidity: function authorize(bytes32 message_, bytes[] signatures_) view returns(bool) -func (_Authorizers *AuthorizersSession) Authorize(message_ [32]byte, signatures_ [][]byte) (bool, error) { - return _Authorizers.Contract.Authorize(&_Authorizers.CallOpts, message_, signatures_) -} - -// Authorize is a free data retrieval call binding the contract method 0xe304688f. -// -// Solidity: function authorize(bytes32 message_, bytes[] signatures_) view returns(bool) -func (_Authorizers *AuthorizersCallerSession) Authorize(message_ [32]byte, signatures_ [][]byte) (bool, error) { - return _Authorizers.Contract.Authorize(&_Authorizers.CallOpts, message_, signatures_) -} - -// AuthorizerCount is a free data retrieval call binding the contract method 0x7ac3d68d. -// -// Solidity: function authorizerCount() view returns(uint256) -func (_Authorizers *AuthorizersCaller) AuthorizerCount(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Authorizers.contract.Call(opts, &out, "authorizerCount") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// AuthorizerCount is a free data retrieval call binding the contract method 0x7ac3d68d. -// -// Solidity: function authorizerCount() view returns(uint256) -func (_Authorizers *AuthorizersSession) AuthorizerCount() (*big.Int, error) { - return _Authorizers.Contract.AuthorizerCount(&_Authorizers.CallOpts) -} - -// AuthorizerCount is a free data retrieval call binding the contract method 0x7ac3d68d. -// -// Solidity: function authorizerCount() view returns(uint256) -func (_Authorizers *AuthorizersCallerSession) AuthorizerCount() (*big.Int, error) { - return _Authorizers.Contract.AuthorizerCount(&_Authorizers.CallOpts) -} - -// Authorizers is a free data retrieval call binding the contract method 0x09c7a20f. -// -// Solidity: function authorizers(address ) view returns(uint256 index, bool isAuthorizer) -func (_Authorizers *AuthorizersCaller) Authorizers(opts *bind.CallOpts, arg0 common.Address) (struct { - Index *big.Int - IsAuthorizer bool -}, error) { - var out []interface{} - err := _Authorizers.contract.Call(opts, &out, "authorizers", arg0) - - outstruct := new(struct { - Index *big.Int - IsAuthorizer bool - }) - if err != nil { - return *outstruct, err - } - - outstruct.Index = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - outstruct.IsAuthorizer = *abi.ConvertType(out[1], new(bool)).(*bool) - - return *outstruct, err - -} - -// Authorizers is a free data retrieval call binding the contract method 0x09c7a20f. -// -// Solidity: function authorizers(address ) view returns(uint256 index, bool isAuthorizer) -func (_Authorizers *AuthorizersSession) Authorizers(arg0 common.Address) (struct { - Index *big.Int - IsAuthorizer bool -}, error) { - return _Authorizers.Contract.Authorizers(&_Authorizers.CallOpts, arg0) -} - -// Authorizers is a free data retrieval call binding the contract method 0x09c7a20f. -// -// Solidity: function authorizers(address ) view returns(uint256 index, bool isAuthorizer) -func (_Authorizers *AuthorizersCallerSession) Authorizers(arg0 common.Address) (struct { - Index *big.Int - IsAuthorizer bool -}, error) { - return _Authorizers.Contract.Authorizers(&_Authorizers.CallOpts, arg0) -} - -// MessageHash is a free data retrieval call binding the contract method 0x0b249ae4. -// -// Solidity: function messageHash(address to_, uint256 amount_, bytes txid_, uint256 nonce_) pure returns(bytes32) -func (_Authorizers *AuthorizersCaller) MessageHash(opts *bind.CallOpts, to_ common.Address, amount_ *big.Int, txid_ []byte, nonce_ *big.Int) ([32]byte, error) { - var out []interface{} - err := _Authorizers.contract.Call(opts, &out, "messageHash", to_, amount_, txid_, nonce_) - - if err != nil { - return *new([32]byte), err - } - - out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) - - return out0, err - -} - -// MessageHash is a free data retrieval call binding the contract method 0x0b249ae4. -// -// Solidity: function messageHash(address to_, uint256 amount_, bytes txid_, uint256 nonce_) pure returns(bytes32) -func (_Authorizers *AuthorizersSession) MessageHash(to_ common.Address, amount_ *big.Int, txid_ []byte, nonce_ *big.Int) ([32]byte, error) { - return _Authorizers.Contract.MessageHash(&_Authorizers.CallOpts, to_, amount_, txid_, nonce_) -} - -// MessageHash is a free data retrieval call binding the contract method 0x0b249ae4. -// -// Solidity: function messageHash(address to_, uint256 amount_, bytes txid_, uint256 nonce_) pure returns(bytes32) -func (_Authorizers *AuthorizersCallerSession) MessageHash(to_ common.Address, amount_ *big.Int, txid_ []byte, nonce_ *big.Int) ([32]byte, error) { - return _Authorizers.Contract.MessageHash(&_Authorizers.CallOpts, to_, amount_, txid_, nonce_) -} - -// MinThreshold is a free data retrieval call binding the contract method 0xc85501bb. -// -// Solidity: function minThreshold() view returns(uint256) -func (_Authorizers *AuthorizersCaller) MinThreshold(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Authorizers.contract.Call(opts, &out, "minThreshold") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// MinThreshold is a free data retrieval call binding the contract method 0xc85501bb. -// -// Solidity: function minThreshold() view returns(uint256) -func (_Authorizers *AuthorizersSession) MinThreshold() (*big.Int, error) { - return _Authorizers.Contract.MinThreshold(&_Authorizers.CallOpts) -} - -// MinThreshold is a free data retrieval call binding the contract method 0xc85501bb. -// -// Solidity: function minThreshold() view returns(uint256) -func (_Authorizers *AuthorizersCallerSession) MinThreshold() (*big.Int, error) { - return _Authorizers.Contract.MinThreshold(&_Authorizers.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Authorizers *AuthorizersCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Authorizers.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Authorizers *AuthorizersSession) Owner() (common.Address, error) { - return _Authorizers.Contract.Owner(&_Authorizers.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Authorizers *AuthorizersCallerSession) Owner() (common.Address, error) { - return _Authorizers.Contract.Owner(&_Authorizers.CallOpts) -} - -// AddAuthorizers is a paid mutator transaction binding the contract method 0x43ab2c9e. -// -// Solidity: function addAuthorizers(address authorizer_) returns() -func (_Authorizers *AuthorizersTransactor) AddAuthorizers(opts *bind.TransactOpts, authorizer_ common.Address) (*types.Transaction, error) { - return _Authorizers.contract.Transact(opts, "addAuthorizers", authorizer_) -} - -// AddAuthorizers is a paid mutator transaction binding the contract method 0x43ab2c9e. -// -// Solidity: function addAuthorizers(address authorizer_) returns() -func (_Authorizers *AuthorizersSession) AddAuthorizers(authorizer_ common.Address) (*types.Transaction, error) { - return _Authorizers.Contract.AddAuthorizers(&_Authorizers.TransactOpts, authorizer_) -} - -// AddAuthorizers is a paid mutator transaction binding the contract method 0x43ab2c9e. -// -// Solidity: function addAuthorizers(address authorizer_) returns() -func (_Authorizers *AuthorizersTransactorSession) AddAuthorizers(authorizer_ common.Address) (*types.Transaction, error) { - return _Authorizers.Contract.AddAuthorizers(&_Authorizers.TransactOpts, authorizer_) -} - -// RemoveAuthorizers is a paid mutator transaction binding the contract method 0xf36bf401. -// -// Solidity: function removeAuthorizers(address authorizer_) returns() -func (_Authorizers *AuthorizersTransactor) RemoveAuthorizers(opts *bind.TransactOpts, authorizer_ common.Address) (*types.Transaction, error) { - return _Authorizers.contract.Transact(opts, "removeAuthorizers", authorizer_) -} - -// RemoveAuthorizers is a paid mutator transaction binding the contract method 0xf36bf401. -// -// Solidity: function removeAuthorizers(address authorizer_) returns() -func (_Authorizers *AuthorizersSession) RemoveAuthorizers(authorizer_ common.Address) (*types.Transaction, error) { - return _Authorizers.Contract.RemoveAuthorizers(&_Authorizers.TransactOpts, authorizer_) -} - -// RemoveAuthorizers is a paid mutator transaction binding the contract method 0xf36bf401. -// -// Solidity: function removeAuthorizers(address authorizer_) returns() -func (_Authorizers *AuthorizersTransactorSession) RemoveAuthorizers(authorizer_ common.Address) (*types.Transaction, error) { - return _Authorizers.Contract.RemoveAuthorizers(&_Authorizers.TransactOpts, authorizer_) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Authorizers *AuthorizersTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Authorizers.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Authorizers *AuthorizersSession) RenounceOwnership() (*types.Transaction, error) { - return _Authorizers.Contract.RenounceOwnership(&_Authorizers.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Authorizers *AuthorizersTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Authorizers.Contract.RenounceOwnership(&_Authorizers.TransactOpts) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Authorizers *AuthorizersTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Authorizers.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Authorizers *AuthorizersSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Authorizers.Contract.TransferOwnership(&_Authorizers.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Authorizers *AuthorizersTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Authorizers.Contract.TransferOwnership(&_Authorizers.TransactOpts, newOwner) -} - -// AuthorizersOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Authorizers contract. -type AuthorizersOwnershipTransferredIterator struct { - Event *AuthorizersOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *AuthorizersOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(AuthorizersOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(AuthorizersOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *AuthorizersOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *AuthorizersOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// AuthorizersOwnershipTransferred represents a OwnershipTransferred event raised by the Authorizers contract. -type AuthorizersOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Authorizers *AuthorizersFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*AuthorizersOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Authorizers.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &AuthorizersOwnershipTransferredIterator{contract: _Authorizers.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Authorizers *AuthorizersFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *AuthorizersOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Authorizers.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(AuthorizersOwnershipTransferred) - if err := _Authorizers.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Authorizers *AuthorizersFilterer) ParseOwnershipTransferred(log types.Log) (*AuthorizersOwnershipTransferred, error) { - event := new(AuthorizersOwnershipTransferred) - if err := _Authorizers.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/ethereum/bridge/bridge.go b/zcnbridge/ethereum/bridge/bridge.go deleted file mode 100644 index 1e02f0404..000000000 --- a/zcnbridge/ethereum/bridge/bridge.go +++ /dev/null @@ -1,1032 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package bridge - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BridgeMetaData contains all meta data concerning the Bridge contract. -var BridgeMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"contractIERC20\",\"name\":\"token_\",\"type\":\"address\"},{\"internalType\":\"contractIAuthorizers\",\"name\":\"authorizers_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"clientId\",\"type\":\"bytes\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"}],\"name\":\"Burned\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"bytes\",\"name\":\"clientId\",\"type\":\"bytes\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"}],\"name\":\"BurnedFullIndex\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"txid\",\"type\":\"bytes\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"}],\"name\":\"Minted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"userNonceMinted\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to_\",\"type\":\"address\"}],\"name\":\"getUserNonceMinted\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"resetUserNonceMinted\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount_\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"clientId_\",\"type\":\"bytes\"}],\"name\":\"burn\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to_\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount_\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"txid_\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"nonce_\",\"type\":\"uint256\"},{\"internalType\":\"bytes[]\",\"name\":\"signatures_\",\"type\":\"bytes[]\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Bin: "0x60806040526000600455600060055534801561001a57600080fd5b50604051610e2e380380610e2e833981016040819052610039916100e6565b806100433361007e565b600180546001600160a01b039283166001600160a01b0319918216178255600291909155600380549490921693169290921790915550610120565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b03811681146100e357600080fd5b50565b600080604083850312156100f957600080fd5b8251610104816100ce565b6020840151909250610115816100ce565b809150509250929050565b610cff8061012f6000396000f3fe608060405234801561001057600080fd5b50600436106100885760003560e01c80639e2aa15c1161005b5780639e2aa15c146100f8578063e563e52614610100578063f2fde38b14610129578063fe9d93031461013c57600080fd5b8063062f950e1461008d57806356f6dd62146100c0578063715018a6146100d55780638da5cb5b146100dd575b600080fd5b6100ad61009b36600461093f565b60076020526000908152604090205481565b6040519081526020015b60405180910390f35b6100d36100ce3660046109aa565b61014f565b005b6100d36102ee565b6000546040516001600160a01b0390911681526020016100b7565b6100d3610302565b6100ad61010e36600461093f565b6001600160a01b031660009081526007602052604090205490565b6100d361013736600461093f565b610350565b6100d361014a366004610a6e565b6103c6565b6001600160a01b038716600090815260076020526040902054879084908190610179906001610ad0565b146101f15760405162461bcd60e51b815260206004820152603e60248201527f50726f7669646564206e6f6e6365206d7573742062652031206772656174657260448201527f207468616e207468652070726576696f7573206275726e206e6f6e63652e000060648201526084015b60405180910390fd5b600060405180608001604052808b6001600160a01b031681526020018a815260200189898080601f016020809104026020016040519081016040528093929190818152602001838380828437600092018290525093855250505060209091018890526001546040516302c926b960e21b815292935090916001600160a01b0390911690630b249ae490610290908e908e908e908e908e90600401610b11565b6020604051808303816000875af11580156102af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102d39190610b4b565b90506102e18282888861040c565b5050505050505050505050565b6102f6610684565b61030060006106de565b565b61030a610684565b60005b600554811161034d576000818152600660209081526040808320546001600160a01b0316835260079091528120558061034581610b64565b91505061030d565b50565b610358610684565b6001600160a01b0381166103bd5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016101e8565b61034d816106de565b610407338484848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061072e92505050565b505050565b6104146108cc565b60015460405163e304688f60e01b81528491849184916001600160a01b03169063e304688f9061044c90869086908690600401610b7d565b6020604051808303816000875af115801561046b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061048f9190610c25565b6104e75760405162461bcd60e51b815260206004820152602360248201527f476976656e207369676e61747572657320617265206e6f7420617574686f72696044820152621e995960ea1b60648201526084016101e8565b6003548751602089015160405163a9059cbb60e01b81526001600160a01b039283166004820152602481019190915291169063a9059cbb906044016020604051808303816000875af1158015610541573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105659190610c25565b6105bd5760405162461bcd60e51b815260206004820152602360248201527f4272696467653a207472616e73666572206f7574206f6620706f6f6c206661696044820152621b195960ea1b60648201526084016101e8565b606087015187516001600160a01b039081166000908152600760209081526040808320949094558a51600580548452600690925293822080546001600160a01b03191694909316939093179091558154919061061883610b64565b9190505550866060015187600001516001600160a01b03167fe04478a4154dc31a079fa36b9ee1af057f492a47c1524ac67f2ea4c214c3de9289602001518a60400151604051610669929190610c73565b60405180910390a350505061067e6001600255565b50505050565b6000546001600160a01b031633146103005760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016101e8565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6107366108cc565b6003546040516323b872dd60e01b81526001600160a01b03858116600483015230602483015260448201859052909116906323b872dd906064016020604051808303816000875af115801561078f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107b39190610c25565b61080e5760405162461bcd60e51b815260206004820152602660248201527f4272696467653a207472616e7366657220696e746f206275726e20706f6f6c2060448201526519985a5b195960d21b60648201526084016101e8565b60045461081c906001610ad0565b60048190556040516001600160a01b038516907f2b1155a5de2441854f3781130b980daa499b3412053ee40fcde076774bb12df29061085e9086908690610c73565b60405180910390a3600454816040516108779190610cad565b6040518091039020846001600160a01b03167ff92c63d6a65a604ac5f7ddd105b1934f80b49d81059edec60935b8f0b3ea29f3856040516108ba91815260200190565b60405180910390a46104076001600255565b600280540361091d5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016101e8565b60028055565b80356001600160a01b038116811461093a57600080fd5b919050565b60006020828403121561095157600080fd5b61095a82610923565b9392505050565b60008083601f84011261097357600080fd5b50813567ffffffffffffffff81111561098b57600080fd5b6020830191508360208285010111156109a357600080fd5b9250929050565b600080600080600080600060a0888a0312156109c557600080fd5b6109ce88610923565b965060208801359550604088013567ffffffffffffffff808211156109f257600080fd5b6109fe8b838c01610961565b909750955060608a0135945060808a0135915080821115610a1e57600080fd5b818a0191508a601f830112610a3257600080fd5b813581811115610a4157600080fd5b8b60208260051b8501011115610a5657600080fd5b60208301945080935050505092959891949750929550565b600080600060408486031215610a8357600080fd5b83359250602084013567ffffffffffffffff811115610aa157600080fd5b610aad86828701610961565b9497909650939450505050565b634e487b7160e01b600052601160045260246000fd5b60008219821115610ae357610ae3610aba565b500190565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60018060a01b0386168152846020820152608060408201526000610b39608083018587610ae8565b90508260608301529695505050505050565b600060208284031215610b5d57600080fd5b5051919050565b600060018201610b7657610b76610aba565b5060010190565b60006040820185835260206040818501528185835260608501905060608660051b86010192508660005b87811015610c1757868503605f190183528135368a9003601e19018112610bcd57600080fd5b8901848101903567ffffffffffffffff811115610be957600080fd5b803603821315610bf857600080fd5b610c03878284610ae8565b965050509183019190830190600101610ba7565b509298975050505050505050565b600060208284031215610c3757600080fd5b8151801515811461095a57600080fd5b60005b83811015610c62578181015183820152602001610c4a565b8381111561067e5750506000910152565b8281526040602082015260008251806040840152610c98816060850160208701610c47565b601f01601f1916919091016060019392505050565b60008251610cbf818460208701610c47565b919091019291505056fea2646970667358221220593b31edb9b383d640436fd13816dc16719b624f004e4f16867b6170fd6a70a864736f6c634300080f0033", -} - -// BridgeABI is the input ABI used to generate the binding from. -// Deprecated: Use BridgeMetaData.ABI instead. -var BridgeABI = BridgeMetaData.ABI - -// BridgeBin is the compiled bytecode used for deploying new contracts. -// Deprecated: Use BridgeMetaData.Bin instead. -var BridgeBin = BridgeMetaData.Bin - -// DeployBridge deploys a new Ethereum contract, binding an instance of Bridge to it. -func DeployBridge(auth *bind.TransactOpts, backend bind.ContractBackend, token_ common.Address, authorizers_ common.Address) (common.Address, *types.Transaction, *Bridge, error) { - parsed, err := BridgeMetaData.GetAbi() - if err != nil { - return common.Address{}, nil, nil, err - } - if parsed == nil { - return common.Address{}, nil, nil, errors.New("GetABI returned nil") - } - - address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(BridgeBin), backend, token_, authorizers_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &Bridge{BridgeCaller: BridgeCaller{contract: contract}, BridgeTransactor: BridgeTransactor{contract: contract}, BridgeFilterer: BridgeFilterer{contract: contract}}, nil -} - -// Bridge is an auto generated Go binding around an Ethereum contract. -type Bridge struct { - BridgeCaller // Read-only binding to the contract - BridgeTransactor // Write-only binding to the contract - BridgeFilterer // Log filterer for contract events -} - -// BridgeCaller is an auto generated read-only Go binding around an Ethereum contract. -type BridgeCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BridgeTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BridgeTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BridgeFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BridgeFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BridgeSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BridgeSession struct { - Contract *Bridge // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BridgeCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BridgeCallerSession struct { - Contract *BridgeCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BridgeTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BridgeTransactorSession struct { - Contract *BridgeTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BridgeRaw is an auto generated low-level Go binding around an Ethereum contract. -type BridgeRaw struct { - Contract *Bridge // Generic contract binding to access the raw methods on -} - -// BridgeCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BridgeCallerRaw struct { - Contract *BridgeCaller // Generic read-only contract binding to access the raw methods on -} - -// BridgeTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BridgeTransactorRaw struct { - Contract *BridgeTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBridge creates a new instance of Bridge, bound to a specific deployed contract. -func NewBridge(address common.Address, backend bind.ContractBackend) (*Bridge, error) { - contract, err := bindBridge(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Bridge{BridgeCaller: BridgeCaller{contract: contract}, BridgeTransactor: BridgeTransactor{contract: contract}, BridgeFilterer: BridgeFilterer{contract: contract}}, nil -} - -// NewBridgeCaller creates a new read-only instance of Bridge, bound to a specific deployed contract. -func NewBridgeCaller(address common.Address, caller bind.ContractCaller) (*BridgeCaller, error) { - contract, err := bindBridge(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BridgeCaller{contract: contract}, nil -} - -// NewBridgeTransactor creates a new write-only instance of Bridge, bound to a specific deployed contract. -func NewBridgeTransactor(address common.Address, transactor bind.ContractTransactor) (*BridgeTransactor, error) { - contract, err := bindBridge(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BridgeTransactor{contract: contract}, nil -} - -// NewBridgeFilterer creates a new log filterer instance of Bridge, bound to a specific deployed contract. -func NewBridgeFilterer(address common.Address, filterer bind.ContractFilterer) (*BridgeFilterer, error) { - contract, err := bindBridge(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BridgeFilterer{contract: contract}, nil -} - -// bindBridge binds a generic wrapper to an already deployed contract. -func bindBridge(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BridgeABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Bridge *BridgeRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Bridge.Contract.BridgeCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Bridge *BridgeRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Bridge.Contract.BridgeTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Bridge *BridgeRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Bridge.Contract.BridgeTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Bridge *BridgeCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Bridge.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Bridge *BridgeTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Bridge.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Bridge *BridgeTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Bridge.Contract.contract.Transact(opts, method, params...) -} - -// GetUserNonceMinted is a free data retrieval call binding the contract method 0xe563e526. -// -// Solidity: function getUserNonceMinted(address to_) view returns(uint256) -func (_Bridge *BridgeCaller) GetUserNonceMinted(opts *bind.CallOpts, to_ common.Address) (*big.Int, error) { - var out []interface{} - err := _Bridge.contract.Call(opts, &out, "getUserNonceMinted", to_) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// GetUserNonceMinted is a free data retrieval call binding the contract method 0xe563e526. -// -// Solidity: function getUserNonceMinted(address to_) view returns(uint256) -func (_Bridge *BridgeSession) GetUserNonceMinted(to_ common.Address) (*big.Int, error) { - return _Bridge.Contract.GetUserNonceMinted(&_Bridge.CallOpts, to_) -} - -// GetUserNonceMinted is a free data retrieval call binding the contract method 0xe563e526. -// -// Solidity: function getUserNonceMinted(address to_) view returns(uint256) -func (_Bridge *BridgeCallerSession) GetUserNonceMinted(to_ common.Address) (*big.Int, error) { - return _Bridge.Contract.GetUserNonceMinted(&_Bridge.CallOpts, to_) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Bridge *BridgeCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Bridge.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Bridge *BridgeSession) Owner() (common.Address, error) { - return _Bridge.Contract.Owner(&_Bridge.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Bridge *BridgeCallerSession) Owner() (common.Address, error) { - return _Bridge.Contract.Owner(&_Bridge.CallOpts) -} - -// UserNonceMinted is a free data retrieval call binding the contract method 0x062f950e. -// -// Solidity: function userNonceMinted(address ) view returns(uint256) -func (_Bridge *BridgeCaller) UserNonceMinted(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _Bridge.contract.Call(opts, &out, "userNonceMinted", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// UserNonceMinted is a free data retrieval call binding the contract method 0x062f950e. -// -// Solidity: function userNonceMinted(address ) view returns(uint256) -func (_Bridge *BridgeSession) UserNonceMinted(arg0 common.Address) (*big.Int, error) { - return _Bridge.Contract.UserNonceMinted(&_Bridge.CallOpts, arg0) -} - -// UserNonceMinted is a free data retrieval call binding the contract method 0x062f950e. -// -// Solidity: function userNonceMinted(address ) view returns(uint256) -func (_Bridge *BridgeCallerSession) UserNonceMinted(arg0 common.Address) (*big.Int, error) { - return _Bridge.Contract.UserNonceMinted(&_Bridge.CallOpts, arg0) -} - -// Burn is a paid mutator transaction binding the contract method 0xfe9d9303. -// -// Solidity: function burn(uint256 amount_, bytes clientId_) returns() -func (_Bridge *BridgeTransactor) Burn(opts *bind.TransactOpts, amount_ *big.Int, clientId_ []byte) (*types.Transaction, error) { - return _Bridge.contract.Transact(opts, "burn", amount_, clientId_) -} - -// Burn is a paid mutator transaction binding the contract method 0xfe9d9303. -// -// Solidity: function burn(uint256 amount_, bytes clientId_) returns() -func (_Bridge *BridgeSession) Burn(amount_ *big.Int, clientId_ []byte) (*types.Transaction, error) { - return _Bridge.Contract.Burn(&_Bridge.TransactOpts, amount_, clientId_) -} - -// Burn is a paid mutator transaction binding the contract method 0xfe9d9303. -// -// Solidity: function burn(uint256 amount_, bytes clientId_) returns() -func (_Bridge *BridgeTransactorSession) Burn(amount_ *big.Int, clientId_ []byte) (*types.Transaction, error) { - return _Bridge.Contract.Burn(&_Bridge.TransactOpts, amount_, clientId_) -} - -// Mint is a paid mutator transaction binding the contract method 0x56f6dd62. -// -// Solidity: function mint(address to_, uint256 amount_, bytes txid_, uint256 nonce_, bytes[] signatures_) returns() -func (_Bridge *BridgeTransactor) Mint(opts *bind.TransactOpts, to_ common.Address, amount_ *big.Int, txid_ []byte, nonce_ *big.Int, signatures_ [][]byte) (*types.Transaction, error) { - return _Bridge.contract.Transact(opts, "mint", to_, amount_, txid_, nonce_, signatures_) -} - -// Mint is a paid mutator transaction binding the contract method 0x56f6dd62. -// -// Solidity: function mint(address to_, uint256 amount_, bytes txid_, uint256 nonce_, bytes[] signatures_) returns() -func (_Bridge *BridgeSession) Mint(to_ common.Address, amount_ *big.Int, txid_ []byte, nonce_ *big.Int, signatures_ [][]byte) (*types.Transaction, error) { - return _Bridge.Contract.Mint(&_Bridge.TransactOpts, to_, amount_, txid_, nonce_, signatures_) -} - -// Mint is a paid mutator transaction binding the contract method 0x56f6dd62. -// -// Solidity: function mint(address to_, uint256 amount_, bytes txid_, uint256 nonce_, bytes[] signatures_) returns() -func (_Bridge *BridgeTransactorSession) Mint(to_ common.Address, amount_ *big.Int, txid_ []byte, nonce_ *big.Int, signatures_ [][]byte) (*types.Transaction, error) { - return _Bridge.Contract.Mint(&_Bridge.TransactOpts, to_, amount_, txid_, nonce_, signatures_) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Bridge *BridgeTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Bridge.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Bridge *BridgeSession) RenounceOwnership() (*types.Transaction, error) { - return _Bridge.Contract.RenounceOwnership(&_Bridge.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Bridge *BridgeTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Bridge.Contract.RenounceOwnership(&_Bridge.TransactOpts) -} - -// ResetUserNonceMinted is a paid mutator transaction binding the contract method 0x9e2aa15c. -// -// Solidity: function resetUserNonceMinted() returns() -func (_Bridge *BridgeTransactor) ResetUserNonceMinted(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Bridge.contract.Transact(opts, "resetUserNonceMinted") -} - -// ResetUserNonceMinted is a paid mutator transaction binding the contract method 0x9e2aa15c. -// -// Solidity: function resetUserNonceMinted() returns() -func (_Bridge *BridgeSession) ResetUserNonceMinted() (*types.Transaction, error) { - return _Bridge.Contract.ResetUserNonceMinted(&_Bridge.TransactOpts) -} - -// ResetUserNonceMinted is a paid mutator transaction binding the contract method 0x9e2aa15c. -// -// Solidity: function resetUserNonceMinted() returns() -func (_Bridge *BridgeTransactorSession) ResetUserNonceMinted() (*types.Transaction, error) { - return _Bridge.Contract.ResetUserNonceMinted(&_Bridge.TransactOpts) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Bridge *BridgeTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Bridge.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Bridge *BridgeSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Bridge.Contract.TransferOwnership(&_Bridge.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Bridge *BridgeTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Bridge.Contract.TransferOwnership(&_Bridge.TransactOpts, newOwner) -} - -// BridgeBurnedIterator is returned from FilterBurned and is used to iterate over the raw logs and unpacked data for Burned events raised by the Bridge contract. -type BridgeBurnedIterator struct { - Event *BridgeBurned // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BridgeBurnedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BridgeBurned) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BridgeBurned) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BridgeBurnedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BridgeBurnedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BridgeBurned represents a Burned event raised by the Bridge contract. -type BridgeBurned struct { - From common.Address - Amount *big.Int - ClientId []byte - Nonce *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterBurned is a free log retrieval operation binding the contract event 0x2b1155a5de2441854f3781130b980daa499b3412053ee40fcde076774bb12df2. -// -// Solidity: event Burned(address indexed from, uint256 amount, bytes clientId, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) FilterBurned(opts *bind.FilterOpts, from []common.Address, nonce []*big.Int) (*BridgeBurnedIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - - var nonceRule []interface{} - for _, nonceItem := range nonce { - nonceRule = append(nonceRule, nonceItem) - } - - logs, sub, err := _Bridge.contract.FilterLogs(opts, "Burned", fromRule, nonceRule) - if err != nil { - return nil, err - } - return &BridgeBurnedIterator{contract: _Bridge.contract, event: "Burned", logs: logs, sub: sub}, nil -} - -// WatchBurned is a free log subscription operation binding the contract event 0x2b1155a5de2441854f3781130b980daa499b3412053ee40fcde076774bb12df2. -// -// Solidity: event Burned(address indexed from, uint256 amount, bytes clientId, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) WatchBurned(opts *bind.WatchOpts, sink chan<- *BridgeBurned, from []common.Address, nonce []*big.Int) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - - var nonceRule []interface{} - for _, nonceItem := range nonce { - nonceRule = append(nonceRule, nonceItem) - } - - logs, sub, err := _Bridge.contract.WatchLogs(opts, "Burned", fromRule, nonceRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BridgeBurned) - if err := _Bridge.contract.UnpackLog(event, "Burned", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseBurned is a log parse operation binding the contract event 0x2b1155a5de2441854f3781130b980daa499b3412053ee40fcde076774bb12df2. -// -// Solidity: event Burned(address indexed from, uint256 amount, bytes clientId, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) ParseBurned(log types.Log) (*BridgeBurned, error) { - event := new(BridgeBurned) - if err := _Bridge.contract.UnpackLog(event, "Burned", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BridgeBurnedFullIndexIterator is returned from FilterBurnedFullIndex and is used to iterate over the raw logs and unpacked data for BurnedFullIndex events raised by the Bridge contract. -type BridgeBurnedFullIndexIterator struct { - Event *BridgeBurnedFullIndex // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BridgeBurnedFullIndexIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BridgeBurnedFullIndex) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BridgeBurnedFullIndex) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BridgeBurnedFullIndexIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BridgeBurnedFullIndexIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BridgeBurnedFullIndex represents a BurnedFullIndex event raised by the Bridge contract. -type BridgeBurnedFullIndex struct { - From common.Address - Amount *big.Int - ClientId common.Hash - Nonce *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterBurnedFullIndex is a free log retrieval operation binding the contract event 0xf92c63d6a65a604ac5f7ddd105b1934f80b49d81059edec60935b8f0b3ea29f3. -// -// Solidity: event BurnedFullIndex(address indexed from, uint256 amount, bytes indexed clientId, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) FilterBurnedFullIndex(opts *bind.FilterOpts, from []common.Address, clientId [][]byte, nonce []*big.Int) (*BridgeBurnedFullIndexIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - - var clientIdRule []interface{} - for _, clientIdItem := range clientId { - clientIdRule = append(clientIdRule, clientIdItem) - } - var nonceRule []interface{} - for _, nonceItem := range nonce { - nonceRule = append(nonceRule, nonceItem) - } - - logs, sub, err := _Bridge.contract.FilterLogs(opts, "BurnedFullIndex", fromRule, clientIdRule, nonceRule) - if err != nil { - return nil, err - } - return &BridgeBurnedFullIndexIterator{contract: _Bridge.contract, event: "BurnedFullIndex", logs: logs, sub: sub}, nil -} - -// WatchBurnedFullIndex is a free log subscription operation binding the contract event 0xf92c63d6a65a604ac5f7ddd105b1934f80b49d81059edec60935b8f0b3ea29f3. -// -// Solidity: event BurnedFullIndex(address indexed from, uint256 amount, bytes indexed clientId, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) WatchBurnedFullIndex(opts *bind.WatchOpts, sink chan<- *BridgeBurnedFullIndex, from []common.Address, clientId [][]byte, nonce []*big.Int) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - - var clientIdRule []interface{} - for _, clientIdItem := range clientId { - clientIdRule = append(clientIdRule, clientIdItem) - } - var nonceRule []interface{} - for _, nonceItem := range nonce { - nonceRule = append(nonceRule, nonceItem) - } - - logs, sub, err := _Bridge.contract.WatchLogs(opts, "BurnedFullIndex", fromRule, clientIdRule, nonceRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BridgeBurnedFullIndex) - if err := _Bridge.contract.UnpackLog(event, "BurnedFullIndex", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseBurnedFullIndex is a log parse operation binding the contract event 0xf92c63d6a65a604ac5f7ddd105b1934f80b49d81059edec60935b8f0b3ea29f3. -// -// Solidity: event BurnedFullIndex(address indexed from, uint256 amount, bytes indexed clientId, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) ParseBurnedFullIndex(log types.Log) (*BridgeBurnedFullIndex, error) { - event := new(BridgeBurnedFullIndex) - if err := _Bridge.contract.UnpackLog(event, "BurnedFullIndex", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BridgeMintedIterator is returned from FilterMinted and is used to iterate over the raw logs and unpacked data for Minted events raised by the Bridge contract. -type BridgeMintedIterator struct { - Event *BridgeMinted // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BridgeMintedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BridgeMinted) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BridgeMinted) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BridgeMintedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BridgeMintedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BridgeMinted represents a Minted event raised by the Bridge contract. -type BridgeMinted struct { - To common.Address - Amount *big.Int - Txid []byte - Nonce *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMinted is a free log retrieval operation binding the contract event 0xe04478a4154dc31a079fa36b9ee1af057f492a47c1524ac67f2ea4c214c3de92. -// -// Solidity: event Minted(address indexed to, uint256 amount, bytes txid, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) FilterMinted(opts *bind.FilterOpts, to []common.Address, nonce []*big.Int) (*BridgeMintedIterator, error) { - - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - var nonceRule []interface{} - for _, nonceItem := range nonce { - nonceRule = append(nonceRule, nonceItem) - } - - logs, sub, err := _Bridge.contract.FilterLogs(opts, "Minted", toRule, nonceRule) - if err != nil { - return nil, err - } - return &BridgeMintedIterator{contract: _Bridge.contract, event: "Minted", logs: logs, sub: sub}, nil -} - -// WatchMinted is a free log subscription operation binding the contract event 0xe04478a4154dc31a079fa36b9ee1af057f492a47c1524ac67f2ea4c214c3de92. -// -// Solidity: event Minted(address indexed to, uint256 amount, bytes txid, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) WatchMinted(opts *bind.WatchOpts, sink chan<- *BridgeMinted, to []common.Address, nonce []*big.Int) (event.Subscription, error) { - - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - var nonceRule []interface{} - for _, nonceItem := range nonce { - nonceRule = append(nonceRule, nonceItem) - } - - logs, sub, err := _Bridge.contract.WatchLogs(opts, "Minted", toRule, nonceRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BridgeMinted) - if err := _Bridge.contract.UnpackLog(event, "Minted", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMinted is a log parse operation binding the contract event 0xe04478a4154dc31a079fa36b9ee1af057f492a47c1524ac67f2ea4c214c3de92. -// -// Solidity: event Minted(address indexed to, uint256 amount, bytes txid, uint256 indexed nonce) -func (_Bridge *BridgeFilterer) ParseMinted(log types.Log) (*BridgeMinted, error) { - event := new(BridgeMinted) - if err := _Bridge.contract.UnpackLog(event, "Minted", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BridgeOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Bridge contract. -type BridgeOwnershipTransferredIterator struct { - Event *BridgeOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BridgeOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BridgeOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BridgeOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BridgeOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BridgeOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BridgeOwnershipTransferred represents a OwnershipTransferred event raised by the Bridge contract. -type BridgeOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Bridge *BridgeFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*BridgeOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Bridge.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &BridgeOwnershipTransferredIterator{contract: _Bridge.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Bridge *BridgeFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *BridgeOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Bridge.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BridgeOwnershipTransferred) - if err := _Bridge.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Bridge *BridgeFilterer) ParseOwnershipTransferred(log types.Log) (*BridgeOwnershipTransferred, error) { - event := new(BridgeOwnershipTransferred) - if err := _Bridge.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/ethereum/doc.go b/zcnbridge/ethereum/doc.go deleted file mode 100644 index 7e2f0203a..000000000 --- a/zcnbridge/ethereum/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// 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/ethereum/mint_payload.go b/zcnbridge/ethereum/mint_payload.go deleted file mode 100644 index 4ca566ff1..000000000 --- a/zcnbridge/ethereum/mint_payload.go +++ /dev/null @@ -1,29 +0,0 @@ -package ethereum - -import "encoding/json" - -// BurnEvent represents received WZCN burn event. -type BurnEvent struct { - Nonce int64 `json:"nonce"` - Amount int64 `json:"amount"` - TransactionHash string `json:"hash"` -} - -// MintPayload Payload to submit to the ethereum bridge contract -type MintPayload struct { - ZCNTxnID string `json:"zcn_txn_id"` - Amount int64 `json:"amount"` - To string `json:"to"` - Nonce int64 `json:"nonce"` - Signatures []*AuthorizerSignature `json:"signatures"` -} - -type AuthorizerSignature struct { - ID string `json:"authorizer_id"` - Signature []byte `json:"signature"` -} - -func (mp *MintPayload) Encode() []byte { - buff, _ := json.Marshal(mp) - return buff -} diff --git a/zcnbridge/ethereum/nftconfig/nftconfig.go b/zcnbridge/ethereum/nftconfig/nftconfig.go deleted file mode 100644 index 2961f9fce..000000000 --- a/zcnbridge/ethereum/nftconfig/nftconfig.go +++ /dev/null @@ -1,656 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package nftconfig - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// NFTConfigMetaData contains all meta data concerning the NFTConfig contract. -var NFTConfigMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"ConfigUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"setUint256\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"value\",\"type\":\"address\"}],\"name\":\"setAddress\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"}],\"name\":\"getUint256\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"}],\"name\":\"getAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true}]", -} - -// NFTConfigABI is the input ABI used to generate the binding from. -// Deprecated: Use NFTConfigMetaData.ABI instead. -var NFTConfigABI = NFTConfigMetaData.ABI - -// NFTConfig is an auto generated Go binding around an Ethereum contract. -type NFTConfig struct { - NFTConfigCaller // Read-only binding to the contract - NFTConfigTransactor // Write-only binding to the contract - NFTConfigFilterer // Log filterer for contract events -} - -// NFTConfigCaller is an auto generated read-only Go binding around an Ethereum contract. -type NFTConfigCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// NFTConfigTransactor is an auto generated write-only Go binding around an Ethereum contract. -type NFTConfigTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// NFTConfigFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type NFTConfigFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// NFTConfigSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type NFTConfigSession struct { - Contract *NFTConfig // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// NFTConfigCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type NFTConfigCallerSession struct { - Contract *NFTConfigCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// NFTConfigTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type NFTConfigTransactorSession struct { - Contract *NFTConfigTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// NFTConfigRaw is an auto generated low-level Go binding around an Ethereum contract. -type NFTConfigRaw struct { - Contract *NFTConfig // Generic contract binding to access the raw methods on -} - -// NFTConfigCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type NFTConfigCallerRaw struct { - Contract *NFTConfigCaller // Generic read-only contract binding to access the raw methods on -} - -// NFTConfigTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type NFTConfigTransactorRaw struct { - Contract *NFTConfigTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewNFTConfig creates a new instance of NFTConfig, bound to a specific deployed contract. -func NewNFTConfig(address common.Address, backend bind.ContractBackend) (*NFTConfig, error) { - contract, err := bindNFTConfig(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &NFTConfig{NFTConfigCaller: NFTConfigCaller{contract: contract}, NFTConfigTransactor: NFTConfigTransactor{contract: contract}, NFTConfigFilterer: NFTConfigFilterer{contract: contract}}, nil -} - -// NewNFTConfigCaller creates a new read-only instance of NFTConfig, bound to a specific deployed contract. -func NewNFTConfigCaller(address common.Address, caller bind.ContractCaller) (*NFTConfigCaller, error) { - contract, err := bindNFTConfig(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &NFTConfigCaller{contract: contract}, nil -} - -// NewNFTConfigTransactor creates a new write-only instance of NFTConfig, bound to a specific deployed contract. -func NewNFTConfigTransactor(address common.Address, transactor bind.ContractTransactor) (*NFTConfigTransactor, error) { - contract, err := bindNFTConfig(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &NFTConfigTransactor{contract: contract}, nil -} - -// NewNFTConfigFilterer creates a new log filterer instance of NFTConfig, bound to a specific deployed contract. -func NewNFTConfigFilterer(address common.Address, filterer bind.ContractFilterer) (*NFTConfigFilterer, error) { - contract, err := bindNFTConfig(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &NFTConfigFilterer{contract: contract}, nil -} - -// bindNFTConfig binds a generic wrapper to an already deployed contract. -func bindNFTConfig(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(NFTConfigABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_NFTConfig *NFTConfigRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _NFTConfig.Contract.NFTConfigCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_NFTConfig *NFTConfigRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _NFTConfig.Contract.NFTConfigTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_NFTConfig *NFTConfigRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _NFTConfig.Contract.NFTConfigTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_NFTConfig *NFTConfigCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _NFTConfig.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_NFTConfig *NFTConfigTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _NFTConfig.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_NFTConfig *NFTConfigTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _NFTConfig.Contract.contract.Transact(opts, method, params...) -} - -// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. -// -// Solidity: function getAddress(bytes32 key) view returns(address) -func (_NFTConfig *NFTConfigCaller) GetAddress(opts *bind.CallOpts, key [32]byte) (common.Address, error) { - var out []interface{} - err := _NFTConfig.contract.Call(opts, &out, "getAddress", key) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. -// -// Solidity: function getAddress(bytes32 key) view returns(address) -func (_NFTConfig *NFTConfigSession) GetAddress(key [32]byte) (common.Address, error) { - return _NFTConfig.Contract.GetAddress(&_NFTConfig.CallOpts, key) -} - -// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. -// -// Solidity: function getAddress(bytes32 key) view returns(address) -func (_NFTConfig *NFTConfigCallerSession) GetAddress(key [32]byte) (common.Address, error) { - return _NFTConfig.Contract.GetAddress(&_NFTConfig.CallOpts, key) -} - -// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. -// -// Solidity: function getUint256(bytes32 key) view returns(uint256) -func (_NFTConfig *NFTConfigCaller) GetUint256(opts *bind.CallOpts, key [32]byte) (*big.Int, error) { - var out []interface{} - err := _NFTConfig.contract.Call(opts, &out, "getUint256", key) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. -// -// Solidity: function getUint256(bytes32 key) view returns(uint256) -func (_NFTConfig *NFTConfigSession) GetUint256(key [32]byte) (*big.Int, error) { - return _NFTConfig.Contract.GetUint256(&_NFTConfig.CallOpts, key) -} - -// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. -// -// Solidity: function getUint256(bytes32 key) view returns(uint256) -func (_NFTConfig *NFTConfigCallerSession) GetUint256(key [32]byte) (*big.Int, error) { - return _NFTConfig.Contract.GetUint256(&_NFTConfig.CallOpts, key) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_NFTConfig *NFTConfigCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _NFTConfig.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_NFTConfig *NFTConfigSession) Owner() (common.Address, error) { - return _NFTConfig.Contract.Owner(&_NFTConfig.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_NFTConfig *NFTConfigCallerSession) Owner() (common.Address, error) { - return _NFTConfig.Contract.Owner(&_NFTConfig.CallOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_NFTConfig *NFTConfigTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _NFTConfig.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_NFTConfig *NFTConfigSession) RenounceOwnership() (*types.Transaction, error) { - return _NFTConfig.Contract.RenounceOwnership(&_NFTConfig.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_NFTConfig *NFTConfigTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _NFTConfig.Contract.RenounceOwnership(&_NFTConfig.TransactOpts) -} - -// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. -// -// Solidity: function setAddress(bytes32 key, address value) returns() -func (_NFTConfig *NFTConfigTransactor) SetAddress(opts *bind.TransactOpts, key [32]byte, value common.Address) (*types.Transaction, error) { - return _NFTConfig.contract.Transact(opts, "setAddress", key, value) -} - -// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. -// -// Solidity: function setAddress(bytes32 key, address value) returns() -func (_NFTConfig *NFTConfigSession) SetAddress(key [32]byte, value common.Address) (*types.Transaction, error) { - return _NFTConfig.Contract.SetAddress(&_NFTConfig.TransactOpts, key, value) -} - -// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. -// -// Solidity: function setAddress(bytes32 key, address value) returns() -func (_NFTConfig *NFTConfigTransactorSession) SetAddress(key [32]byte, value common.Address) (*types.Transaction, error) { - return _NFTConfig.Contract.SetAddress(&_NFTConfig.TransactOpts, key, value) -} - -// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. -// -// Solidity: function setUint256(bytes32 key, uint256 value) returns() -func (_NFTConfig *NFTConfigTransactor) SetUint256(opts *bind.TransactOpts, key [32]byte, value *big.Int) (*types.Transaction, error) { - return _NFTConfig.contract.Transact(opts, "setUint256", key, value) -} - -// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. -// -// Solidity: function setUint256(bytes32 key, uint256 value) returns() -func (_NFTConfig *NFTConfigSession) SetUint256(key [32]byte, value *big.Int) (*types.Transaction, error) { - return _NFTConfig.Contract.SetUint256(&_NFTConfig.TransactOpts, key, value) -} - -// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. -// -// Solidity: function setUint256(bytes32 key, uint256 value) returns() -func (_NFTConfig *NFTConfigTransactorSession) SetUint256(key [32]byte, value *big.Int) (*types.Transaction, error) { - return _NFTConfig.Contract.SetUint256(&_NFTConfig.TransactOpts, key, value) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_NFTConfig *NFTConfigTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _NFTConfig.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_NFTConfig *NFTConfigSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _NFTConfig.Contract.TransferOwnership(&_NFTConfig.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_NFTConfig *NFTConfigTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _NFTConfig.Contract.TransferOwnership(&_NFTConfig.TransactOpts, newOwner) -} - -// NFTConfigConfigUpdatedIterator is returned from FilterConfigUpdated and is used to iterate over the raw logs and unpacked data for ConfigUpdated events raised by the NFTConfig contract. -type NFTConfigConfigUpdatedIterator struct { - Event *NFTConfigConfigUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *NFTConfigConfigUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(NFTConfigConfigUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(NFTConfigConfigUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *NFTConfigConfigUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *NFTConfigConfigUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// NFTConfigConfigUpdated represents a ConfigUpdated event raised by the NFTConfig contract. -type NFTConfigConfigUpdated struct { - Key [32]byte - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterConfigUpdated is a free log retrieval operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. -// -// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) -func (_NFTConfig *NFTConfigFilterer) FilterConfigUpdated(opts *bind.FilterOpts, key [][32]byte) (*NFTConfigConfigUpdatedIterator, error) { - - var keyRule []interface{} - for _, keyItem := range key { - keyRule = append(keyRule, keyItem) - } - - logs, sub, err := _NFTConfig.contract.FilterLogs(opts, "ConfigUpdated", keyRule) - if err != nil { - return nil, err - } - return &NFTConfigConfigUpdatedIterator{contract: _NFTConfig.contract, event: "ConfigUpdated", logs: logs, sub: sub}, nil -} - -// WatchConfigUpdated is a free log subscription operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. -// -// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) -func (_NFTConfig *NFTConfigFilterer) WatchConfigUpdated(opts *bind.WatchOpts, sink chan<- *NFTConfigConfigUpdated, key [][32]byte) (event.Subscription, error) { - - var keyRule []interface{} - for _, keyItem := range key { - keyRule = append(keyRule, keyItem) - } - - logs, sub, err := _NFTConfig.contract.WatchLogs(opts, "ConfigUpdated", keyRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(NFTConfigConfigUpdated) - if err := _NFTConfig.contract.UnpackLog(event, "ConfigUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseConfigUpdated is a log parse operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. -// -// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) -func (_NFTConfig *NFTConfigFilterer) ParseConfigUpdated(log types.Log) (*NFTConfigConfigUpdated, error) { - event := new(NFTConfigConfigUpdated) - if err := _NFTConfig.contract.UnpackLog(event, "ConfigUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// NFTConfigOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the NFTConfig contract. -type NFTConfigOwnershipTransferredIterator struct { - Event *NFTConfigOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *NFTConfigOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(NFTConfigOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(NFTConfigOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *NFTConfigOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *NFTConfigOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// NFTConfigOwnershipTransferred represents a OwnershipTransferred event raised by the NFTConfig contract. -type NFTConfigOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_NFTConfig *NFTConfigFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*NFTConfigOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _NFTConfig.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &NFTConfigOwnershipTransferredIterator{contract: _NFTConfig.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_NFTConfig *NFTConfigFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *NFTConfigOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _NFTConfig.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(NFTConfigOwnershipTransferred) - if err := _NFTConfig.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_NFTConfig *NFTConfigFilterer) ParseOwnershipTransferred(log types.Log) (*NFTConfigOwnershipTransferred, error) { - event := new(NFTConfigOwnershipTransferred) - if err := _NFTConfig.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/ethereum/uniswapnetwork/uniswapnetwork.go b/zcnbridge/ethereum/uniswapnetwork/uniswapnetwork.go deleted file mode 100644 index 1045cad8b..000000000 --- a/zcnbridge/ethereum/uniswapnetwork/uniswapnetwork.go +++ /dev/null @@ -1,536 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package uniswapnetwork - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = abi.ConvertType -) - -// UniswapMetaData contains all meta data concerning the Uniswap contract. -var UniswapMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"msg\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"v\",\"type\":\"uint256\"}],\"name\":\"DebugMsg\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"zcnAmount\",\"type\":\"uint256\"}],\"name\":\"getEstimatedETHforZCN\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"}],\"name\":\"swapETHForZCNExactAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutDesired\",\"type\":\"uint256\"}],\"name\":\"swapETHForZCNExactAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"}],\"name\":\"swapUSDCForZCNExactAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"}],\"name\":\"swapUSDCForZCNExactAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"}],\"name\":\"swapZCNForUSDCExactAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"}],\"name\":\"swapZCNForUSDCExactAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"}],\"name\":\"swapZCNForWETHExactAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"}],\"name\":\"swapZCNForWETHExactAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", -} - -// UniswapABI is the input ABI used to generate the binding from. -// Deprecated: Use UniswapMetaData.ABI instead. -var UniswapABI = UniswapMetaData.ABI - -// Uniswap is an auto generated Go binding around an Ethereum contract. -type Uniswap struct { - UniswapCaller // Read-only binding to the contract - UniswapTransactor // Write-only binding to the contract - UniswapFilterer // Log filterer for contract events -} - -// UniswapCaller is an auto generated read-only Go binding around an Ethereum contract. -type UniswapCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// UniswapTransactor is an auto generated write-only Go binding around an Ethereum contract. -type UniswapTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// UniswapFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type UniswapFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// UniswapSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type UniswapSession struct { - Contract *Uniswap // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// UniswapCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type UniswapCallerSession struct { - Contract *UniswapCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// UniswapTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type UniswapTransactorSession struct { - Contract *UniswapTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// UniswapRaw is an auto generated low-level Go binding around an Ethereum contract. -type UniswapRaw struct { - Contract *Uniswap // Generic contract binding to access the raw methods on -} - -// UniswapCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type UniswapCallerRaw struct { - Contract *UniswapCaller // Generic read-only contract binding to access the raw methods on -} - -// UniswapTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type UniswapTransactorRaw struct { - Contract *UniswapTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewUniswap creates a new instance of Uniswap, bound to a specific deployed contract. -func NewUniswap(address common.Address, backend bind.ContractBackend) (*Uniswap, error) { - contract, err := bindUniswap(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Uniswap{UniswapCaller: UniswapCaller{contract: contract}, UniswapTransactor: UniswapTransactor{contract: contract}, UniswapFilterer: UniswapFilterer{contract: contract}}, nil -} - -// NewUniswapCaller creates a new read-only instance of Uniswap, bound to a specific deployed contract. -func NewUniswapCaller(address common.Address, caller bind.ContractCaller) (*UniswapCaller, error) { - contract, err := bindUniswap(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &UniswapCaller{contract: contract}, nil -} - -// NewUniswapTransactor creates a new write-only instance of Uniswap, bound to a specific deployed contract. -func NewUniswapTransactor(address common.Address, transactor bind.ContractTransactor) (*UniswapTransactor, error) { - contract, err := bindUniswap(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &UniswapTransactor{contract: contract}, nil -} - -// NewUniswapFilterer creates a new log filterer instance of Uniswap, bound to a specific deployed contract. -func NewUniswapFilterer(address common.Address, filterer bind.ContractFilterer) (*UniswapFilterer, error) { - contract, err := bindUniswap(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &UniswapFilterer{contract: contract}, nil -} - -// bindUniswap binds a generic wrapper to an already deployed contract. -func bindUniswap(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := UniswapMetaData.GetAbi() - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Uniswap *UniswapRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Uniswap.Contract.UniswapCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Uniswap *UniswapRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Uniswap.Contract.UniswapTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Uniswap *UniswapRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Uniswap.Contract.UniswapTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Uniswap *UniswapCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Uniswap.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Uniswap *UniswapTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Uniswap.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Uniswap *UniswapTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Uniswap.Contract.contract.Transact(opts, method, params...) -} - -// GetEstimatedETHforZCN is a free data retrieval call binding the contract method 0x1a34ff1c. -// -// Solidity: function getEstimatedETHforZCN(uint256 zcnAmount) view returns(uint256[]) -func (_Uniswap *UniswapCaller) GetEstimatedETHforZCN(opts *bind.CallOpts, zcnAmount *big.Int) ([]*big.Int, error) { - var out []interface{} - err := _Uniswap.contract.Call(opts, &out, "getEstimatedETHforZCN", zcnAmount) - - if err != nil { - return *new([]*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) - - return out0, err - -} - -// GetEstimatedETHforZCN is a free data retrieval call binding the contract method 0x1a34ff1c. -// -// Solidity: function getEstimatedETHforZCN(uint256 zcnAmount) view returns(uint256[]) -func (_Uniswap *UniswapSession) GetEstimatedETHforZCN(zcnAmount *big.Int) ([]*big.Int, error) { - return _Uniswap.Contract.GetEstimatedETHforZCN(&_Uniswap.CallOpts, zcnAmount) -} - -// GetEstimatedETHforZCN is a free data retrieval call binding the contract method 0x1a34ff1c. -// -// Solidity: function getEstimatedETHforZCN(uint256 zcnAmount) view returns(uint256[]) -func (_Uniswap *UniswapCallerSession) GetEstimatedETHforZCN(zcnAmount *big.Int) ([]*big.Int, error) { - return _Uniswap.Contract.GetEstimatedETHforZCN(&_Uniswap.CallOpts, zcnAmount) -} - -// SwapETHForZCNExactAmountIn is a paid mutator transaction binding the contract method 0xb33d99b1. -// -// Solidity: function swapETHForZCNExactAmountIn(uint256 amountOutMin) payable returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapETHForZCNExactAmountIn(opts *bind.TransactOpts, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapETHForZCNExactAmountIn", amountOutMin) -} - -// SwapETHForZCNExactAmountIn is a paid mutator transaction binding the contract method 0xb33d99b1. -// -// Solidity: function swapETHForZCNExactAmountIn(uint256 amountOutMin) payable returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapETHForZCNExactAmountIn(amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapETHForZCNExactAmountIn(&_Uniswap.TransactOpts, amountOutMin) -} - -// SwapETHForZCNExactAmountIn is a paid mutator transaction binding the contract method 0xb33d99b1. -// -// Solidity: function swapETHForZCNExactAmountIn(uint256 amountOutMin) payable returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapETHForZCNExactAmountIn(amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapETHForZCNExactAmountIn(&_Uniswap.TransactOpts, amountOutMin) -} - -// SwapETHForZCNExactAmountOut is a paid mutator transaction binding the contract method 0x18ae74a4. -// -// Solidity: function swapETHForZCNExactAmountOut(uint256 amountOutDesired) payable returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapETHForZCNExactAmountOut(opts *bind.TransactOpts, amountOutDesired *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapETHForZCNExactAmountOut", amountOutDesired) -} - -// SwapETHForZCNExactAmountOut is a paid mutator transaction binding the contract method 0x18ae74a4. -// -// Solidity: function swapETHForZCNExactAmountOut(uint256 amountOutDesired) payable returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapETHForZCNExactAmountOut(amountOutDesired *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapETHForZCNExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired) -} - -// SwapETHForZCNExactAmountOut is a paid mutator transaction binding the contract method 0x18ae74a4. -// -// Solidity: function swapETHForZCNExactAmountOut(uint256 amountOutDesired) payable returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapETHForZCNExactAmountOut(amountOutDesired *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapETHForZCNExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired) -} - -// SwapUSDCForZCNExactAmountIn is a paid mutator transaction binding the contract method 0x0976c3c2. -// -// Solidity: function swapUSDCForZCNExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapUSDCForZCNExactAmountIn(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapUSDCForZCNExactAmountIn", amountIn, amountOutMin) -} - -// SwapUSDCForZCNExactAmountIn is a paid mutator transaction binding the contract method 0x0976c3c2. -// -// Solidity: function swapUSDCForZCNExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapUSDCForZCNExactAmountIn(amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapUSDCForZCNExactAmountIn(&_Uniswap.TransactOpts, amountIn, amountOutMin) -} - -// SwapUSDCForZCNExactAmountIn is a paid mutator transaction binding the contract method 0x0976c3c2. -// -// Solidity: function swapUSDCForZCNExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapUSDCForZCNExactAmountIn(amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapUSDCForZCNExactAmountIn(&_Uniswap.TransactOpts, amountIn, amountOutMin) -} - -// SwapUSDCForZCNExactAmountOut is a paid mutator transaction binding the contract method 0x97a40b34. -// -// Solidity: function swapUSDCForZCNExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapUSDCForZCNExactAmountOut(opts *bind.TransactOpts, amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapUSDCForZCNExactAmountOut", amountOutDesired, amountInMax) -} - -// SwapUSDCForZCNExactAmountOut is a paid mutator transaction binding the contract method 0x97a40b34. -// -// Solidity: function swapUSDCForZCNExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapUSDCForZCNExactAmountOut(amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapUSDCForZCNExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired, amountInMax) -} - -// SwapUSDCForZCNExactAmountOut is a paid mutator transaction binding the contract method 0x97a40b34. -// -// Solidity: function swapUSDCForZCNExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapUSDCForZCNExactAmountOut(amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapUSDCForZCNExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired, amountInMax) -} - -// SwapZCNForUSDCExactAmountIn is a paid mutator transaction binding the contract method 0xe60b51b6. -// -// Solidity: function swapZCNForUSDCExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapZCNForUSDCExactAmountIn(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapZCNForUSDCExactAmountIn", amountIn, amountOutMin) -} - -// SwapZCNForUSDCExactAmountIn is a paid mutator transaction binding the contract method 0xe60b51b6. -// -// Solidity: function swapZCNForUSDCExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapZCNForUSDCExactAmountIn(amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForUSDCExactAmountIn(&_Uniswap.TransactOpts, amountIn, amountOutMin) -} - -// SwapZCNForUSDCExactAmountIn is a paid mutator transaction binding the contract method 0xe60b51b6. -// -// Solidity: function swapZCNForUSDCExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapZCNForUSDCExactAmountIn(amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForUSDCExactAmountIn(&_Uniswap.TransactOpts, amountIn, amountOutMin) -} - -// SwapZCNForUSDCExactAmountOut is a paid mutator transaction binding the contract method 0x4becb631. -// -// Solidity: function swapZCNForUSDCExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapZCNForUSDCExactAmountOut(opts *bind.TransactOpts, amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapZCNForUSDCExactAmountOut", amountOutDesired, amountInMax) -} - -// SwapZCNForUSDCExactAmountOut is a paid mutator transaction binding the contract method 0x4becb631. -// -// Solidity: function swapZCNForUSDCExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapZCNForUSDCExactAmountOut(amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForUSDCExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired, amountInMax) -} - -// SwapZCNForUSDCExactAmountOut is a paid mutator transaction binding the contract method 0x4becb631. -// -// Solidity: function swapZCNForUSDCExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapZCNForUSDCExactAmountOut(amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForUSDCExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired, amountInMax) -} - -// SwapZCNForWETHExactAmountIn is a paid mutator transaction binding the contract method 0x50a6cd6f. -// -// Solidity: function swapZCNForWETHExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapZCNForWETHExactAmountIn(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapZCNForWETHExactAmountIn", amountIn, amountOutMin) -} - -// SwapZCNForWETHExactAmountIn is a paid mutator transaction binding the contract method 0x50a6cd6f. -// -// Solidity: function swapZCNForWETHExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapZCNForWETHExactAmountIn(amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForWETHExactAmountIn(&_Uniswap.TransactOpts, amountIn, amountOutMin) -} - -// SwapZCNForWETHExactAmountIn is a paid mutator transaction binding the contract method 0x50a6cd6f. -// -// Solidity: function swapZCNForWETHExactAmountIn(uint256 amountIn, uint256 amountOutMin) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapZCNForWETHExactAmountIn(amountIn *big.Int, amountOutMin *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForWETHExactAmountIn(&_Uniswap.TransactOpts, amountIn, amountOutMin) -} - -// SwapZCNForWETHExactAmountOut is a paid mutator transaction binding the contract method 0xaae07c3e. -// -// Solidity: function swapZCNForWETHExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactor) SwapZCNForWETHExactAmountOut(opts *bind.TransactOpts, amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.contract.Transact(opts, "swapZCNForWETHExactAmountOut", amountOutDesired, amountInMax) -} - -// SwapZCNForWETHExactAmountOut is a paid mutator transaction binding the contract method 0xaae07c3e. -// -// Solidity: function swapZCNForWETHExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapSession) SwapZCNForWETHExactAmountOut(amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForWETHExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired, amountInMax) -} - -// SwapZCNForWETHExactAmountOut is a paid mutator transaction binding the contract method 0xaae07c3e. -// -// Solidity: function swapZCNForWETHExactAmountOut(uint256 amountOutDesired, uint256 amountInMax) returns(uint256 amountOut) -func (_Uniswap *UniswapTransactorSession) SwapZCNForWETHExactAmountOut(amountOutDesired *big.Int, amountInMax *big.Int) (*types.Transaction, error) { - return _Uniswap.Contract.SwapZCNForWETHExactAmountOut(&_Uniswap.TransactOpts, amountOutDesired, amountInMax) -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Uniswap *UniswapTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Uniswap.contract.RawTransact(opts, nil) // calldata is disallowed for receive function -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Uniswap *UniswapSession) Receive() (*types.Transaction, error) { - return _Uniswap.Contract.Receive(&_Uniswap.TransactOpts) -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Uniswap *UniswapTransactorSession) Receive() (*types.Transaction, error) { - return _Uniswap.Contract.Receive(&_Uniswap.TransactOpts) -} - -// UniswapDebugMsgIterator is returned from FilterDebugMsg and is used to iterate over the raw logs and unpacked data for DebugMsg events raised by the Uniswap contract. -type UniswapDebugMsgIterator struct { - Event *UniswapDebugMsg // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *UniswapDebugMsgIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(UniswapDebugMsg) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(UniswapDebugMsg) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *UniswapDebugMsgIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *UniswapDebugMsgIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// UniswapDebugMsg represents a DebugMsg event raised by the Uniswap contract. -type UniswapDebugMsg struct { - Msg string - V *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterDebugMsg is a free log retrieval operation binding the contract event 0xea30ed2bcbf4b7c5487f2c07ef639257ebf04932960dff4496fb914f769a6439. -// -// Solidity: event DebugMsg(string msg, uint256 v) -func (_Uniswap *UniswapFilterer) FilterDebugMsg(opts *bind.FilterOpts) (*UniswapDebugMsgIterator, error) { - - logs, sub, err := _Uniswap.contract.FilterLogs(opts, "DebugMsg") - if err != nil { - return nil, err - } - return &UniswapDebugMsgIterator{contract: _Uniswap.contract, event: "DebugMsg", logs: logs, sub: sub}, nil -} - -// WatchDebugMsg is a free log subscription operation binding the contract event 0xea30ed2bcbf4b7c5487f2c07ef639257ebf04932960dff4496fb914f769a6439. -// -// Solidity: event DebugMsg(string msg, uint256 v) -func (_Uniswap *UniswapFilterer) WatchDebugMsg(opts *bind.WatchOpts, sink chan<- *UniswapDebugMsg) (event.Subscription, error) { - - logs, sub, err := _Uniswap.contract.WatchLogs(opts, "DebugMsg") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(UniswapDebugMsg) - if err := _Uniswap.contract.UnpackLog(event, "DebugMsg", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseDebugMsg is a log parse operation binding the contract event 0xea30ed2bcbf4b7c5487f2c07ef639257ebf04932960dff4496fb914f769a6439. -// -// Solidity: event DebugMsg(string msg, uint256 v) -func (_Uniswap *UniswapFilterer) ParseDebugMsg(log types.Log) (*UniswapDebugMsg, error) { - event := new(UniswapDebugMsg) - if err := _Uniswap.contract.UnpackLog(event, "DebugMsg", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/ethereum/uniswaprouter/uniswaprouter.go b/zcnbridge/ethereum/uniswaprouter/uniswaprouter.go deleted file mode 100644 index 834210b2d..000000000 --- a/zcnbridge/ethereum/uniswaprouter/uniswaprouter.go +++ /dev/null @@ -1,777 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package uniswaprouter - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = abi.ConvertType -) - -// UniswaprouterMetaData contains all meta data concerning the Uniswaprouter contract. -var UniswaprouterMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_factory\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_WETH\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"WETH\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountADesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"addLiquidity\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"addLiquidityETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveOut\",\"type\":\"uint256\"}],\"name\":\"getAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveOut\",\"type\":\"uint256\"}],\"name\":\"getAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"}],\"name\":\"getAmountsIn\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"}],\"name\":\"getAmountsOut\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveB\",\"type\":\"uint256\"}],\"name\":\"quote\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidity\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidityETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidityETHSupportingFeeOnTransferTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityETHWithPermit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityETHWithPermitSupportingFeeOnTransferTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityWithPermit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapETHForExactTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactETHForTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactETHForTokensSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForETH\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForETHSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForTokensSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapTokensForExactETH\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapTokensForExactTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", -} - -// UniswaprouterABI is the input ABI used to generate the binding from. -// Deprecated: Use UniswaprouterMetaData.ABI instead. -var UniswaprouterABI = UniswaprouterMetaData.ABI - -// Uniswaprouter is an auto generated Go binding around an Ethereum contract. -type Uniswaprouter struct { - UniswaprouterCaller // Read-only binding to the contract - UniswaprouterTransactor // Write-only binding to the contract - UniswaprouterFilterer // Log filterer for contract events -} - -// UniswaprouterCaller is an auto generated read-only Go binding around an Ethereum contract. -type UniswaprouterCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// UniswaprouterTransactor is an auto generated write-only Go binding around an Ethereum contract. -type UniswaprouterTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// UniswaprouterFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type UniswaprouterFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// UniswaprouterSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type UniswaprouterSession struct { - Contract *Uniswaprouter // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// UniswaprouterCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type UniswaprouterCallerSession struct { - Contract *UniswaprouterCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// UniswaprouterTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type UniswaprouterTransactorSession struct { - Contract *UniswaprouterTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// UniswaprouterRaw is an auto generated low-level Go binding around an Ethereum contract. -type UniswaprouterRaw struct { - Contract *Uniswaprouter // Generic contract binding to access the raw methods on -} - -// UniswaprouterCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type UniswaprouterCallerRaw struct { - Contract *UniswaprouterCaller // Generic read-only contract binding to access the raw methods on -} - -// UniswaprouterTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type UniswaprouterTransactorRaw struct { - Contract *UniswaprouterTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewUniswaprouter creates a new instance of Uniswaprouter, bound to a specific deployed contract. -func NewUniswaprouter(address common.Address, backend bind.ContractBackend) (*Uniswaprouter, error) { - contract, err := bindUniswaprouter(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Uniswaprouter{UniswaprouterCaller: UniswaprouterCaller{contract: contract}, UniswaprouterTransactor: UniswaprouterTransactor{contract: contract}, UniswaprouterFilterer: UniswaprouterFilterer{contract: contract}}, nil -} - -// NewUniswaprouterCaller creates a new read-only instance of Uniswaprouter, bound to a specific deployed contract. -func NewUniswaprouterCaller(address common.Address, caller bind.ContractCaller) (*UniswaprouterCaller, error) { - contract, err := bindUniswaprouter(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &UniswaprouterCaller{contract: contract}, nil -} - -// NewUniswaprouterTransactor creates a new write-only instance of Uniswaprouter, bound to a specific deployed contract. -func NewUniswaprouterTransactor(address common.Address, transactor bind.ContractTransactor) (*UniswaprouterTransactor, error) { - contract, err := bindUniswaprouter(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &UniswaprouterTransactor{contract: contract}, nil -} - -// NewUniswaprouterFilterer creates a new log filterer instance of Uniswaprouter, bound to a specific deployed contract. -func NewUniswaprouterFilterer(address common.Address, filterer bind.ContractFilterer) (*UniswaprouterFilterer, error) { - contract, err := bindUniswaprouter(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &UniswaprouterFilterer{contract: contract}, nil -} - -// bindUniswaprouter binds a generic wrapper to an already deployed contract. -func bindUniswaprouter(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := UniswaprouterMetaData.GetAbi() - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Uniswaprouter *UniswaprouterRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Uniswaprouter.Contract.UniswaprouterCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Uniswaprouter *UniswaprouterRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Uniswaprouter.Contract.UniswaprouterTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Uniswaprouter *UniswaprouterRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Uniswaprouter.Contract.UniswaprouterTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Uniswaprouter *UniswaprouterCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Uniswaprouter.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Uniswaprouter *UniswaprouterTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Uniswaprouter.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Uniswaprouter *UniswaprouterTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Uniswaprouter.Contract.contract.Transact(opts, method, params...) -} - -// WETH is a free data retrieval call binding the contract method 0xad5c4648. -// -// Solidity: function WETH() view returns(address) -func (_Uniswaprouter *UniswaprouterCaller) WETH(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "WETH") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// WETH is a free data retrieval call binding the contract method 0xad5c4648. -// -// Solidity: function WETH() view returns(address) -func (_Uniswaprouter *UniswaprouterSession) WETH() (common.Address, error) { - return _Uniswaprouter.Contract.WETH(&_Uniswaprouter.CallOpts) -} - -// WETH is a free data retrieval call binding the contract method 0xad5c4648. -// -// Solidity: function WETH() view returns(address) -func (_Uniswaprouter *UniswaprouterCallerSession) WETH() (common.Address, error) { - return _Uniswaprouter.Contract.WETH(&_Uniswaprouter.CallOpts) -} - -// Factory is a free data retrieval call binding the contract method 0xc45a0155. -// -// Solidity: function factory() view returns(address) -func (_Uniswaprouter *UniswaprouterCaller) Factory(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "factory") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Factory is a free data retrieval call binding the contract method 0xc45a0155. -// -// Solidity: function factory() view returns(address) -func (_Uniswaprouter *UniswaprouterSession) Factory() (common.Address, error) { - return _Uniswaprouter.Contract.Factory(&_Uniswaprouter.CallOpts) -} - -// Factory is a free data retrieval call binding the contract method 0xc45a0155. -// -// Solidity: function factory() view returns(address) -func (_Uniswaprouter *UniswaprouterCallerSession) Factory() (common.Address, error) { - return _Uniswaprouter.Contract.Factory(&_Uniswaprouter.CallOpts) -} - -// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. -// -// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) -func (_Uniswaprouter *UniswaprouterCaller) GetAmountIn(opts *bind.CallOpts, amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "getAmountIn", amountOut, reserveIn, reserveOut) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. -// -// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) -func (_Uniswaprouter *UniswaprouterSession) GetAmountIn(amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountIn(&_Uniswaprouter.CallOpts, amountOut, reserveIn, reserveOut) -} - -// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. -// -// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) -func (_Uniswaprouter *UniswaprouterCallerSession) GetAmountIn(amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountIn(&_Uniswaprouter.CallOpts, amountOut, reserveIn, reserveOut) -} - -// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. -// -// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) -func (_Uniswaprouter *UniswaprouterCaller) GetAmountOut(opts *bind.CallOpts, amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "getAmountOut", amountIn, reserveIn, reserveOut) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. -// -// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) -func (_Uniswaprouter *UniswaprouterSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountOut(&_Uniswaprouter.CallOpts, amountIn, reserveIn, reserveOut) -} - -// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. -// -// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) -func (_Uniswaprouter *UniswaprouterCallerSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountOut(&_Uniswaprouter.CallOpts, amountIn, reserveIn, reserveOut) -} - -// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. -// -// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterCaller) GetAmountsIn(opts *bind.CallOpts, amountOut *big.Int, path []common.Address) ([]*big.Int, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "getAmountsIn", amountOut, path) - - if err != nil { - return *new([]*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) - - return out0, err - -} - -// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. -// -// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) GetAmountsIn(amountOut *big.Int, path []common.Address) ([]*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountsIn(&_Uniswaprouter.CallOpts, amountOut, path) -} - -// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. -// -// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterCallerSession) GetAmountsIn(amountOut *big.Int, path []common.Address) ([]*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountsIn(&_Uniswaprouter.CallOpts, amountOut, path) -} - -// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. -// -// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterCaller) GetAmountsOut(opts *bind.CallOpts, amountIn *big.Int, path []common.Address) ([]*big.Int, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "getAmountsOut", amountIn, path) - - if err != nil { - return *new([]*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) - - return out0, err - -} - -// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. -// -// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) GetAmountsOut(amountIn *big.Int, path []common.Address) ([]*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountsOut(&_Uniswaprouter.CallOpts, amountIn, path) -} - -// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. -// -// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterCallerSession) GetAmountsOut(amountIn *big.Int, path []common.Address) ([]*big.Int, error) { - return _Uniswaprouter.Contract.GetAmountsOut(&_Uniswaprouter.CallOpts, amountIn, path) -} - -// Quote is a free data retrieval call binding the contract method 0xad615dec. -// -// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) -func (_Uniswaprouter *UniswaprouterCaller) Quote(opts *bind.CallOpts, amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { - var out []interface{} - err := _Uniswaprouter.contract.Call(opts, &out, "quote", amountA, reserveA, reserveB) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Quote is a free data retrieval call binding the contract method 0xad615dec. -// -// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) -func (_Uniswaprouter *UniswaprouterSession) Quote(amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { - return _Uniswaprouter.Contract.Quote(&_Uniswaprouter.CallOpts, amountA, reserveA, reserveB) -} - -// Quote is a free data retrieval call binding the contract method 0xad615dec. -// -// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) -func (_Uniswaprouter *UniswaprouterCallerSession) Quote(amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { - return _Uniswaprouter.Contract.Quote(&_Uniswaprouter.CallOpts, amountA, reserveA, reserveB) -} - -// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. -// -// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) -func (_Uniswaprouter *UniswaprouterTransactor) AddLiquidity(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "addLiquidity", tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) -} - -// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. -// -// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) -func (_Uniswaprouter *UniswaprouterSession) AddLiquidity(tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.AddLiquidity(&_Uniswaprouter.TransactOpts, tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) -} - -// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. -// -// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) -func (_Uniswaprouter *UniswaprouterTransactorSession) AddLiquidity(tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.AddLiquidity(&_Uniswaprouter.TransactOpts, tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) -} - -// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. -// -// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) -func (_Uniswaprouter *UniswaprouterTransactor) AddLiquidityETH(opts *bind.TransactOpts, token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "addLiquidityETH", token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) -} - -// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. -// -// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) -func (_Uniswaprouter *UniswaprouterSession) AddLiquidityETH(token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.AddLiquidityETH(&_Uniswaprouter.TransactOpts, token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) -} - -// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. -// -// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) -func (_Uniswaprouter *UniswaprouterTransactorSession) AddLiquidityETH(token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.AddLiquidityETH(&_Uniswaprouter.TransactOpts, token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. -// -// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) -func (_Uniswaprouter *UniswaprouterTransactor) RemoveLiquidity(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "removeLiquidity", tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) -} - -// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. -// -// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) -func (_Uniswaprouter *UniswaprouterSession) RemoveLiquidity(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidity(&_Uniswaprouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) -} - -// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. -// -// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) -func (_Uniswaprouter *UniswaprouterTransactorSession) RemoveLiquidity(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidity(&_Uniswaprouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) -} - -// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. -// -// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactor) RemoveLiquidityETH(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "removeLiquidityETH", token, liquidity, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. -// -// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) -func (_Uniswaprouter *UniswaprouterSession) RemoveLiquidityETH(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETH(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. -// -// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactorSession) RemoveLiquidityETH(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETH(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. -// -// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactor) RemoveLiquidityETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "removeLiquidityETHSupportingFeeOnTransferTokens", token, liquidity, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. -// -// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) -func (_Uniswaprouter *UniswaprouterSession) RemoveLiquidityETHSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETHSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. -// -// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactorSession) RemoveLiquidityETHSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETHSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) -} - -// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. -// -// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactor) RemoveLiquidityETHWithPermit(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "removeLiquidityETHWithPermit", token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. -// -// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) -func (_Uniswaprouter *UniswaprouterSession) RemoveLiquidityETHWithPermit(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETHWithPermit(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. -// -// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactorSession) RemoveLiquidityETHWithPermit(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETHWithPermit(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. -// -// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactor) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "removeLiquidityETHWithPermitSupportingFeeOnTransferTokens", token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. -// -// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) -func (_Uniswaprouter *UniswaprouterSession) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. -// -// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) -func (_Uniswaprouter *UniswaprouterTransactorSession) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. -// -// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) -func (_Uniswaprouter *UniswaprouterTransactor) RemoveLiquidityWithPermit(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "removeLiquidityWithPermit", tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. -// -// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) -func (_Uniswaprouter *UniswaprouterSession) RemoveLiquidityWithPermit(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityWithPermit(&_Uniswaprouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) -} - -// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. -// -// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) -func (_Uniswaprouter *UniswaprouterTransactorSession) RemoveLiquidityWithPermit(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { - return _Uniswaprouter.Contract.RemoveLiquidityWithPermit(&_Uniswaprouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) -} - -// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. -// -// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactor) SwapETHForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapETHForExactTokens", amountOut, path, to, deadline) -} - -// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. -// -// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) SwapETHForExactTokens(amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapETHForExactTokens(&_Uniswaprouter.TransactOpts, amountOut, path, to, deadline) -} - -// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. -// -// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapETHForExactTokens(amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapETHForExactTokens(&_Uniswaprouter.TransactOpts, amountOut, path, to, deadline) -} - -// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. -// -// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactor) SwapExactETHForTokens(opts *bind.TransactOpts, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapExactETHForTokens", amountOutMin, path, to, deadline) -} - -// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. -// -// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) SwapExactETHForTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactETHForTokens(&_Uniswaprouter.TransactOpts, amountOutMin, path, to, deadline) -} - -// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. -// -// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapExactETHForTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactETHForTokens(&_Uniswaprouter.TransactOpts, amountOutMin, path, to, deadline) -} - -// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. -// -// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() -func (_Uniswaprouter *UniswaprouterTransactor) SwapExactETHForTokensSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapExactETHForTokensSupportingFeeOnTransferTokens", amountOutMin, path, to, deadline) -} - -// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. -// -// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() -func (_Uniswaprouter *UniswaprouterSession) SwapExactETHForTokensSupportingFeeOnTransferTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactETHForTokensSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, amountOutMin, path, to, deadline) -} - -// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. -// -// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapExactETHForTokensSupportingFeeOnTransferTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactETHForTokensSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. -// -// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactor) SwapExactTokensForETH(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapExactTokensForETH", amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. -// -// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) SwapExactTokensForETH(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForETH(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. -// -// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapExactTokensForETH(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForETH(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. -// -// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() -func (_Uniswaprouter *UniswaprouterTransactor) SwapExactTokensForETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapExactTokensForETHSupportingFeeOnTransferTokens", amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. -// -// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() -func (_Uniswaprouter *UniswaprouterSession) SwapExactTokensForETHSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForETHSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. -// -// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapExactTokensForETHSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForETHSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. -// -// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactor) SwapExactTokensForTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapExactTokensForTokens", amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. -// -// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForTokens(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. -// -// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForTokens(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. -// -// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() -func (_Uniswaprouter *UniswaprouterTransactor) SwapExactTokensForTokensSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapExactTokensForTokensSupportingFeeOnTransferTokens", amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. -// -// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() -func (_Uniswaprouter *UniswaprouterSession) SwapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForTokensSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. -// -// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapExactTokensForTokensSupportingFeeOnTransferTokens(&_Uniswaprouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) -} - -// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. -// -// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactor) SwapTokensForExactETH(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapTokensForExactETH", amountOut, amountInMax, path, to, deadline) -} - -// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. -// -// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) SwapTokensForExactETH(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapTokensForExactETH(&_Uniswaprouter.TransactOpts, amountOut, amountInMax, path, to, deadline) -} - -// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. -// -// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapTokensForExactETH(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapTokensForExactETH(&_Uniswaprouter.TransactOpts, amountOut, amountInMax, path, to, deadline) -} - -// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. -// -// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactor) SwapTokensForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.contract.Transact(opts, "swapTokensForExactTokens", amountOut, amountInMax, path, to, deadline) -} - -// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. -// -// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterSession) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapTokensForExactTokens(&_Uniswaprouter.TransactOpts, amountOut, amountInMax, path, to, deadline) -} - -// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. -// -// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) -func (_Uniswaprouter *UniswaprouterTransactorSession) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { - return _Uniswaprouter.Contract.SwapTokensForExactTokens(&_Uniswaprouter.TransactOpts, amountOut, amountInMax, path, to, deadline) -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Uniswaprouter *UniswaprouterTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Uniswaprouter.contract.RawTransact(opts, nil) // calldata is disallowed for receive function -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Uniswaprouter *UniswaprouterSession) Receive() (*types.Transaction, error) { - return _Uniswaprouter.Contract.Receive(&_Uniswaprouter.TransactOpts) -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Uniswaprouter *UniswaprouterTransactorSession) Receive() (*types.Transaction, error) { - return _Uniswaprouter.Contract.Receive(&_Uniswaprouter.TransactOpts) -} - diff --git a/zcnbridge/ethereum/zcntoken/zcntoken.go b/zcnbridge/ethereum/zcntoken/zcntoken.go deleted file mode 100644 index 0caf78343..000000000 --- a/zcnbridge/ethereum/zcntoken/zcntoken.go +++ /dev/null @@ -1,1336 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package zcntoken - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = abi.ConvertType -) - -// TokenMetaData contains all meta data concerning the Token contract. -var TokenMetaData = &bind.MetaData{ - ABI: "[{\"constant\":true,\"inputs\":[],\"name\":\"mintingFinished\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseApproval\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"finishMinting\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseApproval\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Mint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"MintFinished\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]", -} - -// TokenABI is the input ABI used to generate the binding from. -// Deprecated: Use TokenMetaData.ABI instead. -var TokenABI = TokenMetaData.ABI - -// Token is an auto generated Go binding around an Ethereum contract. -type Token struct { - TokenCaller // Read-only binding to the contract - TokenTransactor // Write-only binding to the contract - TokenFilterer // Log filterer for contract events -} - -// TokenCaller is an auto generated read-only Go binding around an Ethereum contract. -type TokenCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TokenTransactor is an auto generated write-only Go binding around an Ethereum contract. -type TokenTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type TokenFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TokenSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type TokenSession struct { - Contract *Token // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type TokenCallerSession struct { - Contract *TokenCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// TokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type TokenTransactorSession struct { - Contract *TokenTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TokenRaw is an auto generated low-level Go binding around an Ethereum contract. -type TokenRaw struct { - Contract *Token // Generic contract binding to access the raw methods on -} - -// TokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type TokenCallerRaw struct { - Contract *TokenCaller // Generic read-only contract binding to access the raw methods on -} - -// TokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type TokenTransactorRaw struct { - Contract *TokenTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewToken creates a new instance of Token, bound to a specific deployed contract. -func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) { - contract, err := bindToken(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil -} - -// NewTokenCaller creates a new read-only instance of Token, bound to a specific deployed contract. -func NewTokenCaller(address common.Address, caller bind.ContractCaller) (*TokenCaller, error) { - contract, err := bindToken(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &TokenCaller{contract: contract}, nil -} - -// NewTokenTransactor creates a new write-only instance of Token, bound to a specific deployed contract. -func NewTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*TokenTransactor, error) { - contract, err := bindToken(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &TokenTransactor{contract: contract}, nil -} - -// NewTokenFilterer creates a new log filterer instance of Token, bound to a specific deployed contract. -func NewTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*TokenFilterer, error) { - contract, err := bindToken(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &TokenFilterer{contract: contract}, nil -} - -// bindToken binds a generic wrapper to an already deployed contract. -func bindToken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := TokenMetaData.GetAbi() - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Token *TokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Token.Contract.TokenCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Token.Contract.TokenTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Token *TokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Token.Contract.TokenTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Token *TokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Token.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Token.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Token *TokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Token.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address _owner, address _spender) view returns(uint256) -func (_Token *TokenCaller) Allowance(opts *bind.CallOpts, _owner common.Address, _spender common.Address) (*big.Int, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "allowance", _owner, _spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address _owner, address _spender) view returns(uint256) -func (_Token *TokenSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { - return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address _owner, address _spender) view returns(uint256) -func (_Token *TokenCallerSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { - return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address _owner) view returns(uint256 balance) -func (_Token *TokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "balanceOf", _owner) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address _owner) view returns(uint256 balance) -func (_Token *TokenSession) BalanceOf(_owner common.Address) (*big.Int, error) { - return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address _owner) view returns(uint256 balance) -func (_Token *TokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) { - return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_Token *TokenCaller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_Token *TokenSession) Decimals() (uint8, error) { - return _Token.Contract.Decimals(&_Token.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_Token *TokenCallerSession) Decimals() (uint8, error) { - return _Token.Contract.Decimals(&_Token.CallOpts) -} - -// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. -// -// Solidity: function mintingFinished() view returns(bool) -func (_Token *TokenCaller) MintingFinished(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "mintingFinished") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. -// -// Solidity: function mintingFinished() view returns(bool) -func (_Token *TokenSession) MintingFinished() (bool, error) { - return _Token.Contract.MintingFinished(&_Token.CallOpts) -} - -// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. -// -// Solidity: function mintingFinished() view returns(bool) -func (_Token *TokenCallerSession) MintingFinished() (bool, error) { - return _Token.Contract.MintingFinished(&_Token.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Token *TokenCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Token *TokenSession) Name() (string, error) { - return _Token.Contract.Name(&_Token.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Token *TokenCallerSession) Name() (string, error) { - return _Token.Contract.Name(&_Token.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Token *TokenCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Token *TokenSession) Owner() (common.Address, error) { - return _Token.Contract.Owner(&_Token.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Token *TokenCallerSession) Owner() (common.Address, error) { - return _Token.Contract.Owner(&_Token.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Token *TokenCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Token *TokenSession) Symbol() (string, error) { - return _Token.Contract.Symbol(&_Token.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Token *TokenCallerSession) Symbol() (string, error) { - return _Token.Contract.Symbol(&_Token.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_Token *TokenCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Token.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_Token *TokenSession) TotalSupply() (*big.Int, error) { - return _Token.Contract.TotalSupply(&_Token.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_Token *TokenCallerSession) TotalSupply() (*big.Int, error) { - return _Token.Contract.TotalSupply(&_Token.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address _spender, uint256 _value) returns(bool) -func (_Token *TokenTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "approve", _spender, _value) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address _spender, uint256 _value) returns(bool) -func (_Token *TokenSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address _spender, uint256 _value) returns(bool) -func (_Token *TokenTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) -} - -// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. -// -// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) -func (_Token *TokenTransactor) DecreaseApproval(opts *bind.TransactOpts, _spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "decreaseApproval", _spender, _subtractedValue) -} - -// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. -// -// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) -func (_Token *TokenSession) DecreaseApproval(_spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { - return _Token.Contract.DecreaseApproval(&_Token.TransactOpts, _spender, _subtractedValue) -} - -// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. -// -// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) -func (_Token *TokenTransactorSession) DecreaseApproval(_spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { - return _Token.Contract.DecreaseApproval(&_Token.TransactOpts, _spender, _subtractedValue) -} - -// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. -// -// Solidity: function finishMinting() returns(bool) -func (_Token *TokenTransactor) FinishMinting(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "finishMinting") -} - -// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. -// -// Solidity: function finishMinting() returns(bool) -func (_Token *TokenSession) FinishMinting() (*types.Transaction, error) { - return _Token.Contract.FinishMinting(&_Token.TransactOpts) -} - -// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. -// -// Solidity: function finishMinting() returns(bool) -func (_Token *TokenTransactorSession) FinishMinting() (*types.Transaction, error) { - return _Token.Contract.FinishMinting(&_Token.TransactOpts) -} - -// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. -// -// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) -func (_Token *TokenTransactor) IncreaseApproval(opts *bind.TransactOpts, _spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "increaseApproval", _spender, _addedValue) -} - -// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. -// -// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) -func (_Token *TokenSession) IncreaseApproval(_spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { - return _Token.Contract.IncreaseApproval(&_Token.TransactOpts, _spender, _addedValue) -} - -// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. -// -// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) -func (_Token *TokenTransactorSession) IncreaseApproval(_spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { - return _Token.Contract.IncreaseApproval(&_Token.TransactOpts, _spender, _addedValue) -} - -// Mint is a paid mutator transaction binding the contract method 0x40c10f19. -// -// Solidity: function mint(address _to, uint256 _amount) returns(bool) -func (_Token *TokenTransactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "mint", _to, _amount) -} - -// Mint is a paid mutator transaction binding the contract method 0x40c10f19. -// -// Solidity: function mint(address _to, uint256 _amount) returns(bool) -func (_Token *TokenSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) { - return _Token.Contract.Mint(&_Token.TransactOpts, _to, _amount) -} - -// Mint is a paid mutator transaction binding the contract method 0x40c10f19. -// -// Solidity: function mint(address _to, uint256 _amount) returns(bool) -func (_Token *TokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) { - return _Token.Contract.Mint(&_Token.TransactOpts, _to, _amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address _to, uint256 _value) returns(bool) -func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "transfer", _to, _value) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address _to, uint256 _value) returns(bool) -func (_Token *TokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address _to, uint256 _value) returns(bool) -func (_Token *TokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) -func (_Token *TokenTransactor) TransferFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "transferFrom", _from, _to, _value) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) -func (_Token *TokenSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) -func (_Token *TokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { - return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Token *TokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Token.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Token *TokenSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Token.Contract.TransferOwnership(&_Token.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Token *TokenTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Token.Contract.TransferOwnership(&_Token.TransactOpts, newOwner) -} - -// TokenApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Token contract. -type TokenApprovalIterator struct { - Event *TokenApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TokenApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TokenApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TokenApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TokenApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TokenApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TokenApproval represents a Approval event raised by the Token contract. -type TokenApproval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_Token *TokenFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*TokenApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _Token.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &TokenApprovalIterator{contract: _Token.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_Token *TokenFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *TokenApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _Token.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TokenApproval) - if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_Token *TokenFilterer) ParseApproval(log types.Log) (*TokenApproval, error) { - event := new(TokenApproval) - if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TokenMintIterator is returned from FilterMint and is used to iterate over the raw logs and unpacked data for Mint events raised by the Token contract. -type TokenMintIterator struct { - Event *TokenMint // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TokenMintIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TokenMint) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TokenMint) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TokenMintIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TokenMintIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TokenMint represents a Mint event raised by the Token contract. -type TokenMint struct { - To common.Address - Amount *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMint is a free log retrieval operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. -// -// Solidity: event Mint(address indexed to, uint256 amount) -func (_Token *TokenFilterer) FilterMint(opts *bind.FilterOpts, to []common.Address) (*TokenMintIterator, error) { - - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _Token.contract.FilterLogs(opts, "Mint", toRule) - if err != nil { - return nil, err - } - return &TokenMintIterator{contract: _Token.contract, event: "Mint", logs: logs, sub: sub}, nil -} - -// WatchMint is a free log subscription operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. -// -// Solidity: event Mint(address indexed to, uint256 amount) -func (_Token *TokenFilterer) WatchMint(opts *bind.WatchOpts, sink chan<- *TokenMint, to []common.Address) (event.Subscription, error) { - - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _Token.contract.WatchLogs(opts, "Mint", toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TokenMint) - if err := _Token.contract.UnpackLog(event, "Mint", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMint is a log parse operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. -// -// Solidity: event Mint(address indexed to, uint256 amount) -func (_Token *TokenFilterer) ParseMint(log types.Log) (*TokenMint, error) { - event := new(TokenMint) - if err := _Token.contract.UnpackLog(event, "Mint", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TokenMintFinishedIterator is returned from FilterMintFinished and is used to iterate over the raw logs and unpacked data for MintFinished events raised by the Token contract. -type TokenMintFinishedIterator struct { - Event *TokenMintFinished // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TokenMintFinishedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TokenMintFinished) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TokenMintFinished) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TokenMintFinishedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TokenMintFinishedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TokenMintFinished represents a MintFinished event raised by the Token contract. -type TokenMintFinished struct { - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMintFinished is a free log retrieval operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. -// -// Solidity: event MintFinished() -func (_Token *TokenFilterer) FilterMintFinished(opts *bind.FilterOpts) (*TokenMintFinishedIterator, error) { - - logs, sub, err := _Token.contract.FilterLogs(opts, "MintFinished") - if err != nil { - return nil, err - } - return &TokenMintFinishedIterator{contract: _Token.contract, event: "MintFinished", logs: logs, sub: sub}, nil -} - -// WatchMintFinished is a free log subscription operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. -// -// Solidity: event MintFinished() -func (_Token *TokenFilterer) WatchMintFinished(opts *bind.WatchOpts, sink chan<- *TokenMintFinished) (event.Subscription, error) { - - logs, sub, err := _Token.contract.WatchLogs(opts, "MintFinished") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TokenMintFinished) - if err := _Token.contract.UnpackLog(event, "MintFinished", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMintFinished is a log parse operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. -// -// Solidity: event MintFinished() -func (_Token *TokenFilterer) ParseMintFinished(log types.Log) (*TokenMintFinished, error) { - event := new(TokenMintFinished) - if err := _Token.contract.UnpackLog(event, "MintFinished", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TokenOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Token contract. -type TokenOwnershipTransferredIterator struct { - Event *TokenOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TokenOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TokenOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TokenOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TokenOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TokenOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TokenOwnershipTransferred represents a OwnershipTransferred event raised by the Token contract. -type TokenOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Token *TokenFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*TokenOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Token.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &TokenOwnershipTransferredIterator{contract: _Token.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Token *TokenFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *TokenOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Token.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TokenOwnershipTransferred) - if err := _Token.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Token *TokenFilterer) ParseOwnershipTransferred(log types.Log) (*TokenOwnershipTransferred, error) { - event := new(TokenOwnershipTransferred) - if err := _Token.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TokenTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Token contract. -type TokenTransferIterator struct { - Event *TokenTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TokenTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TokenTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TokenTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TokenTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TokenTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TokenTransfer represents a Transfer event raised by the Token contract. -type TokenTransfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_Token *TokenFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*TokenTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _Token.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &TokenTransferIterator{contract: _Token.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_Token *TokenFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *TokenTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _Token.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TokenTransfer) - if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_Token *TokenFilterer) ParseTransfer(log types.Log) (*TokenTransfer, error) { - event := new(TokenTransfer) - if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/http/client.go b/zcnbridge/http/client.go deleted file mode 100644 index a8044cab7..000000000 --- a/zcnbridge/http/client.go +++ /dev/null @@ -1,42 +0,0 @@ -package http - -import ( - "net/http" - "time" - - "github.com/hashicorp/go-retryablehttp" -) - -const ( - RetryWaitMax = 120 * time.Second - RetryMax = 60 -) - -// NewClient creates default http.Client with timeouts. -func NewClient() *http.Client { - return &http.Client{ - Transport: http.DefaultTransport, - } -} - -func CleanClient() *http.Client { - client := &http.Client{ - Transport: http.DefaultTransport, - } - client.Timeout = 250 * time.Second - return client -} - -// NewRetryableClient creates default retryablehttp.Client with timeouts and embedded NewClient result. -func NewRetryableClient(verbose bool) *retryablehttp.Client { - client := retryablehttp.NewClient() - client.HTTPClient = &http.Client{ - Transport: http.DefaultTransport, - } - - if !verbose { - client.Logger = nil - } - - return client -} diff --git a/zcnbridge/http/doc.go b/zcnbridge/http/doc.go deleted file mode 100644 index fd578c520..000000000 --- a/zcnbridge/http/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Utility methods and types to work with HTTP requests and responses. -package http \ No newline at end of file diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go deleted file mode 100644 index c335f2de3..000000000 --- a/zcnbridge/http/rest.go +++ /dev/null @@ -1,186 +0,0 @@ -package http - -import ( - "crypto/sha1" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sync" - - "go.uber.org/zap" - "gopkg.in/natefinch/lumberjack.v2" - - "github.com/0chain/gosdk/zcnbridge/errors" - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/core/util" -) - -const ( - // SCRestAPIPrefix represents base URL path to execute smart contract rest points. - SCRestAPIPrefix = "v1/screst/" - RestPrefix = SCRestAPIPrefix + zcncore.ZCNSCSmartContractAddress - PathGetAuthorizerNodes = "/getAuthorizerNodes?active=%t" - PathGetGlobalConfig = "/getGlobalConfig" - PathGetAuthorizer = "/getAuthorizer" -) - -type Params map[string]string - -var Logger logger.Logger -var defaultLogLevel = logger.DEBUG -var logVerbose = true - -func init() { - Logger.Init(defaultLogLevel, "zcnbridge-http-sdk") - - Logger.SetLevel(logger.DEBUG) - ioWriter := &lumberjack.Logger{ - Filename: "bridge.log", - MaxSize: 100, // MB - MaxBackups: 5, // number of backups - MaxAge: 28, //days - LocalTime: false, - Compress: false, // disabled by default - } - Logger.SetLogFile(ioWriter, true) -} - -func SetLogFile(logFile string, verbose bool) { - Logger.Init(defaultLogLevel, "zcnbridge-sdk") - Logger.SetLevel(logger.DEBUG) - - ioWriter := &lumberjack.Logger{ - Filename: logFile, - MaxSize: 100, // MB - MaxBackups: 5, // number of backups - MaxAge: 28, //days - LocalTime: false, - Compress: false, // disabled by default - } - logVerbose = verbose - Logger.SetLogFile(ioWriter, logVerbose) -} - -// MakeSCRestAPICall calls smart contract with provided address -// and makes retryable request to smart contract resource with provided relative path using params. -func MakeSCRestAPICall(opCode int, relativePath string, params Params, cb zcncore.GetInfoCallback) { - var ( - resMaxCounterBody []byte - hashMaxCounter int - msg string - hashCounters = make(map[string]int) - sharders = extractSharders() - ) - - type queryResult struct { - hash string - body []byte - } - - results := make(chan *queryResult, len(sharders)) - defer close(results) - - var client = NewRetryableClient(logVerbose) - - wg := &sync.WaitGroup{} - for _, sharder := range sharders { - wg.Add(1) - go func(sharderUrl string) { - defer wg.Done() - - var u = makeURL(params, sharderUrl, relativePath) - Logger.Info("Query ", u.String()) - resp, err := client.Get(u.String()) - if err != nil { - Logger.Error("MakeSCRestAPICall - failed to get response from", zap.String("URL", sharderUrl), zap.Any("error", err)) - return - } - if resp.StatusCode != http.StatusInternalServerError { - //goland:noinspection ALL - defer resp.Body.Close() - } - - if err != nil { - Logger.Error("MakeSCRestAPICall - failed to get response from", zap.String("URL", sharderUrl), zap.Any("error", err)) - return - } - - if resp.StatusCode != http.StatusOK { - Logger.Error("MakeSCRestAPICall - error getting response from", zap.String("URL", sharderUrl), zap.Any("error", err)) - return - } - - Logger.Info("MakeSCRestAPICall successful query") - - hash, body, err := hashAndBytesOfReader(resp.Body) - if err != nil { - Logger.Error("MakeSCRestAPICall - error while reading response body", zap.String("URL", sharderUrl), zap.Any("error", err)) - return - } - - Logger.Info("MakeSCRestAPICall push body to results: ", string(body)) - - results <- &queryResult{hash: hash, body: body} - }(sharder) - } - - Logger.Info("MakeSCRestAPICall waiting for response from all sharders") - wg.Wait() - Logger.Info("MakeSCRestAPICall closing results") - - select { - case result := <-results: - Logger.Debug("request_sharders", zap.String("received result", result.hash), zap.String("received body", string(result.body))) - hashCounters[result.hash]++ - if hashCounters[result.hash] > hashMaxCounter { - hashMaxCounter = hashCounters[result.hash] - resMaxCounterBody = result.body - } - default: - } - - if hashMaxCounter == 0 { - err := errors.New("request_sharders", "no valid responses, last err: "+msg) - cb.OnInfoAvailable(opCode, zcncore.StatusError, "", err.Error()) - Logger.Error(err) - return - } - - cb.OnInfoAvailable(opCode, zcncore.StatusSuccess, string(resMaxCounterBody), "") -} - -// hashAndBytesOfReader computes hash of readers data and returns hash encoded to hex and bytes of reader data. -// If error occurs while reading data from reader, it returns non nil error. -func hashAndBytesOfReader(r io.Reader) (string, []byte, error) { - h := sha1.New() - teeReader := io.TeeReader(r, h) - readerBytes, err := ioutil.ReadAll(teeReader) - if err != nil { - return "", nil, err - } - - return hex.EncodeToString(h.Sum(nil)), readerBytes, nil -} - -// extractSharders returns string slice of randomly ordered sharders existing in the current network. -func extractSharders() []string { - sharders := zcncore.Sharders.Healthy() - return util.GetRandom(sharders, len(sharders)) -} - -// makeURL creates url.URL to make smart contract request to sharder. -func makeURL(params Params, baseURL, relativePath string) *url.URL { - uString := fmt.Sprintf("%v/%v%v", baseURL, RestPrefix, relativePath) - u, _ := url.Parse(uString) - q := u.Query() - for k, v := range params { - q.Add(k, v) - } - u.RawQuery = q.Encode() - - return u -} diff --git a/zcnbridge/http/rest_test.go b/zcnbridge/http/rest_test.go deleted file mode 100644 index feff0d7cf..000000000 --- a/zcnbridge/http/rest_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package http - -import ( - "testing" - - "github.com/0chain/gosdk/zcncore" - - "github.com/stretchr/testify/require" -) - -func Test_MakeURL(t *testing.T) { - p := Params{ - "blobber_id": "1", - } - - url := makeURL(p, "https://baseuri", "/relativePath").String() - require.Equal(t, "https://baseuri/v1/screst/"+zcncore.ZCNSCSmartContractAddress+"/relativePath?blobber_id=1", url) - - p = Params{ - "blobber_id": "1", - "path": "2", - } - - url = makeURL(p, "https://baseuri", "/relativePath").String() - require.Equal(t, "https://baseuri/v1/screst/"+zcncore.ZCNSCSmartContractAddress+"/relativePath?blobber_id=1&path=2", url) -} diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go deleted file mode 100644 index 4794681ce..000000000 --- a/zcnbridge/keystore.go +++ /dev/null @@ -1,202 +0,0 @@ -package zcnbridge - -import ( - "fmt" - "path" - "time" - - hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" -) - -// DetailedAccount describes detailed account -type DetailedAccount struct { - EthereumAddress, - PublicKey, - PrivateKey accounts.Account -} - -// KeyStore is a wrapper, which exposes Ethereum KeyStore methods used by DEX bridge. -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 -} - -type keyStore struct { - ks *keystore.KeyStore -} - -// NewKeyStore creates new KeyStore wrapper instance -func NewKeyStore(path string) KeyStore { - return &keyStore{ - ks: keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP), - } -} - -// Find forwards request to Ethereum KeyStore Find method -func (k *keyStore) Find(account accounts.Account) (accounts.Account, error) { - return k.ks.Find(account) -} - -// TimedUnlock forwards request to Ethereum KeyStore TimedUnlock method -func (k *keyStore) TimedUnlock(account accounts.Account, passPhrase string, timeout time.Duration) error { - return k.ks.TimedUnlock(account, passPhrase, timeout) -} - -// SignHash forwards request to Ethereum KeyStore SignHash method -func (k *keyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { - return k.ks.SignHash(account, hash) -} - -// GetEthereumKeyStore returns Ethereum KeyStore instance -func (k *keyStore) GetEthereumKeyStore() *keystore.KeyStore { - return k.ks -} - -// 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) - config := &accounts.Config{InsecureUnlockAllowed: false} - am := accounts.NewManager(config, ks) - addresses := am.Accounts() - - return addresses -} - -// 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) - config := &accounts.Config{InsecureUnlockAllowed: false} - am := accounts.NewManager(config, ks) - - wallet, err := am.Find(accounts.Account{ - Address: common.HexToAddress(address), - }) - - if err != nil && wallet == nil { - fmt.Printf("failed to find account %s, error: %s", address, err) - return false - } - - return true -} - -// 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) - config := &accounts.Config{InsecureUnlockAllowed: false} - am := accounts.NewManager(config, ks) - - wallet, err := am.Find(accounts.Account{ - Address: common.HexToAddress(address), - }) - - if err != nil && wallet == nil { - fmt.Printf("failed to find account %s, error: %s\n", address, err) - return false - } - - status, _ := wallet.Status() - url := wallet.URL() - - fmt.Printf("Account exists. Status: %s, Path: %s\n", status, url) - - return true -} - -// 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) - account, err := ks.NewAccount(password) - if err != nil { - return errors.Wrap(err, "failed to create keystore") - } - fmt.Printf("Created account: %s", account.Address.Hex()) - - 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 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 - - keyDir := path.Join(homedir, EthereumWalletStorageDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - - // 2. Init wallet - - wallet, err := hdw.NewFromMnemonic(mnemonic) - if err != nil { - return "", errors.Wrap(err, "failed to import from mnemonic") - } - - var aai AccountAddressIndex - if len(accountAddrIndex) > 0 { - aai = accountAddrIndex[0] - } - - var pathD accounts.DerivationPath - if aai.Bip32 { - pathD = hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/%d", aai.AddressIndex)) - } else { - pathD = hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/%d'/0/%d", aai.AccountIndex, aai.AddressIndex)) - } - - account, err := wallet.Derive(pathD, true) - if err != nil { - return "", errors.Wrap(err, "failed parse derivation path") - } - - key, err := wallet.PrivateKey(account) - if err != nil { - return "", errors.Wrap(err, "failed to get private key") - } - - // 3. Find key - - acc, err := ks.Find(account) - if err == nil { - fmt.Printf("Account already exists: %s\nPath: %s\n\n", acc.Address.Hex(), acc.URL.Path) - return acc.Address.Hex(), nil - } - - // 4. Import the key if it doesn't exist - - acc, err = ks.ImportECDSA(key, password) - if err != nil { - return "", errors.Wrap(err, "failed to get import private key") - } - - fmt.Printf("Imported account %s to path: %s\n", acc.Address.Hex(), acc.URL.Path) - - return acc.Address.Hex(), nil -} diff --git a/zcnbridge/log/doc.go b/zcnbridge/log/doc.go deleted file mode 100644 index dee00abe6..000000000 --- a/zcnbridge/log/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Logging methods and types for the ZCN bridge SDK. -package log \ No newline at end of file diff --git a/zcnbridge/log/handler.go b/zcnbridge/log/handler.go deleted file mode 100644 index 8c08faa08..000000000 --- a/zcnbridge/log/handler.go +++ /dev/null @@ -1,57 +0,0 @@ -package log - -import ( - "net/http" - "os" - "strings" - - "github.com/0chain/gosdk_common/core/sys" -) - -// HandleFunc returns handle function that writes logs to http.ResponseWriter with provided buffer size. -// Buffered length represented in kilobytes. -func HandleFunc(buffLen int64) func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, _ *http.Request) { - file, err := os.Open(logName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - defer func() { - _ = file.Close() - }() - - stat, err := sys.Files.Stat(logName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - var ( - writeLen = buffLen * 1024 - brokenLines = true // flag that describes existence of broken lines - ) - if writeLen > stat.Size() { - writeLen = stat.Size() - brokenLines = false - } - - buf := make([]byte, writeLen) - _, err = file.ReadAt(buf, stat.Size()-writeLen) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - // cut broken lines if it exists - if brokenLines { - lbInd := strings.Index(string(buf), "\n") - buf = buf[lbInd+1:] - } - - if _, err := w.Write(buf); err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - } -} diff --git a/zcnbridge/log/logging.go b/zcnbridge/log/logging.go deleted file mode 100644 index d3faac3df..000000000 --- a/zcnbridge/log/logging.go +++ /dev/null @@ -1,93 +0,0 @@ -package log - -import ( - "os" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - "gopkg.in/natefinch/lumberjack.v2" - - "github.com/0chain/gosdk/zcnbridge/errors" -) - -var ( - // Logger represents main logger implementation used in app. - Logger = zap.NewNop() - - // logName - logName string -) - -// InitLogging initializes the main Logger consistent with passed log directory and level. -// -// If an error occurs during execution, the program terminates with code 2 and the error will be written in os.Stderr. -// -// InitLogging should be used only once while application is starting. -func InitLogging(development bool, logDir, level string) { - logName = logDir + "/" + "logs.log" - var ( - logWriter = getWriteSyncer(logName) - logCfg zap.Config - ) - - if development { - logCfg = zap.NewProductionConfig() - logCfg.DisableCaller = true - } else { - logCfg = zap.NewDevelopmentConfig() - logCfg.EncoderConfig.LevelKey = "level" - logCfg.EncoderConfig.NameKey = "name" - logCfg.EncoderConfig.MessageKey = "msg" - logCfg.EncoderConfig.CallerKey = "caller" - logCfg.EncoderConfig.StacktraceKey = "stacktrace" - - logWriter = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), logWriter) - } - _ = logCfg.Level.UnmarshalText([]byte(level)) - logCfg.Encoding = consoleEncoderType - logCfg.EncoderConfig.TimeKey = "timestamp" - logCfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder - - l, err := logCfg.Build(setOutput(logWriter, logCfg)) - if err != nil { - errors.ExitErr("error while build logger config", err, 2) - } - - Logger = l -} - -const ( - jsonEncoderType = "json" - consoleEncoderType = "console" -) - -// setOutput replaces existing Core with new, that writes to passed zapcore.WriteSyncer. -func setOutput(ws zapcore.WriteSyncer, conf zap.Config) zap.Option { - var enc zapcore.Encoder - switch conf.Encoding { - case jsonEncoderType: - enc = zapcore.NewJSONEncoder(conf.EncoderConfig) - case consoleEncoderType: - enc = zapcore.NewConsoleEncoder(conf.EncoderConfig) - default: - errors.ExitMsg("error while build logger config", 2) - } - - return zap.WrapCore(func(core zapcore.Core) zapcore.Core { - return zapcore.NewCore(enc, ws, conf.Level) - }) -} - -// getWriteSyncer creates zapcore.WriteSyncer using provided log file. -func getWriteSyncer(logName string) zapcore.WriteSyncer { - var ioWriter = &lumberjack.Logger{ - Filename: logName, - MaxSize: 10, // MB - MaxBackups: 3, // number of backups - MaxAge: 28, // days - LocalTime: true, - Compress: false, // disabled by default - } - _ = ioWriter.Rotate() - return zapcore.AddSync(ioWriter) -} diff --git a/zcnbridge/mocks/EthereumClient.go b/zcnbridge/mocks/EthereumClient.go deleted file mode 100644 index 309d5ae67..000000000 --- a/zcnbridge/mocks/EthereumClient.go +++ /dev/null @@ -1,332 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - context "context" - big "math/big" - - common "github.com/ethereum/go-ethereum/common" - - ethereum "github.com/ethereum/go-ethereum" - - mock "github.com/stretchr/testify/mock" - - types "github.com/ethereum/go-ethereum/core/types" -) - -// EthereumClient is an autogenerated mock type for the EthereumClient type -type EthereumClient struct { - mock.Mock -} - -// CallContract provides a mock function with given fields: ctx, call, blockNumber -func (_m *EthereumClient) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, call, blockNumber) - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)); ok { - return rf(ctx, call, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) []byte); ok { - r0 = rf(ctx, call, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg, *big.Int) error); ok { - r1 = rf(ctx, call, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ChainID provides a mock function with given fields: ctx -func (_m *EthereumClient) ChainID(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// CodeAt provides a mock function with given fields: ctx, contract, blockNumber -func (_m *EthereumClient) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, contract, blockNumber) - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) ([]byte, error)); ok { - return rf(ctx, contract, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) []byte); ok { - r0 = rf(ctx, contract, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address, *big.Int) error); ok { - r1 = rf(ctx, contract, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EstimateGas provides a mock function with given fields: ctx, call -func (_m *EthereumClient) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { - ret := _m.Called(ctx, call) - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) (uint64, error)); ok { - return rf(ctx, call) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) uint64); ok { - r0 = rf(ctx, call) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg) error); ok { - r1 = rf(ctx, call) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FilterLogs provides a mock function with given fields: ctx, query -func (_m *EthereumClient) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { - ret := _m.Called(ctx, query) - - var r0 []types.Log - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) ([]types.Log, error)); ok { - return rf(ctx, query) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) []types.Log); ok { - r0 = rf(ctx, query) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Log) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery) error); ok { - r1 = rf(ctx, query) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// HeaderByNumber provides a mock function with given fields: ctx, number -func (_m *EthereumClient) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { - ret := _m.Called(ctx, number) - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// PendingCodeAt provides a mock function with given fields: ctx, account -func (_m *EthereumClient) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - ret := _m.Called(ctx, account) - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) ([]byte, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) []byte); ok { - r0 = rf(ctx, account) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// PendingNonceAt provides a mock function with given fields: ctx, account -func (_m *EthereumClient) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - ret := _m.Called(ctx, account) - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) (uint64, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) uint64); ok { - r0 = rf(ctx, account) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *EthereumClient) SendTransaction(ctx context.Context, tx *types.Transaction) error { - ret := _m.Called(ctx, tx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction) error); ok { - r0 = rf(ctx, tx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SubscribeFilterLogs provides a mock function with given fields: ctx, query, ch -func (_m *EthereumClient) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - ret := _m.Called(ctx, query, ch) - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)); ok { - return rf(ctx, query, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) ethereum.Subscription); ok { - r0 = rf(ctx, query, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) error); ok { - r1 = rf(ctx, query, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// SuggestGasPrice provides a mock function with given fields: ctx -func (_m *EthereumClient) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// SuggestGasTipCap provides a mock function with given fields: ctx -func (_m *EthereumClient) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewEthereumClient interface { - mock.TestingT - Cleanup(func()) -} - -// NewEthereumClient creates a new instance of EthereumClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewEthereumClient(t mockConstructorTestingTNewEthereumClient) *EthereumClient { - mock := &EthereumClient{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/mocks/JobResult.go b/zcnbridge/mocks/JobResult.go deleted file mode 100644 index ed7bf80fa..000000000 --- a/zcnbridge/mocks/JobResult.go +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// JobResult is an autogenerated mock type for the JobResult type -type JobResult struct { - mock.Mock -} - -// Data provides a mock function with given fields: -func (_m *JobResult) Data() interface{} { - ret := _m.Called() - - var r0 interface{} - if rf, ok := ret.Get(0).(func() interface{}); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(interface{}) - } - } - - return r0 -} - -// Error provides a mock function with given fields: -func (_m *JobResult) Error() error { - ret := _m.Called() - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// GetAuthorizerID provides a mock function with given fields: -func (_m *JobResult) GetAuthorizerID() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// SetAuthorizerID provides a mock function with given fields: ID -func (_m *JobResult) SetAuthorizerID(ID string) { - _m.Called(ID) -} - -type mockConstructorTestingTNewJobResult interface { - mock.TestingT - Cleanup(func()) -} - -// NewJobResult creates a new instance of JobResult. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewJobResult(t mockConstructorTestingTNewJobResult) *JobResult { - mock := &JobResult{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/mocks/KeyStore.go b/zcnbridge/mocks/KeyStore.go deleted file mode 100644 index be5f0130d..000000000 --- a/zcnbridge/mocks/KeyStore.go +++ /dev/null @@ -1,112 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - accounts "github.com/ethereum/go-ethereum/accounts" - keystore "github.com/ethereum/go-ethereum/accounts/keystore" - - mock "github.com/stretchr/testify/mock" - - time "time" -) - -// KeyStore is an autogenerated mock type for the KeyStore type -type KeyStore struct { - mock.Mock -} - -// Find provides a mock function with given fields: _a0 -func (_m *KeyStore) Find(_a0 accounts.Account) (accounts.Account, error) { - ret := _m.Called(_a0) - - var r0 accounts.Account - var r1 error - if rf, ok := ret.Get(0).(func(accounts.Account) (accounts.Account, error)); ok { - return rf(_a0) - } - if rf, ok := ret.Get(0).(func(accounts.Account) accounts.Account); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(accounts.Account) - } - - if rf, ok := ret.Get(1).(func(accounts.Account) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetEthereumKeyStore provides a mock function with given fields: -func (_m *KeyStore) GetEthereumKeyStore() *keystore.KeyStore { - ret := _m.Called() - - var r0 *keystore.KeyStore - if rf, ok := ret.Get(0).(func() *keystore.KeyStore); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*keystore.KeyStore) - } - } - - return r0 -} - -// SignHash provides a mock function with given fields: account, hash -func (_m *KeyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { - ret := _m.Called(account, hash) - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(accounts.Account, []byte) ([]byte, error)); ok { - return rf(account, hash) - } - if rf, ok := ret.Get(0).(func(accounts.Account, []byte) []byte); ok { - r0 = rf(account, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(accounts.Account, []byte) error); ok { - r1 = rf(account, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// TimedUnlock provides a mock function with given fields: _a0, _a1, _a2 -func (_m *KeyStore) TimedUnlock(_a0 accounts.Account, _a1 string, _a2 time.Duration) error { - ret := _m.Called(_a0, _a1, _a2) - - var r0 error - if rf, ok := ret.Get(0).(func(accounts.Account, string, time.Duration) error); ok { - r0 = rf(_a0, _a1, _a2) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewKeyStore interface { - mock.TestingT - Cleanup(func()) -} - -// NewKeyStore creates a new instance of KeyStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewKeyStore(t mockConstructorTestingTNewKeyStore) *KeyStore { - mock := &KeyStore{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/mocks/Transaction.go b/zcnbridge/mocks/Transaction.go deleted file mode 100644 index ae323f12b..000000000 --- a/zcnbridge/mocks/Transaction.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - context "context" - - transaction "github.com/0chain/gosdk/zcnbridge/transaction" - mock "github.com/stretchr/testify/mock" - - zcncore "github.com/0chain/gosdk/zcncore" -) - -// Transaction is an autogenerated mock type for the Transaction type -type Transaction struct { - mock.Mock -} - -// ExecuteSmartContract provides a mock function with given fields: ctx, address, funcName, input, val -func (_m *Transaction) ExecuteSmartContract(ctx context.Context, address string, funcName string, input interface{}, val uint64) (string, error) { - ret := _m.Called(ctx, address, funcName, input, val) - - var r0 string - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) (string, error)); ok { - return rf(ctx, address, funcName, input, val) - } - if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) string); ok { - r0 = rf(ctx, address, funcName, input, val) - } else { - r0 = ret.Get(0).(string) - } - - if rf, ok := ret.Get(1).(func(context.Context, string, string, interface{}, uint64) error); ok { - r1 = rf(ctx, address, funcName, input, val) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetCallback provides a mock function with given fields: -func (_m *Transaction) GetCallback() transaction.TransactionCallbackAwaitable { - ret := _m.Called() - - var r0 transaction.TransactionCallbackAwaitable - if rf, ok := ret.Get(0).(func() transaction.TransactionCallbackAwaitable); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(transaction.TransactionCallbackAwaitable) - } - } - - return r0 -} - -// GetHash provides a mock function with given fields: -func (_m *Transaction) GetHash() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetScheme provides a mock function with given fields: -func (_m *Transaction) GetScheme() zcncore.TransactionScheme { - ret := _m.Called() - - var r0 zcncore.TransactionScheme - if rf, ok := ret.Get(0).(func() zcncore.TransactionScheme); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(zcncore.TransactionScheme) - } - } - - return r0 -} - -// GetTransactionOutput provides a mock function with given fields: -func (_m *Transaction) GetTransactionOutput() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// SetHash provides a mock function with given fields: _a0 -func (_m *Transaction) SetHash(_a0 string) { - _m.Called(_a0) -} - -// Verify provides a mock function with given fields: ctx -func (_m *Transaction) Verify(ctx context.Context) error { - ret := _m.Called(ctx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewTransaction interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransaction(t mockConstructorTestingTNewTransaction) *Transaction { - mock := &Transaction{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/mocks/TransactionCallbackAwaitable.go b/zcnbridge/mocks/TransactionCallbackAwaitable.go deleted file mode 100644 index 9966f8fba..000000000 --- a/zcnbridge/mocks/TransactionCallbackAwaitable.go +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - - zcncore "github.com/0chain/gosdk/zcncore" -) - -// TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type -type TransactionCallbackAwaitable struct { - mock.Mock -} - -// OnAuthComplete provides a mock function with given fields: t, status -func (_m *TransactionCallbackAwaitable) OnAuthComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// OnTransactionComplete provides a mock function with given fields: t, status -func (_m *TransactionCallbackAwaitable) OnTransactionComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// OnVerifyComplete provides a mock function with given fields: t, status -func (_m *TransactionCallbackAwaitable) OnVerifyComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// WaitCompleteCall provides a mock function with given fields: ctx -func (_m *TransactionCallbackAwaitable) WaitCompleteCall(ctx context.Context) error { - ret := _m.Called(ctx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// WaitVerifyCall provides a mock function with given fields: ctx -func (_m *TransactionCallbackAwaitable) WaitVerifyCall(ctx context.Context) error { - ret := _m.Called(ctx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewTransactionCallbackAwaitable interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionCallbackAwaitable creates a new instance of TransactionCallbackAwaitable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionCallbackAwaitable(t mockConstructorTestingTNewTransactionCallbackAwaitable) *TransactionCallbackAwaitable { - mock := &TransactionCallbackAwaitable{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/mocks/TransactionProvider.go b/zcnbridge/mocks/TransactionProvider.go deleted file mode 100644 index 2ca8c875b..000000000 --- a/zcnbridge/mocks/TransactionProvider.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - transaction "github.com/0chain/gosdk/zcnbridge/transaction" - mock "github.com/stretchr/testify/mock" -) - -// TransactionProvider is an autogenerated mock type for the TransactionProvider type -type TransactionProvider struct { - mock.Mock -} - -// NewTransactionEntity provides a mock function with given fields: txnFee -func (_m *TransactionProvider) NewTransactionEntity(txnFee uint64) (transaction.Transaction, error) { - ret := _m.Called(txnFee) - - var r0 transaction.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(uint64) (transaction.Transaction, error)); ok { - return rf(txnFee) - } - if rf, ok := ret.Get(0).(func(uint64) transaction.Transaction); ok { - r0 = rf(txnFee) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(transaction.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(txnFee) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewTransactionProvider interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionProvider(t mockConstructorTestingTNewTransactionProvider) *TransactionProvider { - mock := &TransactionProvider{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/mocks/doc.go b/zcnbridge/mocks/doc.go deleted file mode 100644 index d5f5048fa..000000000 --- a/zcnbridge/mocks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// AUTOGENERATED! Do not use. -package mocks \ No newline at end of file diff --git a/zcnbridge/rest.go b/zcnbridge/rest.go deleted file mode 100644 index 326d976e3..000000000 --- a/zcnbridge/rest.go +++ /dev/null @@ -1,119 +0,0 @@ -package zcnbridge - -import ( - "fmt" - - "github.com/0chain/gosdk_common/core/common" - - "github.com/0chain/gosdk/zcnbridge/http" - "github.com/0chain/gosdk/zcnbridge/wallet" - "github.com/0chain/gosdk/zcncore" -) - -// 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"` - - // Configuration - Fee common.Balance `json:"fee"` - - // Geolocation - Latitude float64 `json:"latitude"` - Longitude float64 `json:"longitude"` - - // Stats - LastHealthCheck int64 `json:"last_health_check"` - - // 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"` -} - -// 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"` -} - -// Rest endpoints - -// getAuthorizers returns authorizers from smart contract -func getAuthorizers(active bool) ([]*AuthorizerNode, error) { - var ( - authorizers = new(AuthorizerNodesResponse) - cb = wallet.NewZCNStatus(authorizers) - err error - ) - - cb.Begin() - - if err = GetAuthorizers(active, cb); err != nil { - return nil, err - } - - if err = cb.Wait(); err != nil { - return nil, err - } - - if len(authorizers.Nodes) == 0 { - fmt.Println("no authorizers found") - return nil, err - } - - return authorizers.Nodes, nil -} - -// 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 { - return err - } - - go http.MakeSCRestAPICall( - zcncore.OpZCNSCGetAuthorizer, - http.PathGetAuthorizer, - http.Params{ - "id": id, - }, - cb, - ) - - return -} - -// 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 { - return err - } - go http.MakeSCRestAPICall(zcncore.OpZCNSCGetAuthorizerNodes, fmt.Sprintf(http.PathGetAuthorizerNodes, active), nil, cb) - return -} - -// 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 { - return err - } - go http.MakeSCRestAPICall(zcncore.OpZCNSCGetGlobalConfig, http.PathGetGlobalConfig, nil, cb) - return -} diff --git a/zcnbridge/time/doc.go b/zcnbridge/time/doc.go deleted file mode 100644 index 2feb4fd7d..000000000 --- a/zcnbridge/time/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Utility functions to handle the time. -package time diff --git a/zcnbridge/time/time.go b/zcnbridge/time/time.go deleted file mode 100644 index 2095bbe32..000000000 --- a/zcnbridge/time/time.go +++ /dev/null @@ -1,34 +0,0 @@ -package time - -import ( - "time" -) - -const ( - // RFC3339 is useful for formatting time. - RFC3339 = "2006-01-02T15:04:05Z07:00" -) - -type ( - // A Duration represents the elapsed time between two instants - // as an int64 nanosecond count. The representation limits the - // largest representable duration to approximately 290 years. - Duration = time.Duration - - // Time is a copy of time from golang std lib - // to avoid import it from other packages. - Time = time.Time - - // Timestamp represents a wrapper to control the json encoding. - Timestamp int64 -) - -// Now returns current Unix time. -func Now() Timestamp { - return Timestamp(time.Now().Unix()) -} - -// NowTime returns the current local time. -func NowTime() Time { - return time.Now() -} diff --git a/zcnbridge/transaction/callback.go b/zcnbridge/transaction/callback.go deleted file mode 100644 index 0ce4a1e1a..000000000 --- a/zcnbridge/transaction/callback.go +++ /dev/null @@ -1,89 +0,0 @@ -package transaction - -import ( - "context" - - "github.com/0chain/gosdk/zcnbridge/errors" - "github.com/0chain/gosdk/zcncore" -) - -var ( - // Ensure callback implements interface. - _ zcncore.TransactionCallback = (*callback)(nil) -) - -type ( - // TransactionCallbackAwaitable extends zcncore.TransactionCallback with synchronization methods - TransactionCallbackAwaitable interface { - zcncore.TransactionCallback - - WaitCompleteCall(ctx context.Context) error - WaitVerifyCall(ctx context.Context) error - } - - // callback implements zcncore.TransactionCallback interface. - callback struct { - // waitCh represents channel for making callback.OnTransactionComplete, - // callback.OnVerifyComplete and callBack.OnAuthComplete operations async. - waitCh chan interface{} - err error - } -) - -func NewStatus() TransactionCallbackAwaitable { - return &callback{ - waitCh: make(chan interface{}), - } -} - -// OnTransactionComplete implements zcncore.TransactionCallback interface. -func (cb *callback) OnTransactionComplete(zcnTxn *zcncore.Transaction, status int) { - if status != zcncore.StatusSuccess { - msg := "status is not success: " + TxnStatus(status).String() + "; err: " + zcnTxn.GetTransactionError() - cb.err = errors.New("on_transaction_complete", msg) - } - - cb.sendCall() -} - -// OnVerifyComplete implements zcncore.TransactionCallback interface. -func (cb *callback) OnVerifyComplete(zcnTxn *zcncore.Transaction, status int) { - if status != zcncore.StatusSuccess { - msg := "status is not success: " + TxnStatus(status).String() + "; err: " + zcnTxn.GetVerifyError() - cb.err = errors.New("on_transaction_verify", msg) - } - - cb.sendCall() -} - -// OnAuthComplete implements zcncore.TransactionCallback interface. -func (cb *callback) OnAuthComplete(_ *zcncore.Transaction, status int) { - if status != zcncore.StatusSuccess { - msg := "status is not success: " + TxnStatus(status).String() - cb.err = errors.New("on_transaction_verify", msg) - } - - cb.sendCall() -} - -func (cb *callback) WaitCompleteCall(ctx context.Context) error { - select { - case <-ctx.Done(): - return errors.New("completing_transaction", "completing transaction context deadline exceeded") - case <-cb.waitCh: - return cb.err - } -} - -func (cb *callback) WaitVerifyCall(ctx context.Context) error { - select { - case <-ctx.Done(): - return errors.New("verifying_transaction", "verifying transaction context deadline exceeded") - case <-cb.waitCh: - return cb.err - } -} - -func (cb *callback) sendCall() { - cb.waitCh <- true -} diff --git a/zcnbridge/transaction/const.go b/zcnbridge/transaction/const.go deleted file mode 100644 index 3ad2971c2..000000000 --- a/zcnbridge/transaction/const.go +++ /dev/null @@ -1,62 +0,0 @@ -package transaction - -type ( - // TxnStatus represented zcncore.TransactionCallback operations statuses. - TxnStatus int -) - -const ( - // StatusSuccess represent zcncore.StatusSuccess. - StatusSuccess TxnStatus = iota - // StatusNetworkError represent zcncore.StatusNetworkError. - StatusNetworkError - // StatusError represent zcncore.StatusError. - StatusError - // StatusRejectedByUser represent zcncore.StatusRejectedByUser. - StatusRejectedByUser - // StatusInvalidSignature represent zcncore.StatusInvalidSignature. - StatusInvalidSignature - // StatusAuthError represent zcncore.StatusAuthError. - StatusAuthError - // StatusAuthVerifyFailed represent zcncore.StatusAuthVerifyFailed. - StatusAuthVerifyFailed - // StatusAuthTimeout represent zcncore.StatusAuthTimeout. - StatusAuthTimeout - // StatusUnknown represent zcncore.StatusUnknown. - StatusUnknown = -1 -) - -// String returns represented in string format TxnStatus. -func (ts TxnStatus) String() string { - switch ts { - case StatusSuccess: - return "success" - - case StatusNetworkError: - return "network error" - - case StatusError: - return "error" - - case StatusRejectedByUser: - return "rejected byt user" - - case StatusInvalidSignature: - return "invalid signature" - - case StatusAuthError: - return "auth error" - - case StatusAuthVerifyFailed: - return "auth verify error" - - case StatusAuthTimeout: - return "auth timeout error" - - case StatusUnknown: - return "unknown" - - default: - return "" - } -} diff --git a/zcnbridge/transaction/doc.go b/zcnbridge/transaction/doc.go deleted file mode 100644 index 7c7450aee..000000000 --- a/zcnbridge/transaction/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index 07d803e36..000000000 --- a/zcnbridge/transaction/functions.go +++ /dev/null @@ -1,63 +0,0 @@ -package transaction - -// ZCNSC smart contract functions wrappers - -import ( - "context" - - "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 { - return nil, err - } - - scheme := t.GetScheme() - - err = scheme.ZCNSCAddAuthorizer(input) - if err != nil { - return t, err - } - - callBack := t.GetCallback() - - err = callBack.WaitCompleteCall(ctx) - t.SetHash(scheme.Hash()) - if err != nil { - return t, err - } - - 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 { - return nil, err - } - - scheme := t.GetScheme() - - err = scheme.ZCNSCAuthorizerHealthCheck(input) - if err != nil { - return t, err - } - - callBack := t.GetCallback() - - err = callBack.WaitCompleteCall(ctx) - t.SetHash(scheme.Hash()) - if err != nil { - return t, err - } - - return t, nil -} diff --git a/zcnbridge/transaction/mocks/Transaction.go b/zcnbridge/transaction/mocks/Transaction.go deleted file mode 100644 index ae323f12b..000000000 --- a/zcnbridge/transaction/mocks/Transaction.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - context "context" - - transaction "github.com/0chain/gosdk/zcnbridge/transaction" - mock "github.com/stretchr/testify/mock" - - zcncore "github.com/0chain/gosdk/zcncore" -) - -// Transaction is an autogenerated mock type for the Transaction type -type Transaction struct { - mock.Mock -} - -// ExecuteSmartContract provides a mock function with given fields: ctx, address, funcName, input, val -func (_m *Transaction) ExecuteSmartContract(ctx context.Context, address string, funcName string, input interface{}, val uint64) (string, error) { - ret := _m.Called(ctx, address, funcName, input, val) - - var r0 string - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) (string, error)); ok { - return rf(ctx, address, funcName, input, val) - } - if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) string); ok { - r0 = rf(ctx, address, funcName, input, val) - } else { - r0 = ret.Get(0).(string) - } - - if rf, ok := ret.Get(1).(func(context.Context, string, string, interface{}, uint64) error); ok { - r1 = rf(ctx, address, funcName, input, val) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetCallback provides a mock function with given fields: -func (_m *Transaction) GetCallback() transaction.TransactionCallbackAwaitable { - ret := _m.Called() - - var r0 transaction.TransactionCallbackAwaitable - if rf, ok := ret.Get(0).(func() transaction.TransactionCallbackAwaitable); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(transaction.TransactionCallbackAwaitable) - } - } - - return r0 -} - -// GetHash provides a mock function with given fields: -func (_m *Transaction) GetHash() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetScheme provides a mock function with given fields: -func (_m *Transaction) GetScheme() zcncore.TransactionScheme { - ret := _m.Called() - - var r0 zcncore.TransactionScheme - if rf, ok := ret.Get(0).(func() zcncore.TransactionScheme); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(zcncore.TransactionScheme) - } - } - - return r0 -} - -// GetTransactionOutput provides a mock function with given fields: -func (_m *Transaction) GetTransactionOutput() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// SetHash provides a mock function with given fields: _a0 -func (_m *Transaction) SetHash(_a0 string) { - _m.Called(_a0) -} - -// Verify provides a mock function with given fields: ctx -func (_m *Transaction) Verify(ctx context.Context) error { - ret := _m.Called(ctx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewTransaction interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransaction(t mockConstructorTestingTNewTransaction) *Transaction { - mock := &Transaction{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go b/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go deleted file mode 100644 index 9966f8fba..000000000 --- a/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" - - zcncore "github.com/0chain/gosdk/zcncore" -) - -// TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type -type TransactionCallbackAwaitable struct { - mock.Mock -} - -// OnAuthComplete provides a mock function with given fields: t, status -func (_m *TransactionCallbackAwaitable) OnAuthComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// OnTransactionComplete provides a mock function with given fields: t, status -func (_m *TransactionCallbackAwaitable) OnTransactionComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// OnVerifyComplete provides a mock function with given fields: t, status -func (_m *TransactionCallbackAwaitable) OnVerifyComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// WaitCompleteCall provides a mock function with given fields: ctx -func (_m *TransactionCallbackAwaitable) WaitCompleteCall(ctx context.Context) error { - ret := _m.Called(ctx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// WaitVerifyCall provides a mock function with given fields: ctx -func (_m *TransactionCallbackAwaitable) WaitVerifyCall(ctx context.Context) error { - ret := _m.Called(ctx) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewTransactionCallbackAwaitable interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionCallbackAwaitable creates a new instance of TransactionCallbackAwaitable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionCallbackAwaitable(t mockConstructorTestingTNewTransactionCallbackAwaitable) *TransactionCallbackAwaitable { - mock := &TransactionCallbackAwaitable{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/transaction/mocks/TransactionProvider.go b/zcnbridge/transaction/mocks/TransactionProvider.go deleted file mode 100644 index 2ca8c875b..000000000 --- a/zcnbridge/transaction/mocks/TransactionProvider.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - transaction "github.com/0chain/gosdk/zcnbridge/transaction" - mock "github.com/stretchr/testify/mock" -) - -// TransactionProvider is an autogenerated mock type for the TransactionProvider type -type TransactionProvider struct { - mock.Mock -} - -// NewTransactionEntity provides a mock function with given fields: txnFee -func (_m *TransactionProvider) NewTransactionEntity(txnFee uint64) (transaction.Transaction, error) { - ret := _m.Called(txnFee) - - var r0 transaction.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(uint64) (transaction.Transaction, error)); ok { - return rf(txnFee) - } - if rf, ok := ret.Get(0).(func(uint64) transaction.Transaction); ok { - r0 = rf(txnFee) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(transaction.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(txnFee) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewTransactionProvider interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionProvider(t mockConstructorTestingTNewTransactionProvider) *TransactionProvider { - mock := &TransactionProvider{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcnbridge/transaction/mocks/doc.go b/zcnbridge/transaction/mocks/doc.go deleted file mode 100644 index d5f5048fa..000000000 --- a/zcnbridge/transaction/mocks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// AUTOGENERATED! Do not use. -package mocks \ No newline at end of file diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go deleted file mode 100644 index ab0a1c654..000000000 --- a/zcnbridge/transaction/txn.go +++ /dev/null @@ -1,210 +0,0 @@ -package transaction - -import ( - "context" - "encoding/json" - "fmt" - "strconv" - "strings" - - "github.com/0chain/gosdk/zcnbridge/errors" - ctime "github.com/0chain/gosdk/zcnbridge/time" - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/util" -) - -var ( - _ zcncore.TransactionCallback = (*callback)(nil) -) - -type ( - // TransactionProvider ... - TransactionProvider interface { - NewTransactionEntity(txnFee uint64) (Transaction, error) - } - - // transactionProvider ... - transactionProvider struct{} - - // Transaction interface describes transaction entity. - Transaction interface { - ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) - Verify(ctx context.Context) error - GetScheme() zcncore.TransactionScheme - GetCallback() TransactionCallbackAwaitable - GetTransactionOutput() string - GetHash() string - SetHash(string) - } - - // TransactionEntity entity that encapsulates the transaction related data and metadata. - transactionEntity struct { - Hash string `json:"hash,omitempty"` - Version string `json:"version,omitempty"` - TransactionOutput string `json:"transaction_output,omitempty"` - scheme zcncore.TransactionScheme - callBack TransactionCallbackAwaitable - } -) - -type ( - verifyOutput struct { - Confirmation confirmation `json:"confirmation"` - } - - // confirmation represents the acceptance that a transaction is included into the blockchain. - confirmation struct { - Version string `json:"version"` - Hash string `json:"hash"` - BlockHash string `json:"block_hash"` - PreviousBlockHash string `json:"previous_block_hash"` - Transaction *transactionEntity `json:"txn,omitempty"` - CreationDate ctime.Timestamp `json:"creation_date"` - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - Status int `json:"transaction_status"` - RoundRandomSeed int64 `json:"round_random_seed"` - MerkleTreeRoot string `json:"merkle_tree_root"` - MerkleTreePath *util.MTPath `json:"merkle_tree_path"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` - } -) - -func NewTransactionProvider() TransactionProvider { - return &transactionProvider{} -} - -func (t *transactionProvider) NewTransactionEntity(txnFee uint64) (Transaction, error) { - return NewTransactionEntity(txnFee) -} - -// NewTransactionEntity creates Transaction with initialized fields. -// Sets version, client ID, creation date, public key and creates internal zcncore.TransactionScheme. -func NewTransactionEntity(txnFee uint64) (Transaction, error) { - txn := &transactionEntity{ - callBack: NewStatus().(*callback), - } - zcntxn, err := zcncore.NewTransaction(txn.callBack, txnFee, 0) - if err != nil { - return nil, err - } - - txn.scheme = zcntxn - - return txn, nil -} - -// ExecuteSmartContract executes function of smart contract with provided address. -// -// Returns hash of executed transaction. -func (t *transactionEntity) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, - val uint64) (string, error) { - const errCode = "transaction_send" - - tran, err := t.scheme.ExecuteSmartContract(address, funcName, input, val) - t.Hash = tran.Hash - - if err != nil { - msg := fmt.Sprintf("error while sending txn: %v", err) - return "", errors.New(errCode, msg) - } - - if err := t.callBack.WaitCompleteCall(ctx); err != nil { - msg := fmt.Sprintf("error while sending txn: %v", err) - return "", errors.New(errCode, msg) - } - - if len(t.scheme.GetTransactionError()) > 0 { - return "", errors.New(errCode, t.scheme.GetTransactionError()) - } - - return t.scheme.Hash(), nil -} - -func (t *transactionEntity) Verify(ctx context.Context) error { - const errCode = "transaction_verify" - - err := t.scheme.Verify() - if err != nil { - msg := fmt.Sprintf("error while verifying txn: %v; txn hash: %s", err, t.scheme.GetTransactionHash()) - return errors.New(errCode, msg) - } - - if err := t.callBack.WaitVerifyCall(ctx); err != nil { - msg := fmt.Sprintf("error while verifying txn: %v; txn hash: %s", err, t.scheme.GetTransactionHash()) - return errors.New(errCode, msg) - } - - switch t.scheme.GetVerifyConfirmationStatus() { - case zcncore.ChargeableError: - return errors.New(errCode, strings.Trim(t.scheme.GetVerifyOutput(), "\"")) - case zcncore.Success: - fmt.Println("Executed smart contract successfully with txn: ", t.scheme.GetTransactionHash()) - default: - msg := fmt.Sprint("\nExecute smart contract failed. Unknown status code: " + - strconv.Itoa(int(t.scheme.GetVerifyConfirmationStatus()))) - return errors.New(errCode, msg) - } - - vo := new(verifyOutput) - if err := json.Unmarshal([]byte(t.scheme.GetVerifyOutput()), vo); err != nil { - return errors.New(errCode, "error while unmarshalling confirmation: "+err.Error()+", json: "+t.scheme.GetVerifyOutput()) - } - - if vo.Confirmation.Transaction != nil { - t.Hash = vo.Confirmation.Transaction.GetHash() - t.TransactionOutput = vo.Confirmation.Transaction.GetTransactionOutput() - } else { - return errors.New(errCode, "got invalid confirmation (missing transaction)") - } - - return nil -} - -// GetSheme returns transaction scheme -func (t *transactionEntity) GetScheme() zcncore.TransactionScheme { - return t.scheme -} - -// GetHash returns transaction hash -func (t *transactionEntity) GetHash() string { - return t.Hash -} - -// SetHash sets transaction hash -func (t *transactionEntity) SetHash(hash string) { - t.Hash = hash -} - -// GetTransactionOutput returns transaction output -func (t *transactionEntity) GetTransactionOutput() string { - return t.TransactionOutput -} - -func (t *transactionEntity) GetCallback() TransactionCallbackAwaitable { - return t.callBack -} - -// GetVersion returns transaction version -func (t *transactionEntity) GetVersion() string { - return t.Version -} - -// Verify checks including of transaction in the blockchain. -func Verify(ctx context.Context, hash string) (Transaction, error) { - t, err := NewTransactionEntity(0) - if err != nil { - return nil, err - } - - scheme := t.GetScheme() - - if err := scheme.SetTransactionHash(hash); err != nil { - return nil, err - } - - err = t.Verify(ctx) - - return t, err -} diff --git a/zcnbridge/utils/convert.go b/zcnbridge/utils/convert.go deleted file mode 100644 index a3bf4d776..000000000 --- a/zcnbridge/utils/convert.go +++ /dev/null @@ -1,18 +0,0 @@ -// Miscellaneous utility functions. -package utils - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" -) - -func Encode(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) (string, string) { - x509Encoded, _ := x509.MarshalECPrivateKey(privateKey) - pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded}) - - x509EncodedPub, _ := x509.MarshalPKIXPublicKey(publicKey) - pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub}) - - return string(pemEncoded), string(pemEncodedPub) -} diff --git a/zcnbridge/wallet/doc.go b/zcnbridge/wallet/doc.go deleted file mode 100644 index ca7daf1aa..000000000 --- a/zcnbridge/wallet/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index df9b8306f..000000000 --- a/zcnbridge/wallet/status.go +++ /dev/null @@ -1,189 +0,0 @@ -package wallet - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "sync" - - "github.com/0chain/gosdk/zcncore" -) - -// ZCNStatus represents the status of a ZCN operation. -type ZCNStatus struct { - walletString string - balance int64 - value interface{} - Wg *sync.WaitGroup - Success bool - 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), - value: value, - } -} - -// 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 { - zcn.Success = true - } else { - zcn.Success = false - } - 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 { - zcn.Success = true - } else { - zcn.Err = errors.New(t.GetTransactionError()) - } -} - -// 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 { - zcn.Success = true - } else { - zcn.Err = errors.New(t.GetVerifyError()) - } -} - -// 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 { - zcn.Success = false - zcn.Err = errors.New(err) - zcn.walletString = "" - return - } - zcn.Success = true - zcn.Err = nil - 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() - - // If status is 400 for OpGetMintNonce, mintNonce is considered as 0 - if op == zcncore.OpGetMintNonce && status == http.StatusBadRequest { - zcn.Err = nil - zcn.Success = true - return - } - - if status != zcncore.StatusSuccess { - zcn.Err = errors.New(err) - zcn.Success = false - return - } - - if info == "" || info == "{}" { - zcn.Err = errors.New("empty response") - zcn.Success = false - return - } - - var errm error - if errm = json.Unmarshal([]byte(info), zcn.value); errm != nil { - zcn.Err = fmt.Errorf("decoding response: %v", errm) - zcn.Success = false - return - } - - zcn.Err = nil - 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() - - Logger.Info("Status: ", status) - Logger.Info("Timestamp:", creationDate) - Logger.Info("Signature:", signature) -} - -// 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 { - zcn.Success = false - zcn.Err = errors.New(err) - zcn.walletString = "" - return - } - zcn.Success = true - zcn.Err = nil - zcn.walletString = proposal -} - -//goland:noinspection ALL -func PrintError(v ...interface{}) { - fmt.Fprintln(os.Stderr, v...) -} - -//goland:noinspection ALL -func ExitWithError(v ...interface{}) { - fmt.Fprintln(os.Stderr, v...) - os.Exit(1) -} diff --git a/zcnbridge/wallet/wallet.go b/zcnbridge/wallet/wallet.go deleted file mode 100644 index 1f98a571e..000000000 --- a/zcnbridge/wallet/wallet.go +++ /dev/null @@ -1,33 +0,0 @@ -package wallet - -import ( - "github.com/0chain/gosdk_common/core/logger" - "gopkg.in/natefinch/lumberjack.v2" -) - -const ( - ZCNSCSmartContractAddress = "6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712e0" - MintFunc = "mint" - BurnFunc = "burn" - BurnWzcnTicketPath = "/v1/ether/burnticket/" - BurnWzcnBurnEventsPath = "/v1/ether/burnevents/" - BurnNativeTicketPath = "/v1/0chain/burnticket/" -) - -var Logger logger.Logger -var defaultLogLevel = logger.DEBUG - -func init() { - Logger.Init(defaultLogLevel, "zcnbridge-wallet-sdk") - - Logger.SetLevel(logger.DEBUG) - ioWriter := &lumberjack.Logger{ - Filename: "bridge.log", - MaxSize: 100, // MB - MaxBackups: 5, // number of backups - MaxAge: 28, //days - LocalTime: false, - Compress: false, // disabled by default - } - Logger.SetLogFile(ioWriter, true) -} diff --git a/zcnbridge/wallets/README.md b/zcnbridge/wallets/README.md deleted file mode 100644 index 9ab8bf214..000000000 --- a/zcnbridge/wallets/README.md +++ /dev/null @@ -1 +0,0 @@ -Contains Ethereum KeyStore wallets used for tests. \ No newline at end of file diff --git a/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 b/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 deleted file mode 100644 index a3590fc0a..000000000 --- a/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 +++ /dev/null @@ -1 +0,0 @@ -{"address":"d8c9156e782c68ee671c09b6b92de76c97948432","crypto":{"cipher":"aes-128-ctr","ciphertext":"7048af9fa09a3a0ca22e7ef8afea41fec8dcce848b48be8fc0d59a1f04e8581f","cipherparams":{"iv":"c97dd7cb9c554965196dd4d5bc218e0e"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"aaccc85e65af50058262ee54a2e8952a91b47d0af266e4a3558425049e77c835"},"mac":"c5ac03cbe13375c6e4c3052ff5f23f92a2c595fca6c90c3ac908b57dccd78b0a"},"id":"16c89ced-50fd-4c78-86e3-40ff440078fb","version":3} \ No newline at end of file diff --git a/zcnbridge/zcnsc/burn_event.go b/zcnbridge/zcnsc/burn_event.go deleted file mode 100644 index 152528ce4..000000000 --- a/zcnbridge/zcnsc/burn_event.go +++ /dev/null @@ -1,6 +0,0 @@ -package zcnsc - -// BurnEvent represents WZCN burn event -type BurnEvent struct { - Burneds []BurnTicket `json:"burneds"` -} diff --git a/zcnbridge/zcnsc/burn_payload.go b/zcnbridge/zcnsc/burn_payload.go deleted file mode 100644 index c5747a78f..000000000 --- a/zcnbridge/zcnsc/burn_payload.go +++ /dev/null @@ -1,18 +0,0 @@ -package zcnsc - -import "encoding/json" - -// BurnPayload Payload to submit to ZCN chain `burn` smart contract -type BurnPayload struct { - EthereumAddress string `json:"ethereum_address"` -} - -func (bp *BurnPayload) Encode() []byte { - buff, _ := json.Marshal(bp) - return buff -} - -func (bp *BurnPayload) Decode(input []byte) error { - err := json.Unmarshal(input, bp) - return err -} diff --git a/zcnbridge/zcnsc/burn_ticket.go b/zcnbridge/zcnsc/burn_ticket.go deleted file mode 100644 index 9f7169524..000000000 --- a/zcnbridge/zcnsc/burn_ticket.go +++ /dev/null @@ -1,7 +0,0 @@ -package zcnsc - -// BurnTicket represents WZCN burn ticket details -type BurnTicket struct { - TransactionHash string `json:"transactionHash"` - Nonce string `json:"nonce"` -} diff --git a/zcnbridge/zcnsc/doc.go b/zcnbridge/zcnsc/doc.go deleted file mode 100644 index 25a1aa998..000000000 --- a/zcnbridge/zcnsc/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Utilities to interact with native ZCN smart contract functions. -package zcnsc \ No newline at end of file diff --git a/zcnbridge/zcnsc/mint_payload.go b/zcnbridge/zcnsc/mint_payload.go deleted file mode 100644 index 2cecac2bf..000000000 --- a/zcnbridge/zcnsc/mint_payload.go +++ /dev/null @@ -1,26 +0,0 @@ -package zcnsc - -import ( - "encoding/json" - - "github.com/0chain/gosdk_common/core/common" -) - -// MintPayload Payload to submit to ZCN chain `mint` smart contract -type MintPayload struct { - EthereumTxnID string `json:"ethereum_txn_id"` - Amount common.Balance `json:"amount"` - Nonce int64 `json:"nonce"` - Signatures []*AuthorizerSignature `json:"signatures"` - ReceivingClientID string `json:"receiving_client_id"` -} - -type AuthorizerSignature struct { - ID string `json:"authorizer_id"` - Signature string `json:"signature"` -} - -func (mp *MintPayload) Encode() []byte { - buff, _ := json.Marshal(mp) - return buff -} diff --git a/zcncore/doc.go b/zcncore/doc.go deleted file mode 100644 index 1e9ce0fa8..000000000 --- a/zcncore/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index ec5afbb51..000000000 --- a/zcncore/ethhdwallet/hdwallet.go +++ /dev/null @@ -1,558 +0,0 @@ -// Utilities to interact with ethereum wallet. -package hdwallet - -import ( - "crypto/ecdsa" - "crypto/rand" - "errors" - "fmt" - "math/big" - "os" - "sync" - - "github.com/btcsuite/btcd/btcutil/hdkeychain" - - "github.com/btcsuite/btcd/chaincfg" - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/tyler-smith/go-bip39" -) - -// DefaultRootDerivationPath is the root path to which custom derivation endpoints -// are appended. As such, the first account will be at m/44'/60'/0'/0, the second -// at m/44'/60'/0'/1, etc. -var DefaultRootDerivationPath = accounts.DefaultRootDerivationPath - -// DefaultBaseDerivationPath is the base path from which custom derivation endpoints -// are incremented. As such, the first account will be at m/44'/60'/0'/0, the second -// at m/44'/60'/0'/1, etc -var DefaultBaseDerivationPath = accounts.DefaultBaseDerivationPath - -const issue179FixEnvar = "GO_ETHEREUM_HDWALLET_FIX_ISSUE_179" - -// Wallet is the underlying wallet struct. -type Wallet struct { - mnemonic string - masterKey *hdkeychain.ExtendedKey - seed []byte - url accounts.URL - paths map[common.Address]accounts.DerivationPath - accounts []accounts.Account - stateLock sync.RWMutex - fixIssue172 bool -} - -func newWallet(seed []byte) (*Wallet, error) { - masterKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams) - if err != nil { - return nil, err - } - - return &Wallet{ - masterKey: masterKey, - seed: seed, - accounts: []accounts.Account{}, - paths: map[common.Address]accounts.DerivationPath{}, - fixIssue172: false || len(os.Getenv(issue179FixEnvar)) > 0, - }, nil -} - -// NewFromMnemonic returns a new wallet from a BIP-39 mnemonic. -func NewFromMnemonic(mnemonic string) (*Wallet, error) { - if mnemonic == "" { - return nil, errors.New("mnemonic is required") - } - - if !bip39.IsMnemonicValid(mnemonic) { - return nil, errors.New("mnemonic is invalid") - } - - seed, err := NewSeedFromMnemonic(mnemonic) - if err != nil { - return nil, err - } - - wallet, err := newWallet(seed) - if err != nil { - return nil, err - } - wallet.mnemonic = mnemonic - - return wallet, nil -} - -// NewFromSeed returns a new wallet from a BIP-39 seed. -func NewFromSeed(seed []byte) (*Wallet, error) { - if len(seed) == 0 { - return nil, errors.New("seed is required") - } - - return newWallet(seed) -} - -// URL implements accounts.Wallet, returning the URL of the device that -// the wallet is on, however this does nothing since this is not a hardware device. -func (w *Wallet) URL() accounts.URL { - return w.url -} - -// Status implements accounts.Wallet, returning a custom status message -// from the underlying vendor-specific hardware wallet implementation, -// however this does nothing since this is not a hardware device. -func (w *Wallet) Status() (string, error) { - return "ok", nil -} - -// Open implements accounts.Wallet, however this does nothing since this -// is not a hardware device. -func (w *Wallet) Open(passphrase string) error { - return nil -} - -// Close implements accounts.Wallet, however this does nothing since this -// is not a hardware device. -func (w *Wallet) Close() error { - return nil -} - -// Accounts implements accounts.Wallet, returning the list of accounts pinned to -// the wallet. If self-derivation was enabled, the account list is -// periodically expanded based on current chain state. -func (w *Wallet) Accounts() []accounts.Account { - // Attempt self-derivation if it's running - // Return whatever account list we ended up with - w.stateLock.RLock() - defer w.stateLock.RUnlock() - - cpy := make([]accounts.Account, len(w.accounts)) - copy(cpy, w.accounts) - return cpy -} - -// Contains implements accounts.Wallet, returning whether a particular account is -// or is not pinned into this wallet instance. -func (w *Wallet) Contains(account accounts.Account) bool { - w.stateLock.RLock() - defer w.stateLock.RUnlock() - - _, exists := w.paths[account.Address] - return exists -} - -// Unpin unpins account from list of pinned accounts. -func (w *Wallet) Unpin(account accounts.Account) error { - w.stateLock.RLock() - defer w.stateLock.RUnlock() - - for i, acct := range w.accounts { - if acct.Address.String() == account.Address.String() { - w.accounts = removeAtIndex(w.accounts, i) - delete(w.paths, account.Address) - return nil - } - } - - return errors.New("account not found") -} - -// SetFixIssue172 determines whether the standard (correct) bip39 -// derivation path was used, or if derivation should be affected by -// Issue172 [0] which was how this library was originally implemented. -// [0] https://github.com/btcsuite/btcutil/pull/182/files -func (w *Wallet) SetFixIssue172(fixIssue172 bool) { - w.fixIssue172 = fixIssue172 -} - -// Derive implements accounts.Wallet, deriving a new account at the specific -// derivation path. If pin is set to true, the account will be added to the list -// of tracked accounts. -func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) { - // Try to derive the actual account and update its URL if successful - w.stateLock.RLock() // Avoid device disappearing during derivation - - address, err := w.deriveAddress(path) - - w.stateLock.RUnlock() - - // If an error occurred or no pinning was requested, return - if err != nil { - return accounts.Account{}, err - } - - account := accounts.Account{ - Address: address, - URL: accounts.URL{ - Scheme: "", - Path: path.String(), - }, - } - - if !pin { - return account, nil - } - - // Pinning needs to modify the state - w.stateLock.Lock() - defer w.stateLock.Unlock() - - if _, ok := w.paths[address]; !ok { - w.accounts = append(w.accounts, account) - w.paths[address] = path - } - - return account, nil -} - -// SelfDerive implements accounts.Wallet, trying to discover accounts that the -// user used previously (based on the chain state), but ones that he/she did not -// explicitly pin to the wallet manually. To avoid chain head monitoring, self -// derivation only runs during account listing (and even then throttled). -func (w *Wallet) SelfDerive(base []accounts.DerivationPath, chain ethereum.ChainStateReader) { - // TODO: self derivation -} - -// SignHash implements accounts.Wallet, which allows signing arbitrary data. -func (w *Wallet) SignHash(account accounts.Account, hash []byte) ([]byte, error) { - // Make sure the requested account is contained within - path, ok := w.paths[account.Address] - if !ok { - return nil, accounts.ErrUnknownAccount - } - - privateKey, err := w.derivePrivateKey(path) - if err != nil { - return nil, err - } - - return crypto.Sign(hash, privateKey) -} - -// SignTxEIP155 implements accounts.Wallet, which allows the account to sign an ERC-20 transaction. -func (w *Wallet) SignTxEIP155(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { - w.stateLock.RLock() // Comms have own mutex, this is for the state fields - defer w.stateLock.RUnlock() - - // Make sure the requested account is contained within - path, ok := w.paths[account.Address] - if !ok { - return nil, accounts.ErrUnknownAccount - } - - privateKey, err := w.derivePrivateKey(path) - if err != nil { - return nil, err - } - - signer := types.NewEIP155Signer(chainID) - // Sign the transaction and verify the sender to avoid hardware fault surprises - signedTx, err := types.SignTx(tx, signer, privateKey) - if err != nil { - return nil, err - } - - sender, err := types.Sender(signer, signedTx) - if err != nil { - return nil, err - } - - if sender != account.Address { - return nil, fmt.Errorf("signer mismatch: expected %s, got %s", account.Address.Hex(), sender.Hex()) - } - - return signedTx, nil -} - -// SignTx implements accounts.Wallet, which allows the account to sign an Ethereum transaction. -func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { - w.stateLock.RLock() // Comms have own mutex, this is for the state fields - defer w.stateLock.RUnlock() - - // Make sure the requested account is contained within - path, ok := w.paths[account.Address] - if !ok { - return nil, accounts.ErrUnknownAccount - } - - privateKey, err := w.derivePrivateKey(path) - if err != nil { - return nil, err - } - - signer := types.HomesteadSigner{} - // Sign the transaction and verify the sender to avoid hardware fault surprises - signedTx, err := types.SignTx(tx, signer, privateKey) - if err != nil { - return nil, err - } - - sender, err := types.Sender(signer, signedTx) - if err != nil { - return nil, err - } - - if sender != account.Address { - return nil, fmt.Errorf("signer mismatch: expected %s, got %s", account.Address.Hex(), sender.Hex()) - } - - return signedTx, nil -} - -// SignHashWithPassphrase implements accounts.Wallet, attempting -// to sign the given hash with the given account using the -// passphrase as extra authentication. -func (w *Wallet) SignHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) { - return w.SignHash(account, hash) -} - -// SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given -// transaction with the given account using passphrase as extra authentication. -func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { - return w.SignTx(account, tx, chainID) -} - -// PrivateKey returns the ECDSA private key of the account. -func (w *Wallet) PrivateKey(account accounts.Account) (*ecdsa.PrivateKey, error) { - path, err := ParseDerivationPath(account.URL.Path) - if err != nil { - return nil, err - } - - return w.derivePrivateKey(path) -} - -// PrivateKeyBytes returns the ECDSA private key in bytes format of the account. -func (w *Wallet) PrivateKeyBytes(account accounts.Account) ([]byte, error) { - privateKey, err := w.PrivateKey(account) - if err != nil { - return nil, err - } - - return crypto.FromECDSA(privateKey), nil -} - -// PrivateKeyHex return the ECDSA private key in hex string format of the account. -func (w *Wallet) PrivateKeyHex(account accounts.Account) (string, error) { - privateKeyBytes, err := w.PrivateKeyBytes(account) - if err != nil { - return "", err - } - - return hexutil.Encode(privateKeyBytes)[2:], nil -} - -// PublicKey returns the ECDSA public key of the account. -func (w *Wallet) PublicKey(account accounts.Account) (*ecdsa.PublicKey, error) { - path, err := ParseDerivationPath(account.URL.Path) - if err != nil { - return nil, err - } - - return w.derivePublicKey(path) -} - -// PublicKeyBytes returns the ECDSA public key in bytes format of the account. -func (w *Wallet) PublicKeyBytes(account accounts.Account) ([]byte, error) { - publicKey, err := w.PublicKey(account) - if err != nil { - return nil, err - } - - return crypto.FromECDSAPub(publicKey), nil -} - -// PublicKeyHex return the ECDSA public key in hex string format of the account. -func (w *Wallet) PublicKeyHex(account accounts.Account) (string, error) { - publicKeyBytes, err := w.PublicKeyBytes(account) - if err != nil { - return "", err - } - - return hexutil.Encode(publicKeyBytes)[4:], nil -} - -// Address returns the address of the account. -func (w *Wallet) Address(account accounts.Account) (common.Address, error) { - publicKey, err := w.PublicKey(account) - if err != nil { - return common.Address{}, err - } - - return crypto.PubkeyToAddress(*publicKey), nil -} - -// AddressBytes returns the address in bytes format of the account. -func (w *Wallet) AddressBytes(account accounts.Account) ([]byte, error) { - address, err := w.Address(account) - if err != nil { - return nil, err - } - return address.Bytes(), nil -} - -// AddressHex returns the address in hex string format of the account. -func (w *Wallet) AddressHex(account accounts.Account) (string, error) { - address, err := w.Address(account) - if err != nil { - return "", err - } - return address.Hex(), nil -} - -// Path return the derivation path of the account. -func (w *Wallet) Path(account accounts.Account) (string, error) { - return account.URL.Path, nil -} - -// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed -func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) { - // Make sure the requested account is contained within - if !w.Contains(account) { - return nil, accounts.ErrUnknownAccount - } - - return w.SignHash(account, crypto.Keccak256(data)) -} - -// SignDataWithPassphrase signs keccak256(data). The mimetype parameter describes the type of data being signed -func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) { - // Make sure the requested account is contained within - if !w.Contains(account) { - return nil, accounts.ErrUnknownAccount - } - - return w.SignHashWithPassphrase(account, passphrase, crypto.Keccak256(data)) -} - -// SignText requests the wallet to sign the hash of a given piece of data, prefixed -// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock -// the account in a keystore). -func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) { - // Make sure the requested account is contained within - if !w.Contains(account) { - return nil, accounts.ErrUnknownAccount - } - - return w.SignHash(account, accounts.TextHash(text)) -} - -// SignTextWithPassphrase implements accounts.Wallet, attempting to sign the -// given text (which is hashed) with the given account using passphrase as extra authentication. -func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) { - // Make sure the requested account is contained within - if !w.Contains(account) { - return nil, accounts.ErrUnknownAccount - } - - return w.SignHashWithPassphrase(account, passphrase, accounts.TextHash(text)) -} - -// ParseDerivationPath parses the derivation path in string format into []uint32 -func ParseDerivationPath(path string) (accounts.DerivationPath, error) { - return accounts.ParseDerivationPath(path) -} - -// MustParseDerivationPath parses the derivation path in string format into -// []uint32 but will panic if it can't parse it. -func MustParseDerivationPath(path string) accounts.DerivationPath { - parsed, err := accounts.ParseDerivationPath(path) - if err != nil { - panic(err) - } - - return parsed -} - -// NewMnemonic returns a randomly generated BIP-39 mnemonic using 128-256 bits of entropy. -func NewMnemonic(bits int) (string, error) { - entropy, err := bip39.NewEntropy(bits) - if err != nil { - return "", err - } - return bip39.NewMnemonic(entropy) -} - -// NewMnemonicFromEntropy returns a BIP-39 mnemonic from entropy. -func NewMnemonicFromEntropy(entropy []byte) (string, error) { - return bip39.NewMnemonic(entropy) -} - -// NewEntropy returns a randomly generated entropy. -func NewEntropy(bits int) ([]byte, error) { - return bip39.NewEntropy(bits) -} - -// NewSeed returns a randomly generated BIP-39 seed. -func NewSeed() ([]byte, error) { - b := make([]byte, 64) - _, err := rand.Read(b) - return b, err -} - -// NewSeedFromMnemonic returns a BIP-39 seed based on a BIP-39 mnemonic. -func NewSeedFromMnemonic(mnemonic string) ([]byte, error) { - if mnemonic == "" { - return nil, errors.New("mnemonic is required") - } - - return bip39.NewSeedWithErrorChecking(mnemonic, "") -} - -// DerivePrivateKey derives the private key of the derivation path. -func (w *Wallet) derivePrivateKey(path accounts.DerivationPath) (*ecdsa.PrivateKey, error) { - var err error - key := w.masterKey - for _, n := range path { - if w.fixIssue172 && key.IsAffectedByIssue172() { - key, err = key.Derive(n) - } else { - key, err = key.DeriveNonStandard(n) //nolint - } - if err != nil { - return nil, err - } - } - - privateKey, err := key.ECPrivKey() - privateKeyECDSA := privateKey.ToECDSA() - if err != nil { - return nil, err - } - - return privateKeyECDSA, nil -} - -// DerivePublicKey derives the public key of the derivation path. -func (w *Wallet) derivePublicKey(path accounts.DerivationPath) (*ecdsa.PublicKey, error) { - privateKeyECDSA, err := w.derivePrivateKey(path) - if err != nil { - return nil, err - } - - publicKey := privateKeyECDSA.Public() - publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey) - if !ok { - return nil, errors.New("failed to get public key") - } - - return publicKeyECDSA, nil -} - -// DeriveAddress derives the account address of the derivation path. -func (w *Wallet) deriveAddress(path accounts.DerivationPath) (common.Address, error) { - publicKeyECDSA, err := w.derivePublicKey(path) - if err != nil { - return common.Address{}, err - } - - address := crypto.PubkeyToAddress(*publicKeyECDSA) - return address, nil -} - -// removeAtIndex removes an account at index. -func removeAtIndex(accts []accounts.Account, index int) []accounts.Account { - return append(accts[:index], accts[index+1:]...) -} diff --git a/zcncore/ethhdwallet/hdwallet_test.go b/zcncore/ethhdwallet/hdwallet_test.go deleted file mode 100644 index b95f26aae..000000000 --- a/zcncore/ethhdwallet/hdwallet_test.go +++ /dev/null @@ -1,344 +0,0 @@ -package hdwallet - -import ( - "math/big" - "os" - "strings" - "testing" - - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" -) - -// TODO: table test - -func TestIssue172(t *testing.T) { - mnemonic := "sound practice disease erupt basket pumpkin truck file gorilla behave find exchange napkin boy congress address city net prosper crop chair marine chase seven" - - getWallet := func() *Wallet { - wallet, err := NewFromMnemonic(mnemonic) - if err != nil { - t.Error(err) - } - return wallet - } - - path, err := ParseDerivationPath("m/44'/60'/0'/0/0") - if err != nil { - t.Error(err) - } - - // Reset Envars - os.Setenv(issue179FixEnvar, "") - - // Derive the old (wrong way) - account, err := getWallet().Derive(path, false) - if err != nil { - t.Error(err) - } - - if account.Address.Hex() != "0x3943412CBEEEd4b68d73382b136F36b0CB82F481" { - t.Error("wrong address") - } - - // Set envar to non-zero length to derive correctly - os.Setenv(issue179FixEnvar, "1") - account, err = getWallet().Derive(path, false) - if err != nil { - t.Error(err) - } - if account.Address.Hex() != "0x98e440675eFF3041D20bECb7fE7e81746A431b6d" { - t.Error("wrong address") - } - - // Reset Envars - os.Setenv(issue179FixEnvar, "") - wallet := getWallet() - wallet.SetFixIssue172(true) - account, err = wallet.Derive(path, false) - if err != nil { - t.Error(err) - } - if account.Address.Hex() != "0x98e440675eFF3041D20bECb7fE7e81746A431b6d" { - t.Error("wrong address") - } -} - -func TestWallet(t *testing.T) { - mnemonic := "tag volcano eight thank tide danger coast health above argue embrace heavy" - wallet, err := NewFromMnemonic(mnemonic) - if err != nil { - t.Error(err) - } - // Check that Wallet implements the accounts.Wallet interface. - var _ accounts.Wallet = wallet - - path, err := ParseDerivationPath("m/44'/60'/0'/0/0") - if err != nil { - t.Error(err) - } - - account, err := wallet.Derive(path, false) - if err != nil { - t.Error(err) - } - - if account.Address.Hex() != "0xC49926C4124cEe1cbA0Ea94Ea31a6c12318df947" { - t.Error("wrong address") - } - - if len(wallet.Accounts()) != 0 { - t.Error("expected 0") - } - - account, err = wallet.Derive(path, true) - if err != nil { - t.Error(err) - } - - if len(wallet.Accounts()) != 1 { - t.Error("expected 1") - } - - if !wallet.Contains(account) { - t.Error("expected to contain account") - } - - url := wallet.URL() - if url.String() != "" { - t.Error("expected empty url") - } - - if err := wallet.Open(""); err != nil { - t.Error(err) - } - - if err := wallet.Close(); err != nil { - t.Error(err) - } - - status, err := wallet.Status() - if err != nil { - t.Error(err) - } - - if status != "ok" { - t.Error("expected status ok") - } - - accountPath, err := wallet.Path(account) - if err != nil { - t.Error(err) - } - - if accountPath != `m/44'/60'/0'/0/0` { - t.Error("wrong hdpath") - } - - privateKeyHex, err := wallet.PrivateKeyHex(account) - if err != nil { - t.Error(err) - } - - if privateKeyHex != "63e21d10fd50155dbba0e7d3f7431a400b84b4c2ac1ee38872f82448fe3ecfb9" { - t.Error("wrong private key") - } - - publicKeyHex, err := wallet.PublicKeyHex(account) - if err != nil { - t.Error(err) - } - - if publicKeyHex != "6005c86a6718f66221713a77073c41291cc3abbfcd03aa4955e9b2b50dbf7f9b6672dad0d46ade61e382f79888a73ea7899d9419becf1d6c9ec2087c1188fa18" { - t.Error("wrong public key") - } - - addressHex, err := wallet.AddressHex(account) - if err != nil { - t.Error(err) - } - - if addressHex != "0xC49926C4124cEe1cbA0Ea94Ea31a6c12318df947" { - t.Error("wrong address") - } - - nonce := uint64(0) - value := big.NewInt(1000000000000000000) - toAddress := common.HexToAddress("0x0") - gasLimit := uint64(21000) - gasPrice := big.NewInt(21000000000) - data := []byte{} - - tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, data) - - signedTx, err := wallet.SignTx(account, tx, nil) - if err != nil { - t.Error(err) - } - - v, r, s := signedTx.RawSignatureValues() - if v.Cmp(big.NewInt(0)) != 1 { - t.Error("expected v value") - } - if r.Cmp(big.NewInt(0)) != 1 { - t.Error("expected r value") - } - if s.Cmp(big.NewInt(0)) != 1 { - t.Error("expected s value") - } - - signedTx2, err := wallet.SignTxWithPassphrase(account, "", tx, nil) - if err != nil { - t.Error(err) - } - if signedTx.Hash() != signedTx2.Hash() { - t.Error("expected match") - } - - signedTx3, err := wallet.SignTxEIP155(account, tx, big.NewInt(42)) - if err != nil { - t.Error(err) - } - - v, r, s = signedTx3.RawSignatureValues() - if v.Cmp(big.NewInt(0)) != 1 { - t.Error("expected v value") - } - if r.Cmp(big.NewInt(0)) != 1 { - t.Error("expected r value") - } - if s.Cmp(big.NewInt(0)) != 1 { - t.Error("expected s value") - } - - data = []byte("hello") - hash := crypto.Keccak256Hash(data) - sig, err := wallet.SignHash(account, hash.Bytes()) - if err != nil { - t.Error(err) - } - if len(sig) == 0 { - t.Error("expected signature") - } - - sig2, err := wallet.SignHashWithPassphrase(account, "", hash.Bytes()) - if err != nil { - t.Error(err) - } - if len(sig2) == 0 { - t.Error("expected signature") - } - if hexutil.Encode(sig) != hexutil.Encode(sig2) { - t.Error("expected match") - } - - mimeType := "text/plain" - signedData, err := wallet.SignData(account, mimeType, []byte("hello world")) - if err != nil { - t.Error(err) - } - if len(signedData) == 0 { - t.Error("Expected signature") - } - - signedTextData, err := wallet.SignText(account, []byte("hello world")) - if err != nil { - t.Error(err) - } - if len(signedTextData) == 0 { - t.Error("Expected signature") - } - - signedData2, err := wallet.SignDataWithPassphrase(account, "", mimeType, []byte("hello world")) - if err != nil { - t.Error(err) - } - if len(signedData2) == 0 { - t.Error("Expected signature") - } - - signedData3, err := wallet.SignTextWithPassphrase(account, "", []byte("hello world")) - if err != nil { - t.Error(err) - } - if len(signedData3) == 0 { - t.Error("Expected signature") - } - - err = wallet.Unpin(account) - if err != nil { - t.Error(err) - } - - if wallet.Contains(account) { - t.Error("expected to not contain account") - } - - // seed test - - seed, err := NewSeedFromMnemonic(mnemonic) - if err != nil { - t.Error(err) - } - - wallet, err = NewFromSeed(seed) - if err != nil { - t.Error(err) - } - - path = MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err = wallet.Derive(path, false) - if err != nil { - t.Error(err) - } - - if account.Address.Hex() != "0xC49926C4124cEe1cbA0Ea94Ea31a6c12318df947" { - t.Error("wrong address") - } - - seed, err = NewSeed() - if err != nil { - t.Error(err) - } - - if len(seed) != 64 { - t.Error("expected size of 64") - } - - seed, err = NewSeedFromMnemonic(mnemonic) - if err != nil { - t.Error(err) - } - - if len(seed) != 64 { - t.Error("expected size of 64") - } - - mnemonic, err = NewMnemonic(128) - if err != nil { - t.Error(err) - } - - words := strings.Split(mnemonic, " ") - if len(words) != 12 { - t.Error("expected 12 words") - } - - entropy, err := NewEntropy(128) - if err != nil { - t.Error(err) - } - - mnemonic, err = NewMnemonicFromEntropy(entropy) - if err != nil { - t.Error(err) - } - - words = strings.Split(mnemonic, " ") - if len(words) != 12 { - t.Error("expected 12 words") - } -} diff --git a/zcncore/ethwallet.go b/zcncore/ethwallet.go deleted file mode 100644 index 2eea48f48..000000000 --- a/zcncore/ethwallet.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import "github.com/ethereum/go-ethereum/ethclient" - -func GetEthClient() (*ethclient.Client, error) { - return getEthClient() -} diff --git a/zcncore/ethwallet_base.go b/zcncore/ethwallet_base.go deleted file mode 100644 index 836ee0b15..000000000 --- a/zcncore/ethwallet_base.go +++ /dev/null @@ -1,315 +0,0 @@ -package zcncore - -import ( - "context" - "crypto/ecdsa" - "encoding/json" - "fmt" - "log" - "math" - "math/big" - "regexp" - "sync" - - hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/0chain/gosdk_common/core/tokenrate" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" - "golang.org/x/crypto/sha3" -) - -// TODO change to real wallets -const walletAddr = "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78" -const tokenAddress = "0x28b149020d2152179873ec60bed6bf7cd705775d" - -var once sync.Once - -var ethClient *ethclient.Client - -var getEthClient = func() (*ethclient.Client, error) { - var err error - - once.Do(func() { - if len(_config.chain.EthNode) == 0 { - err = fmt.Errorf("eth node SDK not initialized") - return - } - - logging.Info("requesting from ", _config.chain.EthNode) - ethClient, err = ethclient.Dial(_config.chain.EthNode) - }) - - return ethClient, err -} - -// TokensToEth - converting wei to eth tokens -func TokensToEth(tokens int64) float64 { - fbalance := new(big.Float) - fbalance.SetString(fmt.Sprint(tokens)) - ethValue, _ := new(big.Float).Quo(fbalance, big.NewFloat(math.Pow10(18))).Float64() - return ethValue -} - -// TokensToEth - converting eth tokens to wei -func EthToTokens(tokens float64) int64 { - return int64(tokens * float64(params.Ether)) -} - -func GTokensToEth(tokens int64) float64 { - return float64(tokens) / float64(params.GWei) -} - -func GEthToTokens(gwei float64) int64 { - return int64(gwei * float64(params.GWei)) -} - -// GetWalletAddrFromEthMnemonic - wallet ETH address from mnemoninnc -func GetWalletAddrFromEthMnemonic(mnemonic string) (string, error) { - wallet, err := hdwallet.NewFromMnemonic(mnemonic) - if err != nil { - return "", err - } - - path := hdwallet.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := wallet.Derive(path, false) - if err != nil { - return "", err - } - - privKey, err := wallet.PrivateKeyHex(account) - if err != nil { - return "", err - } - - type ethWalletinfo struct { - ID string `json:"ID"` - PrivateKey string `json:"PrivateKey"` - } - - res, err := json.Marshal(ethWalletinfo{ID: account.Address.Hex(), PrivateKey: privKey}) - return string(res), err -} - -// GetEthBalance - getting back balance for ETH wallet -func GetEthBalance(ethAddr string, cb GetBalanceCallback) error { - go func() { - value, err := getBalanceFromEthNode(ethAddr) - if err != nil { - logging.Error(err) - cb.OnBalanceAvailable(StatusError, 0, err.Error()) - return - } - cb.OnBalanceAvailable(StatusSuccess, value, "") - }() - return nil -} - -// IsValidEthAddress - multiple checks for valid ETH address -func IsValidEthAddress(ethAddr string) (bool, error) { - client, err := getEthClient() - if err != nil { - return false, err - } - - return isValidEthAddress(ethAddr, client) -} - -// 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 { - return false, err - } - - var ( - tx *types.Transaction - pending bool - ) - - tx, pending, err = client.TransactionByHash(context.Background(), common.HexToHash(txHash)) - if err != nil { - return false, err - } - return tx != nil && !pending, nil -} - -func isValidEthAddress(ethAddr string, client *ethclient.Client) (bool, error) { - re := regexp.MustCompile("^0x[0-9a-fA-F]{40}$") - if !re.MatchString(ethAddr) { - return false, fmt.Errorf("regex error") - } - - address := common.HexToAddress(ethAddr) - balance, err := client.BalanceAt(context.Background(), address, nil) - if err != nil { - return false, fmt.Errorf(err.Error()) - } - - isContract := balance.Int64() > 0 - return isContract, nil -} - -// CreateWalletFromEthMnemonic - creating new wallet from Eth mnemonics -func CreateWalletFromEthMnemonic(mnemonic, password string, statusCb WalletCallback) error { - if len(_config.chain.Miners) < 1 || len(_config.chain.Sharders) < 1 { - return fmt.Errorf("SDK not initialized") - } - go func() { - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - _, err := sigScheme.GenerateKeysWithEth(mnemonic, password) - if err != nil { - statusCb.OnWalletCreateComplete(StatusError, "", err.Error()) - return - } - }() - return nil -} - -// CheckEthHashStatus - checking the status of ETH transaction -// possible values 0 or 1 -func CheckEthHashStatus(hash string) int { - txHash := common.HexToHash(hash) - - var client *ethclient.Client - var err error - if client, err = getEthClient(); err != nil { - return -1 - } - - tx, err := client.TransactionReceipt(context.Background(), txHash) - if err != nil { - return -1 - } - return int(tx.Status) -} - -// 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 { - return 0, err - } - return f * ethRate, nil -} - -// SuggestEthGasPrice - return back suggested price for gas -func SuggestEthGasPrice() (int64, error) { - var client *ethclient.Client - var err error - if client, err = getEthClient(); err != nil { - return 0, err - } - - gasPrice, err := client.SuggestGasPrice(context.Background()) - if err != nil { - return 0, err - } - - return gasPrice.Int64(), nil -} - -// TransferEthTokens - transfer ETH tokens to multisign wallet -func TransferEthTokens(fromPrivKey string, amountTokens, gasPrice int64) (string, error) { - var client *ethclient.Client - var err error - if client, err = getEthClient(); err != nil { - return "", err - } - - privateKey, err := crypto.HexToECDSA(fromPrivKey) - if err != nil { - return "", err - } - - publicKey := privateKey.Public() - publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) - - fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) - nonce, err := client.PendingNonceAt(context.Background(), fromAddress) - if err != nil { - return "", err - } - - toAddress := common.HexToAddress(walletAddr) - tokenAddress := common.HexToAddress(tokenAddress) - - transferFnSignature := []byte("transfer(address,uint256)") - hash := sha3.NewLegacyKeccak256() - hash.Write(transferFnSignature) - methodID := hash.Sum(nil)[:4] - fmt.Println(hexutil.Encode(methodID)) // 0xa9059cbb - - paddedAddress := common.LeftPadBytes(toAddress.Bytes(), 32) - fmt.Println(hexutil.Encode(paddedAddress)) // 0x0000000000000000000000004592d8f8d7b001e72cb26a73e4fa1806a51ac79d - - amount := new(big.Int) - amount.SetInt64(amountTokens) - - paddedAmount := common.LeftPadBytes(amount.Bytes(), 32) - fmt.Println(hexutil.Encode(paddedAmount)) // 0x00000000000000000000000000000000000000000000003635c9adc5dea00000 - - var data []byte - data = append(data, methodID...) - data = append(data, paddedAddress...) - data = append(data, paddedAmount...) - - gasLimit, err := client.EstimateGas(context.Background(), ethereum.CallMsg{ - To: &tokenAddress, - Data: data, - }) - if err != nil { - log.Fatal(err) - } - - txData := &types.LegacyTx{ - Nonce: nonce, - GasPrice: big.NewInt(gasPrice), - Gas: gasLimit, - To: &tokenAddress, - Value: amount, - Data: data, - } - tx := types.NewTx(txData) - - chainID, err := client.ChainID(context.Background()) - if err != nil { - return "", err - } - - signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) - if err != nil { - return "", err - } - - err = client.SendTransaction(context.Background(), signedTx) - if err != nil { - return "", err - } - - return signedTx.Hash().Hex(), nil -} - -func getBalanceFromEthNode(ethAddr string) (int64, error) { - if client, err := getEthClient(); err == nil { - account := common.HexToAddress(ethAddr) - logging.Info("for eth address", account) - balance, err := client.BalanceAt(context.Background(), account, nil) - if err != nil { - return 0, err - } - - logging.Info("balance", balance.String()) - - return balance.Int64(), nil - } else { - return 0, err - } -} diff --git a/zcncore/ethwallet_base_test.go b/zcncore/ethwallet_base_test.go deleted file mode 100644 index 7c5925607..000000000 --- a/zcncore/ethwallet_base_test.go +++ /dev/null @@ -1,294 +0,0 @@ -package zcncore - -import ( - "context" - "math/big" - "sync" - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/consensus/ethash" - "github.com/ethereum/go-ethereum/core" - "github.com/ethereum/go-ethereum/core/rawdb" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/eth" - "github.com/ethereum/go-ethereum/eth/ethconfig" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/node" - "github.com/ethereum/go-ethereum/params" - "github.com/stretchr/testify/require" -) - -var ( - testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - testAddr = crypto.PubkeyToAddress(testKey.PublicKey) - testBalance = big.NewInt(2e15) -) - -func TestTokensConversion(t *testing.T) { - t.Run("Tokens to Eth", func(t *testing.T) { - ethTokens := TokensToEth(4337488392000000000) - require.Equal(t, 4.337488392, ethTokens) - }) - - t.Run("Eth to tokens", func(t *testing.T) { - ethTokens := EthToTokens(4.337488392) - require.Equal(t, int64(4337488392000000000), ethTokens) - }) - - t.Run("GTokens to Eth", func(t *testing.T) { - ethTokens := GTokensToEth(10000000) - require.Equal(t, 0.01, ethTokens) - }) - - t.Run("Eth to GTokens", func(t *testing.T) { - ethTokens := GEthToTokens(4.337488392) - require.Equal(t, int64(4337488392), ethTokens) - }) -} - -func TestValidEthAddress(t *testing.T) { - t.Run("Valid Eth wallet, but no balance", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - - res, err := IsValidEthAddress("0x531f9349ed2Fe5c526B47fa7841D35c90482e6cF") - require.Nil(t, err, "") - require.False(t, res, "") - }) - - t.Run("Valid Eth wallet", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - err := sendTransaction(realClient) - require.Nil(t, err) - - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - - res, err := IsValidEthAddress(testAddr.String()) - require.Nil(t, err, "") - require.True(t, res, "") - }) - - t.Run("Invalid Eth wallet", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - - res, err := IsValidEthAddress("testAddr.String()") - require.NotNil(t, err, "") - require.False(t, res, "") - }) -} - -func TestGetWalletAddrFromEthMnemonic(t *testing.T) { - t.Run("Success", func(t *testing.T) { - _config.chain.EthNode = "test" - mnemonic := "expect domain water near beauty bag pond clap chronic chronic length leisure" - res, err := GetWalletAddrFromEthMnemonic(mnemonic) - require.Nil(t, err, "") - require.Equal(t, res, "{\"ID\":\"0x531f9349ed2Fe5c526B47fa7841D35c90482e6cF\",\"PrivateKey\":\"b68bbd97a2b46b3fb2e38db771ec38935231f0b95733a4021d61601c658bc541\"}") - }) - - t.Run("Wrong", func(t *testing.T) { - _config.chain.EthNode = "test" - mnemonic := "this is wrong mnemonic" - _, err := GetWalletAddrFromEthMnemonic(mnemonic) - require.NotNil(t, err, "") - }) -} - -func TestGetEthBalance(t *testing.T) { - t.Run("Success", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - err := sendTransaction(realClient) - require.Nil(t, err) - - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - - tcb := &MockBalanceCallback{} - tcb.wg = &sync.WaitGroup{} - tcb.wg.Add(1) - err = GetEthBalance(testAddr.String(), tcb) - if err != nil { - tcb.wg.Done() - } - tcb.wg.Wait() - - require.Nil(t, err, "") - require.True(t, tcb.value > 0, "") - require.True(t, tcb.status == StatusSuccess, "") - require.True(t, tcb.info == "") - }) -} - -func TestCheckEthHashStatus(t *testing.T) { - t.Run("Pending transaction", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - err := sendTransaction(realClient) - require.Nil(t, err) - - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - result := CheckEthHashStatus("0x05aa8890d4778e292f837dd36b59a50931c175f4648c3d8157525f5454475cf7") - require.True(t, result < 0, "") - }) -} - -func TestSuggestEthGasPrice(t *testing.T) { - t.Run("suggest gas price success", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - gas, err := SuggestEthGasPrice() - require.Nil(t, err) - require.True(t, gas > 0) - }) -} - -func TestTransferEthTokens(t *testing.T) { - t.Run("success transfer", func(t *testing.T) { - _config.chain.EthNode = "test" - backend, _ := newTestBackend(t) - client, _ := backend.Attach() - defer backend.Close() - defer client.Close() - - realClient := ethclient.NewClient(client) - getEthClient = func() (*ethclient.Client, error) { - return realClient, nil - } - - hash, err := TransferEthTokens("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291", 1000000000000, 10000) - require.Nil(t, err) - require.EqualValues(t, hash, "0x43eba8525933e34908e766de93176d810e8582e886052708d44d9db157803aec") - }) -} - -type MockBalanceCallback struct { - wg *sync.WaitGroup - status int - value int64 - info string -} - -func (balCall *MockBalanceCallback) OnBalanceAvailable(status int, value int64, info string) { - defer balCall.wg.Done() - - balCall.status = status - balCall.value = value - balCall.info = info -} - -func newTestBackend(t *testing.T) (*node.Node, []*types.Block) { - // Generate test chain. - genesis, blocks := generateTestChain() - // Create node - n, err := node.New(&node.Config{}) - if err != nil { - t.Fatalf("can't create new node: %v", err) - } - // Create Ethereum Service - config := ðconfig.Config{Genesis: genesis} - config.Ethash.PowMode = ethash.ModeFake - ethservice, err := eth.New(n, config) - if err != nil { - t.Fatalf("can't create new ethereum service: %v", err) - } - // Import the test chain. - if err := n.Start(); err != nil { - t.Fatalf("can't start test node: %v", err) - } - if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil { - t.Fatalf("can't import test blocks: %v", err) - } - return n, blocks -} - -func generateTestChain() (*core.Genesis, []*types.Block) { - db := rawdb.NewMemoryDatabase() - config := params.AllEthashProtocolChanges - genesis := &core.Genesis{ - Config: config, - Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}}, - ExtraData: []byte("test genesis"), - Timestamp: 9000, - } - // BaseFee: big.NewInt(params.InitialBaseFee), - generate := func(i int, g *core.BlockGen) { - g.OffsetTime(5) - g.SetExtra([]byte("test")) - } - gblock := genesis.ToBlock() - genesis.Commit(db) //nolint: errcheck - engine := ethash.NewFaker() - blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate) - blocks = append([]*types.Block{gblock}, blocks...) - return genesis, blocks -} - -func sendTransaction(ec *ethclient.Client) error { - // Retrieve chainID - chainID, err := ec.ChainID(context.Background()) - if err != nil { - return err - } - // Create transaction - tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(1), nil) - signer := types.LatestSignerForChainID(chainID) - signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey) - if err != nil { - return err - } - signedTx, err := tx.WithSignature(signer, signature) - if err != nil { - return err - } - // Send transaction - return ec.SendTransaction(context.Background(), signedTx) -} diff --git a/zcncore/mocks/AuthCallback.go b/zcncore/mocks/AuthCallback.go deleted file mode 100644 index 555aead13..000000000 --- a/zcncore/mocks/AuthCallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// AuthCallback is an autogenerated mock type for the AuthCallback type -type AuthCallback struct { - mock.Mock -} - -// OnSetupComplete provides a mock function with given fields: status, err -func (_m *AuthCallback) OnSetupComplete(status int, err string) { - _m.Called(status, err) -} - -type mockConstructorTestingTNewAuthCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewAuthCallback creates a new instance of AuthCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewAuthCallback(t mockConstructorTestingTNewAuthCallback) *AuthCallback { - mock := &AuthCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/FeeOption.go b/zcncore/mocks/FeeOption.go deleted file mode 100644 index 34678d44b..000000000 --- a/zcncore/mocks/FeeOption.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - zcncore "github.com/0chain/gosdk/zcncore" - mock "github.com/stretchr/testify/mock" -) - -// FeeOption is an autogenerated mock type for the FeeOption type -type FeeOption struct { - mock.Mock -} - -// Execute provides a mock function with given fields: _a0 -func (_m *FeeOption) Execute(_a0 *zcncore.TxnFeeOption) { - _m.Called(_a0) -} - -type mockConstructorTestingTNewFeeOption interface { - mock.TestingT - Cleanup(func()) -} - -// NewFeeOption creates a new instance of FeeOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewFeeOption(t mockConstructorTestingTNewFeeOption) *FeeOption { - mock := &FeeOption{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/GetBalanceCallback.go b/zcncore/mocks/GetBalanceCallback.go deleted file mode 100644 index 36284afcc..000000000 --- a/zcncore/mocks/GetBalanceCallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// GetBalanceCallback is an autogenerated mock type for the GetBalanceCallback type -type GetBalanceCallback struct { - mock.Mock -} - -// OnBalanceAvailable provides a mock function with given fields: status, value, info -func (_m *GetBalanceCallback) OnBalanceAvailable(status int, value int64, info string) { - _m.Called(status, value, info) -} - -type mockConstructorTestingTNewGetBalanceCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewGetBalanceCallback creates a new instance of GetBalanceCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewGetBalanceCallback(t mockConstructorTestingTNewGetBalanceCallback) *GetBalanceCallback { - mock := &GetBalanceCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/GetInfoCallback.go b/zcncore/mocks/GetInfoCallback.go deleted file mode 100644 index 5d62dee17..000000000 --- a/zcncore/mocks/GetInfoCallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// GetInfoCallback is an autogenerated mock type for the GetInfoCallback type -type GetInfoCallback struct { - mock.Mock -} - -// OnInfoAvailable provides a mock function with given fields: op, status, info, err -func (_m *GetInfoCallback) OnInfoAvailable(op int, status int, info string, err string) { - _m.Called(op, status, info, err) -} - -type mockConstructorTestingTNewGetInfoCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewGetInfoCallback creates a new instance of GetInfoCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewGetInfoCallback(t mockConstructorTestingTNewGetInfoCallback) *GetInfoCallback { - mock := &GetInfoCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/GetNonceCallback.go b/zcncore/mocks/GetNonceCallback.go deleted file mode 100644 index d18111569..000000000 --- a/zcncore/mocks/GetNonceCallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// GetNonceCallback is an autogenerated mock type for the GetNonceCallback type -type GetNonceCallback struct { - mock.Mock -} - -// OnNonceAvailable provides a mock function with given fields: status, nonce, info -func (_m *GetNonceCallback) OnNonceAvailable(status int, nonce int64, info string) { - _m.Called(status, nonce, info) -} - -type mockConstructorTestingTNewGetNonceCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewGetNonceCallback creates a new instance of GetNonceCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewGetNonceCallback(t mockConstructorTestingTNewGetNonceCallback) *GetNonceCallback { - mock := &GetNonceCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/MSVoteCallback.go b/zcncore/mocks/MSVoteCallback.go deleted file mode 100644 index 0100e83ee..000000000 --- a/zcncore/mocks/MSVoteCallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// MSVoteCallback is an autogenerated mock type for the MSVoteCallback type -type MSVoteCallback struct { - mock.Mock -} - -// OnVoteComplete provides a mock function with given fields: status, proposal, err -func (_m *MSVoteCallback) OnVoteComplete(status int, proposal string, err string) { - _m.Called(status, proposal, err) -} - -type mockConstructorTestingTNewMSVoteCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewMSVoteCallback creates a new instance of MSVoteCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewMSVoteCallback(t mockConstructorTestingTNewMSVoteCallback) *MSVoteCallback { - mock := &MSVoteCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/QueryResultHandle.go b/zcncore/mocks/QueryResultHandle.go deleted file mode 100644 index de84a6e22..000000000 --- a/zcncore/mocks/QueryResultHandle.go +++ /dev/null @@ -1,42 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - zcncore "github.com/0chain/gosdk/zcncore" - mock "github.com/stretchr/testify/mock" -) - -// QueryResultHandle is an autogenerated mock type for the QueryResultHandle type -type QueryResultHandle struct { - mock.Mock -} - -// Execute provides a mock function with given fields: result -func (_m *QueryResultHandle) Execute(result zcncore.QueryResult) bool { - ret := _m.Called(result) - - var r0 bool - if rf, ok := ret.Get(0).(func(zcncore.QueryResult) bool); ok { - r0 = rf(result) - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -type mockConstructorTestingTNewQueryResultHandle interface { - mock.TestingT - Cleanup(func()) -} - -// NewQueryResultHandle creates a new instance of QueryResultHandle. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewQueryResultHandle(t mockConstructorTestingTNewQueryResultHandle) *QueryResultHandle { - mock := &QueryResultHandle{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/TransactionCallback.go b/zcncore/mocks/TransactionCallback.go deleted file mode 100644 index c51628063..000000000 --- a/zcncore/mocks/TransactionCallback.go +++ /dev/null @@ -1,43 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - zcncore "github.com/0chain/gosdk/zcncore" - mock "github.com/stretchr/testify/mock" -) - -// TransactionCallback is an autogenerated mock type for the TransactionCallback type -type TransactionCallback struct { - mock.Mock -} - -// OnAuthComplete provides a mock function with given fields: t, status -func (_m *TransactionCallback) OnAuthComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// OnTransactionComplete provides a mock function with given fields: t, status -func (_m *TransactionCallback) OnTransactionComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -// OnVerifyComplete provides a mock function with given fields: t, status -func (_m *TransactionCallback) OnVerifyComplete(t *zcncore.Transaction, status int) { - _m.Called(t, status) -} - -type mockConstructorTestingTNewTransactionCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionCallback creates a new instance of TransactionCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionCallback(t mockConstructorTestingTNewTransactionCallback) *TransactionCallback { - mock := &TransactionCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/TransactionCommon.go b/zcncore/mocks/TransactionCommon.go deleted file mode 100644 index 36734b3cd..000000000 --- a/zcncore/mocks/TransactionCommon.go +++ /dev/null @@ -1,595 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - transaction "github.com/0chain/gosdk_common/core/transaction" - mock "github.com/stretchr/testify/mock" - - zcncore "github.com/0chain/gosdk/zcncore" -) - -// TransactionCommon is an autogenerated mock type for the TransactionCommon type -type TransactionCommon struct { - mock.Mock -} - -// AddHardfork provides a mock function with given fields: ip -func (_m *TransactionCommon) AddHardfork(ip *zcncore.InputMap) error { - ret := _m.Called(ip) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(ip) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// CancelAllocation provides a mock function with given fields: allocID -func (_m *TransactionCommon) CancelAllocation(allocID string) error { - ret := _m.Called(allocID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(allocID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// CreateAllocation provides a mock function with given fields: car, lock -func (_m *TransactionCommon) CreateAllocation(car *zcncore.CreateAllocationRequest, lock uint64) error { - ret := _m.Called(car, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.CreateAllocationRequest, uint64) error); ok { - r0 = rf(car, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// CreateReadPool provides a mock function with given fields: -func (_m *TransactionCommon) CreateReadPool() error { - ret := _m.Called() - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ExecuteSmartContract provides a mock function with given fields: address, methodName, input, val, feeOpts -func (_m *TransactionCommon) ExecuteSmartContract(address string, methodName string, input interface{}, val uint64, feeOpts ...zcncore.FeeOption) (*transaction.Transaction, error) { - _va := make([]interface{}, len(feeOpts)) - for _i := range feeOpts { - _va[_i] = feeOpts[_i] - } - var _ca []interface{} - _ca = append(_ca, address, methodName, input, val) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) - - var r0 *transaction.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) (*transaction.Transaction, error)); ok { - return rf(address, methodName, input, val, feeOpts...) - } - if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) *transaction.Transaction); ok { - r0 = rf(address, methodName, input, val, feeOpts...) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*transaction.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) error); ok { - r1 = rf(address, methodName, input, val, feeOpts...) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FaucetUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionCommon) FaucetUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// FinalizeAllocation provides a mock function with given fields: allocID -func (_m *TransactionCommon) FinalizeAllocation(allocID string) error { - ret := _m.Called(allocID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(allocID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// GetVerifyConfirmationStatus provides a mock function with given fields: -func (_m *TransactionCommon) GetVerifyConfirmationStatus() zcncore.ConfirmationStatus { - ret := _m.Called() - - var r0 zcncore.ConfirmationStatus - if rf, ok := ret.Get(0).(func() zcncore.ConfirmationStatus); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(zcncore.ConfirmationStatus) - } - - return r0 -} - -// MinerSCCollectReward provides a mock function with given fields: providerID, providerType -func (_m *TransactionCommon) MinerSCCollectReward(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCDeleteMiner provides a mock function with given fields: _a0 -func (_m *TransactionCommon) MinerSCDeleteMiner(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCDeleteSharder provides a mock function with given fields: _a0 -func (_m *TransactionCommon) MinerSCDeleteSharder(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCKill provides a mock function with given fields: providerID, providerType -func (_m *TransactionCommon) MinerSCKill(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCLock provides a mock function with given fields: providerId, providerType, lock -func (_m *TransactionCommon) MinerSCLock(providerId string, providerType zcncore.Provider, lock uint64) error { - ret := _m.Called(providerId, providerType, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { - r0 = rf(providerId, providerType, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCMinerSettings provides a mock function with given fields: _a0 -func (_m *TransactionCommon) MinerSCMinerSettings(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCSharderSettings provides a mock function with given fields: _a0 -func (_m *TransactionCommon) MinerSCSharderSettings(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCUnlock provides a mock function with given fields: providerId, providerType -func (_m *TransactionCommon) MinerSCUnlock(providerId string, providerType zcncore.Provider) error { - ret := _m.Called(providerId, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerId, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerScUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionCommon) MinerScUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerScUpdateGlobals provides a mock function with given fields: _a0 -func (_m *TransactionCommon) MinerScUpdateGlobals(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ReadPoolLock provides a mock function with given fields: allocID, blobberID, duration, lock -func (_m *TransactionCommon) ReadPoolLock(allocID string, blobberID string, duration int64, lock uint64) error { - ret := _m.Called(allocID, blobberID, duration, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { - r0 = rf(allocID, blobberID, duration, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ReadPoolUnlock provides a mock function with given fields: -func (_m *TransactionCommon) ReadPoolUnlock() error { - ret := _m.Called() - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// RegisterMultiSig provides a mock function with given fields: walletstr, mswallet -func (_m *TransactionCommon) RegisterMultiSig(walletstr string, mswallet string) error { - ret := _m.Called(walletstr, mswallet) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(walletstr, mswallet) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Send provides a mock function with given fields: toClientID, val, desc -func (_m *TransactionCommon) Send(toClientID string, val uint64, desc string) error { - ret := _m.Called(toClientID, val, desc) - - var r0 error - if rf, ok := ret.Get(0).(func(string, uint64, string) error); ok { - r0 = rf(toClientID, val, desc) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StakePoolLock provides a mock function with given fields: providerId, providerType, lock -func (_m *TransactionCommon) StakePoolLock(providerId string, providerType zcncore.Provider, lock uint64) error { - ret := _m.Called(providerId, providerType, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { - r0 = rf(providerId, providerType, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StakePoolUnlock provides a mock function with given fields: providerId, providerType -func (_m *TransactionCommon) StakePoolUnlock(providerId string, providerType zcncore.Provider) error { - ret := _m.Called(providerId, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerId, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StorageSCCollectReward provides a mock function with given fields: providerID, providerType -func (_m *TransactionCommon) StorageSCCollectReward(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StorageScUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionCommon) StorageScUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpdateAllocation provides a mock function with given fields: allocID, sizeDiff, expirationDiff, lock -func (_m *TransactionCommon) UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock uint64) error { - ret := _m.Called(allocID, sizeDiff, expirationDiff, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, int64, int64, uint64) error); ok { - r0 = rf(allocID, sizeDiff, expirationDiff, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpdateBlobberSettings provides a mock function with given fields: blobber -func (_m *TransactionCommon) UpdateBlobberSettings(blobber *zcncore.Blobber) error { - ret := _m.Called(blobber) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.Blobber) error); ok { - r0 = rf(blobber) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpdateValidatorSettings provides a mock function with given fields: validator -func (_m *TransactionCommon) UpdateValidatorSettings(validator *zcncore.Validator) error { - ret := _m.Called(validator) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.Validator) error); ok { - r0 = rf(validator) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingAdd provides a mock function with given fields: ar, value -func (_m *TransactionCommon) VestingAdd(ar *zcncore.VestingAddRequest, value uint64) error { - ret := _m.Called(ar, value) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.VestingAddRequest, uint64) error); ok { - r0 = rf(ar, value) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionCommon) VestingUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// WritePoolLock provides a mock function with given fields: allocID, blobberID, duration, lock -func (_m *TransactionCommon) WritePoolLock(allocID string, blobberID string, duration int64, lock uint64) error { - ret := _m.Called(allocID, blobberID, duration, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { - r0 = rf(allocID, blobberID, duration, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// WritePoolUnlock provides a mock function with given fields: allocID -func (_m *TransactionCommon) WritePoolUnlock(allocID string) error { - ret := _m.Called(allocID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(allocID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCAddAuthorizer provides a mock function with given fields: _a0 -func (_m *TransactionCommon) ZCNSCAddAuthorizer(_a0 *zcncore.AddAuthorizerPayload) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.AddAuthorizerPayload) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCAuthorizerHealthCheck provides a mock function with given fields: _a0 -func (_m *TransactionCommon) ZCNSCAuthorizerHealthCheck(_a0 *zcncore.AuthorizerHealthCheckPayload) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerHealthCheckPayload) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCCollectReward provides a mock function with given fields: providerID, providerType -func (_m *TransactionCommon) ZCNSCCollectReward(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCDeleteAuthorizer provides a mock function with given fields: _a0 -func (_m *TransactionCommon) ZCNSCDeleteAuthorizer(_a0 *zcncore.DeleteAuthorizerPayload) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.DeleteAuthorizerPayload) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCUpdateAuthorizerConfig provides a mock function with given fields: _a0 -func (_m *TransactionCommon) ZCNSCUpdateAuthorizerConfig(_a0 *zcncore.AuthorizerNode) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerNode) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCUpdateGlobalConfig provides a mock function with given fields: _a0 -func (_m *TransactionCommon) ZCNSCUpdateGlobalConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewTransactionCommon interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionCommon creates a new instance of TransactionCommon. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionCommon(t mockConstructorTestingTNewTransactionCommon) *TransactionCommon { - mock := &TransactionCommon{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/TransactionScheme.go b/zcncore/mocks/TransactionScheme.go deleted file mode 100644 index 95fb2fbab..000000000 --- a/zcncore/mocks/TransactionScheme.go +++ /dev/null @@ -1,835 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import ( - transaction "github.com/0chain/gosdk_common/core/transaction" - mock "github.com/stretchr/testify/mock" - - zcncore "github.com/0chain/gosdk/zcncore" -) - -// TransactionScheme is an autogenerated mock type for the TransactionScheme type -type TransactionScheme struct { - mock.Mock -} - -// AddHardfork provides a mock function with given fields: ip -func (_m *TransactionScheme) AddHardfork(ip *zcncore.InputMap) error { - ret := _m.Called(ip) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(ip) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// CancelAllocation provides a mock function with given fields: allocID -func (_m *TransactionScheme) CancelAllocation(allocID string) error { - ret := _m.Called(allocID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(allocID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// CreateAllocation provides a mock function with given fields: car, lock -func (_m *TransactionScheme) CreateAllocation(car *zcncore.CreateAllocationRequest, lock uint64) error { - ret := _m.Called(car, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.CreateAllocationRequest, uint64) error); ok { - r0 = rf(car, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// CreateReadPool provides a mock function with given fields: -func (_m *TransactionScheme) CreateReadPool() error { - ret := _m.Called() - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ExecuteFaucetSCWallet provides a mock function with given fields: walletStr, methodName, input -func (_m *TransactionScheme) ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error { - ret := _m.Called(walletStr, methodName, input) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string, []byte) error); ok { - r0 = rf(walletStr, methodName, input) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ExecuteSmartContract provides a mock function with given fields: address, methodName, input, val, feeOpts -func (_m *TransactionScheme) ExecuteSmartContract(address string, methodName string, input interface{}, val uint64, feeOpts ...zcncore.FeeOption) (*transaction.Transaction, error) { - _va := make([]interface{}, len(feeOpts)) - for _i := range feeOpts { - _va[_i] = feeOpts[_i] - } - var _ca []interface{} - _ca = append(_ca, address, methodName, input, val) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) - - var r0 *transaction.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) (*transaction.Transaction, error)); ok { - return rf(address, methodName, input, val, feeOpts...) - } - if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) *transaction.Transaction); ok { - r0 = rf(address, methodName, input, val, feeOpts...) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*transaction.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) error); ok { - r1 = rf(address, methodName, input, val, feeOpts...) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FaucetUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionScheme) FaucetUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// FinalizeAllocation provides a mock function with given fields: allocID -func (_m *TransactionScheme) FinalizeAllocation(allocID string) error { - ret := _m.Called(allocID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(allocID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// GetTransactionError provides a mock function with given fields: -func (_m *TransactionScheme) GetTransactionError() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetTransactionHash provides a mock function with given fields: -func (_m *TransactionScheme) GetTransactionHash() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetTransactionNonce provides a mock function with given fields: -func (_m *TransactionScheme) GetTransactionNonce() int64 { - ret := _m.Called() - - var r0 int64 - if rf, ok := ret.Get(0).(func() int64); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(int64) - } - - return r0 -} - -// GetVerifyConfirmationStatus provides a mock function with given fields: -func (_m *TransactionScheme) GetVerifyConfirmationStatus() zcncore.ConfirmationStatus { - ret := _m.Called() - - var r0 zcncore.ConfirmationStatus - if rf, ok := ret.Get(0).(func() zcncore.ConfirmationStatus); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(zcncore.ConfirmationStatus) - } - - return r0 -} - -// GetVerifyError provides a mock function with given fields: -func (_m *TransactionScheme) GetVerifyError() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// GetVerifyOutput provides a mock function with given fields: -func (_m *TransactionScheme) GetVerifyOutput() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// Hash provides a mock function with given fields: -func (_m *TransactionScheme) Hash() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// MinerSCCollectReward provides a mock function with given fields: providerID, providerType -func (_m *TransactionScheme) MinerSCCollectReward(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCDeleteMiner provides a mock function with given fields: _a0 -func (_m *TransactionScheme) MinerSCDeleteMiner(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCDeleteSharder provides a mock function with given fields: _a0 -func (_m *TransactionScheme) MinerSCDeleteSharder(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCKill provides a mock function with given fields: providerID, providerType -func (_m *TransactionScheme) MinerSCKill(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCLock provides a mock function with given fields: providerId, providerType, lock -func (_m *TransactionScheme) MinerSCLock(providerId string, providerType zcncore.Provider, lock uint64) error { - ret := _m.Called(providerId, providerType, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { - r0 = rf(providerId, providerType, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCMinerSettings provides a mock function with given fields: _a0 -func (_m *TransactionScheme) MinerSCMinerSettings(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCSharderSettings provides a mock function with given fields: _a0 -func (_m *TransactionScheme) MinerSCSharderSettings(_a0 *zcncore.MinerSCMinerInfo) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerSCUnlock provides a mock function with given fields: providerId, providerType -func (_m *TransactionScheme) MinerSCUnlock(providerId string, providerType zcncore.Provider) error { - ret := _m.Called(providerId, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerId, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerScUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionScheme) MinerScUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MinerScUpdateGlobals provides a mock function with given fields: _a0 -func (_m *TransactionScheme) MinerScUpdateGlobals(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Output provides a mock function with given fields: -func (_m *TransactionScheme) Output() []byte { - ret := _m.Called() - - var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - return r0 -} - -// ReadPoolLock provides a mock function with given fields: allocID, blobberID, duration, lock -func (_m *TransactionScheme) ReadPoolLock(allocID string, blobberID string, duration int64, lock uint64) error { - ret := _m.Called(allocID, blobberID, duration, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { - r0 = rf(allocID, blobberID, duration, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ReadPoolUnlock provides a mock function with given fields: -func (_m *TransactionScheme) ReadPoolUnlock() error { - ret := _m.Called() - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// RegisterMultiSig provides a mock function with given fields: walletstr, mswallet -func (_m *TransactionScheme) RegisterMultiSig(walletstr string, mswallet string) error { - ret := _m.Called(walletstr, mswallet) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string) error); ok { - r0 = rf(walletstr, mswallet) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Send provides a mock function with given fields: toClientID, val, desc -func (_m *TransactionScheme) Send(toClientID string, val uint64, desc string) error { - ret := _m.Called(toClientID, val, desc) - - var r0 error - if rf, ok := ret.Get(0).(func(string, uint64, string) error); ok { - r0 = rf(toClientID, val, desc) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SetTransactionCallback provides a mock function with given fields: cb -func (_m *TransactionScheme) SetTransactionCallback(cb zcncore.TransactionCallback) error { - ret := _m.Called(cb) - - var r0 error - if rf, ok := ret.Get(0).(func(zcncore.TransactionCallback) error); ok { - r0 = rf(cb) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SetTransactionHash provides a mock function with given fields: hash -func (_m *TransactionScheme) SetTransactionHash(hash string) error { - ret := _m.Called(hash) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(hash) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SetTransactionNonce provides a mock function with given fields: txnNonce -func (_m *TransactionScheme) SetTransactionNonce(txnNonce int64) error { - ret := _m.Called(txnNonce) - - var r0 error - if rf, ok := ret.Get(0).(func(int64) error); ok { - r0 = rf(txnNonce) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StakePoolLock provides a mock function with given fields: providerId, providerType, lock -func (_m *TransactionScheme) StakePoolLock(providerId string, providerType zcncore.Provider, lock uint64) error { - ret := _m.Called(providerId, providerType, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { - r0 = rf(providerId, providerType, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StakePoolUnlock provides a mock function with given fields: providerId, providerType -func (_m *TransactionScheme) StakePoolUnlock(providerId string, providerType zcncore.Provider) error { - ret := _m.Called(providerId, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerId, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StorageSCCollectReward provides a mock function with given fields: providerID, providerType -func (_m *TransactionScheme) StorageSCCollectReward(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StorageScUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionScheme) StorageScUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// StoreData provides a mock function with given fields: data -func (_m *TransactionScheme) StoreData(data string) error { - ret := _m.Called(data) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(data) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpdateAllocation provides a mock function with given fields: allocID, sizeDiff, expirationDiff, lock -func (_m *TransactionScheme) UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock uint64) error { - ret := _m.Called(allocID, sizeDiff, expirationDiff, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, int64, int64, uint64) error); ok { - r0 = rf(allocID, sizeDiff, expirationDiff, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpdateBlobberSettings provides a mock function with given fields: blobber -func (_m *TransactionScheme) UpdateBlobberSettings(blobber *zcncore.Blobber) error { - ret := _m.Called(blobber) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.Blobber) error); ok { - r0 = rf(blobber) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// UpdateValidatorSettings provides a mock function with given fields: validator -func (_m *TransactionScheme) UpdateValidatorSettings(validator *zcncore.Validator) error { - ret := _m.Called(validator) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.Validator) error); ok { - r0 = rf(validator) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Verify provides a mock function with given fields: -func (_m *TransactionScheme) Verify() error { - ret := _m.Called() - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingAdd provides a mock function with given fields: ar, value -func (_m *TransactionScheme) VestingAdd(ar *zcncore.VestingAddRequest, value uint64) error { - ret := _m.Called(ar, value) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.VestingAddRequest, uint64) error); ok { - r0 = rf(ar, value) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingDelete provides a mock function with given fields: poolID -func (_m *TransactionScheme) VestingDelete(poolID string) error { - ret := _m.Called(poolID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(poolID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingStop provides a mock function with given fields: sr -func (_m *TransactionScheme) VestingStop(sr *zcncore.VestingStopRequest) error { - ret := _m.Called(sr) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.VestingStopRequest) error); ok { - r0 = rf(sr) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingTrigger provides a mock function with given fields: poolID -func (_m *TransactionScheme) VestingTrigger(poolID string) error { - ret := _m.Called(poolID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(poolID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingUnlock provides a mock function with given fields: poolID -func (_m *TransactionScheme) VestingUnlock(poolID string) error { - ret := _m.Called(poolID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(poolID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// VestingUpdateConfig provides a mock function with given fields: _a0 -func (_m *TransactionScheme) VestingUpdateConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// WritePoolLock provides a mock function with given fields: allocID, blobberID, duration, lock -func (_m *TransactionScheme) WritePoolLock(allocID string, blobberID string, duration int64, lock uint64) error { - ret := _m.Called(allocID, blobberID, duration, lock) - - var r0 error - if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { - r0 = rf(allocID, blobberID, duration, lock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// WritePoolUnlock provides a mock function with given fields: allocID -func (_m *TransactionScheme) WritePoolUnlock(allocID string) error { - ret := _m.Called(allocID) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(allocID) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCAddAuthorizer provides a mock function with given fields: _a0 -func (_m *TransactionScheme) ZCNSCAddAuthorizer(_a0 *zcncore.AddAuthorizerPayload) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.AddAuthorizerPayload) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCAuthorizerHealthCheck provides a mock function with given fields: _a0 -func (_m *TransactionScheme) ZCNSCAuthorizerHealthCheck(_a0 *zcncore.AuthorizerHealthCheckPayload) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerHealthCheckPayload) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCCollectReward provides a mock function with given fields: providerID, providerType -func (_m *TransactionScheme) ZCNSCCollectReward(providerID string, providerType zcncore.Provider) error { - ret := _m.Called(providerID, providerType) - - var r0 error - if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { - r0 = rf(providerID, providerType) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCDeleteAuthorizer provides a mock function with given fields: _a0 -func (_m *TransactionScheme) ZCNSCDeleteAuthorizer(_a0 *zcncore.DeleteAuthorizerPayload) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.DeleteAuthorizerPayload) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCUpdateAuthorizerConfig provides a mock function with given fields: _a0 -func (_m *TransactionScheme) ZCNSCUpdateAuthorizerConfig(_a0 *zcncore.AuthorizerNode) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerNode) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ZCNSCUpdateGlobalConfig provides a mock function with given fields: _a0 -func (_m *TransactionScheme) ZCNSCUpdateGlobalConfig(_a0 *zcncore.InputMap) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewTransactionScheme interface { - mock.TestingT - Cleanup(func()) -} - -// NewTransactionScheme creates a new instance of TransactionScheme. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionScheme(t mockConstructorTestingTNewTransactionScheme) *TransactionScheme { - mock := &TransactionScheme{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/WalletCallback.go b/zcncore/mocks/WalletCallback.go deleted file mode 100644 index 06b0ea6db..000000000 --- a/zcncore/mocks/WalletCallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by mockery v2.28.1. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// WalletCallback is an autogenerated mock type for the WalletCallback type -type WalletCallback struct { - mock.Mock -} - -// OnWalletCreateComplete provides a mock function with given fields: status, wallet, err -func (_m *WalletCallback) OnWalletCreateComplete(status int, wallet string, err string) { - _m.Called(status, wallet, err) -} - -type mockConstructorTestingTNewWalletCallback interface { - mock.TestingT - Cleanup(func()) -} - -// NewWalletCallback creates a new instance of WalletCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewWalletCallback(t mockConstructorTestingTNewWalletCallback) *WalletCallback { - mock := &WalletCallback{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zcncore/mocks/doc.go b/zcncore/mocks/doc.go deleted file mode 100644 index d5f5048fa..000000000 --- a/zcncore/mocks/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// AUTOGENERATED! Do not use. -package mocks \ No newline at end of file diff --git a/zcncore/mswallet.go b/zcncore/mswallet.go deleted file mode 100644 index ad483ba5f..000000000 --- a/zcncore/mswallet.go +++ /dev/null @@ -1,207 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "encoding/json" - "fmt" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -//MSVote -- this should mimic the type Vote defined in MultiSig SC -type MSVote struct { - ProposalID string `json:"proposal_id"` - - // Client ID in transfer is that of the multi-sig wallet, not the signer. - Transfer MSTransfer `json:"transfer"` - - Signature string `json:"signature"` -} - -//MSTransfer - a data structure to hold state transfer from one client to another -type MSTransfer struct { - ClientID string `json:"from"` - ToClientID string `json:"to"` - Amount uint64 `json:"amount"` -} - -// MultisigSCWallet --this should mimic MultisigWallet definition in MultiSig SC -type MultisigSCWallet struct { - ClientID string `json:"client_id"` - SignatureScheme string `json:"signature_scheme"` - PublicKey string `json:"public_key"` - - SignerThresholdIDs []string `json:"signer_threshold_ids"` - SignerPublicKeys []string `json:"signer_public_keys"` - - NumRequired int `json:"num_required"` -} - -// MSWallet Client data necessary for a multi-sig wallet. -type MSWallet struct { - Id int `json:"id"` - SignatureScheme string `json:"signature_scheme"` - GroupClientID string `json:"group_client_id"` - GroupKey zcncrypto.SignatureScheme `json:"group_key"` - SignerClientIDs []string `json:"sig_client_ids"` - SignerKeys []zcncrypto.SignatureScheme `json:"signer_keys"` - T int `json:"threshold"` - N int `json:"num_subkeys"` -} - -func (msw *MSWallet) UnmarshalJSON(data []byte) error { - m := &struct { - Id int `json:"id"` - SignatureScheme string `json:"signature_scheme"` - GroupClientID string `json:"group_client_id"` - SignerClientIDs []string `json:"sig_client_ids"` - T int `json:"threshold"` - N int `json:"num_subkeys"` - GroupKey interface{} `json:"group_key"` - SignerKeys interface{} `json:"signer_keys"` - }{} - - if err := json.Unmarshal(data, &m); err != nil { - return err - } - - msw.Id = m.Id - msw.SignatureScheme = m.SignatureScheme - msw.GroupClientID = m.GroupClientID - msw.SignerClientIDs = m.SignerClientIDs - msw.T = m.T - msw.N = m.N - - if m.GroupKey != nil { - groupKeyBuf, err := json.Marshal(m.GroupKey) - if err != nil { - return err - } - - ss := zcncrypto.NewSignatureScheme(m.SignatureScheme) - - if err := json.Unmarshal(groupKeyBuf, &ss); err != nil { - return err - } - - msw.GroupKey = ss - } - - signerKeys, err := zcncrypto.UnmarshalSignatureSchemes(m.SignatureScheme, m.SignerKeys) - if err != nil { - return err - } - msw.SignerKeys = signerKeys - - return nil -} - -// Marshal returns json string -func (msw *MSWallet) Marshal() (string, error) { - msws, err := json.Marshal(msw) - if err != nil { - return "", errors.New("", "Invalid Wallet") - } - return string(msws), nil -} - -//GetMultisigPayload given a multisig wallet as a string, makes a multisig wallet payload to register -func GetMultisigPayload(mswstr string) (interface{}, error) { - var msw MSWallet - err := json.Unmarshal([]byte(mswstr), &msw) - - if err != nil { - fmt.Printf("Error while creating multisig wallet from input:\n%v", mswstr) - return "", err - } - var signerThresholdIDs []string - var signerPublicKeys []string - - for _, scheme := range msw.SignerKeys { - signerThresholdIDs = append(signerThresholdIDs, scheme.GetID()) - signerPublicKeys = append(signerPublicKeys, scheme.GetPublicKey()) - } - - msscw := MultisigSCWallet{ - ClientID: msw.GroupClientID, - SignatureScheme: msw.SignatureScheme, - PublicKey: msw.GroupKey.GetPublicKey(), - - SignerThresholdIDs: signerThresholdIDs, - SignerPublicKeys: signerPublicKeys, - - NumRequired: msw.T, - } - - return msscw, nil -} - -//GetMultisigVotePayload given a multisig vote as a string, makes a multisig vote payload to register -func GetMultisigVotePayload(msvstr string) (interface{}, error) { - var msv MSVote - err := json.Unmarshal([]byte(msvstr), &msv) - - if err != nil { - fmt.Printf("Error while creating multisig wallet from input:\n%v", msvstr) - return nil, err - } - - //Marshalling and unmarshalling validates the string. Do any additional veirfication here. - - return msv, nil - -} - -// CreateMSVote create a vote for multisig -func CreateMSVote(proposal, grpClientID, signerWalletstr, toClientID string, token uint64) (string, error) { - if proposal == "" || grpClientID == "" || toClientID == "" || signerWalletstr == "" { - return "", errors.New("", "proposal or groupClient or signer wallet or toClientID cannot be empty") - } - - if token < 1 { - return "", errors.New("", "Token cannot be less than 1") - } - - signerWallet, err := getWallet(signerWalletstr) - if err != nil { - fmt.Printf("Error while parsing the signer wallet. %v", err) - return "", err - } - - //Note: Is this honored by multisig sc? - transfer := MSTransfer{ - ClientID: grpClientID, - ToClientID: toClientID, - Amount: token, - } - - buff, _ := json.Marshal(transfer) - hash := encryption.Hash(buff) - - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - if err := sigScheme.SetPrivateKey(signerWallet.Keys[0].PrivateKey); err != nil { - return "", err - } - - sig, err := sigScheme.Sign(hash) - if err != nil { - return "", err - } - - vote := MSVote{ - Transfer: transfer, - ProposalID: proposal, - Signature: sig, - } - - vbytes, err := json.Marshal(vote) - if err != nil { - fmt.Printf("error in marshalling vote %v", vote) - return "", err - } - return string(vbytes), nil -} diff --git a/zcncore/mswallet_base.go b/zcncore/mswallet_base.go deleted file mode 100644 index e13191507..000000000 --- a/zcncore/mswallet_base.go +++ /dev/null @@ -1,132 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "encoding/hex" - "fmt" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -// MSVoteCallback callback definition multisig Vote function -type MSVoteCallback interface { - OnVoteComplete(status int, proposal string, err string) -} - -// CreateMSWallet returns multisig wallet information -func CreateMSWallet(t, n int) (string, string, []string, error) { - if t < 1 || t > n { - return "", "", nil, errors.New("bls0_generate_threshold_key_shares", fmt.Sprintf("Given threshold (%d) is less than 1 or greater than numsigners (%d)", t, n)) - } - - id := 0 - if _config.chain.SignatureScheme != "bls0chain" { - return "", "", nil, errors.New("", "encryption scheme for this blockchain is not bls0chain") - - } - - groupKey := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - wallet, err := groupKey.GenerateKeys() - if err != nil { - return "", "", nil, err - } - - logging.Info(fmt.Sprintf("Wallet id: %s", wallet.ClientKey)) - - groupClientID := GetClientID(groupKey.GetPublicKey()) - //Code modified to directly use BLS0ChainThresholdScheme - signerKeys, err := zcncrypto.GenerateThresholdKeyShares(t, n, groupKey) - - if err != nil { - return "", "", nil, errors.Wrap(err, "Err in generateThresholdKeyShares") - } - var signerClientIDs []string - for _, key := range signerKeys { - signerClientIDs = append(signerClientIDs, GetClientID(key.GetPublicKey())) - } - - msw := MSWallet{ - Id: id, - SignatureScheme: _config.chain.SignatureScheme, - GroupClientID: groupClientID, - GroupKey: groupKey, - SignerClientIDs: signerClientIDs, - SignerKeys: signerKeys, - T: t, - N: n, - } - - wallets, errw := getWallets(msw) - - if errw != nil { - return "", "", nil, errw - - } - smsw, er := msw.Marshal() - if er != nil { - return "", "", nil, er - } - return smsw, groupClientID, wallets, nil - -} - -func getWallets(msw MSWallet) ([]string, error) { - - wallets := make([]string, 0, msw.N+1) - - b0ss := msw.GroupKey - - grw, err := makeWallet(b0ss.GetPrivateKey(), b0ss.GetPublicKey(), b0ss.GetMnemonic()) - - if err != nil { - return nil, err - } - - wallets = append(wallets, grw) - - for _, signer := range msw.SignerKeys { - w, err := makeWallet(signer.GetPrivateKey(), signer.GetPublicKey(), "") - if err != nil { - return nil, err - } - wallets = append(wallets, w) - } - return wallets, nil -} - -func makeWallet(privateKey, publicKey, mnemonic string) (string, error) { - w := &zcncrypto.Wallet{} - w.Keys = make([]zcncrypto.KeyPair, 1) - w.Keys[0].PrivateKey = privateKey - w.Keys[0].PublicKey = publicKey - w.ClientID = GetClientID(publicKey) //VerifyThis - w.ClientKey = publicKey - w.Mnemonic = mnemonic - w.Version = zcncrypto.CryptoVersion - w.DateCreated = time.Now().Format(time.RFC3339) - - return w.Marshal() -} - -// GetClientID -- computes Client ID from publickey -func GetClientID(pkey string) string { - publicKeyBytes, err := hex.DecodeString(pkey) - if err != nil { - panic(err) - } - - return encryption.Hash(publicKeyBytes) -} - -func GetClientWalletKey() string { - return _config.wallet.ClientKey -} - -func GetClientWalletID() string { - return _config.wallet.ClientID -} diff --git a/zcncore/mswallet_mobile.go b/zcncore/mswallet_mobile.go deleted file mode 100644 index 97d39bc5a..000000000 --- a/zcncore/mswallet_mobile.go +++ /dev/null @@ -1,282 +0,0 @@ -//go:build mobile -// +build mobile - -package zcncore - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -type MultisigSCWallet interface { - GetClientID() string - GetSignatureScheme() string - GetPublicKey() string - GetNumRequired() int - GetSignerThresholdIDs() Stringers - GetSignerPublicKeys() Stringers -} - -// Stringers wraps the methods for accessing string slice -type Stringers interface { - Len() int // return the number of string slice - Get(i int) (string, error) // get string of given index -} - -// stringSlice implements the Stringers interface -type stringSlice []string - -func (ss stringSlice) Len() int { - return len(ss) -} - -func (ss stringSlice) Get(i int) (string, error) { - if i < 0 || i >= len(ss) { - return "", errors.New("index out of bounds") - } - return ss[i], nil -} - -//GetMultisigPayload given a multisig wallet as a string, makes a multisig wallet payload to register -func GetMultisigPayload(mswstr string) (MultisigSCWallet, error) { - var msw msWallet - err := json.Unmarshal([]byte(mswstr), &msw) - if err != nil { - return nil, err - } - - var signerThresholdIDs []string - var signerPublicKeys []string - - for _, scheme := range msw.SignerKeys { - signerThresholdIDs = append(signerThresholdIDs, scheme.GetID()) - signerPublicKeys = append(signerPublicKeys, scheme.GetPublicKey()) - } - - return &multisigSCWallet{ - ClientID: msw.GroupClientID, - SignatureScheme: msw.SignatureScheme, - PublicKey: msw.GroupKey.GetPublicKey(), - - SignerThresholdIDs: signerThresholdIDs, - SignerPublicKeys: signerPublicKeys, - - NumRequired: msw.T, - }, nil -} - -type multisigSCWallet struct { - ClientID string `json:"client_id"` - SignatureScheme string `json:"signature_scheme"` - PublicKey string `json:"public_key"` - - SignerThresholdIDs []string `json:"signer_threshold_ids"` - SignerPublicKeys []string `json:"signer_public_keys"` - - NumRequired int `json:"num_required"` -} - -func (m *multisigSCWallet) GetClientID() string { - return m.ClientID -} - -func (m *multisigSCWallet) GetSignatureScheme() string { - return m.SignatureScheme -} - -func (m *multisigSCWallet) GetPublicKey() string { - return m.PublicKey -} - -func (m *multisigSCWallet) GetSignerThresholdIDs() Stringers { - return stringSlice(m.SignerThresholdIDs) -} - -func (m *multisigSCWallet) GetSignerPublicKeys() Stringers { - return stringSlice(m.SignerPublicKeys) -} - -func (m *multisigSCWallet) GetNumRequired() int { - return m.NumRequired -} - -type msWallet struct { - Id int `json:"id"` - SignatureScheme string `json:"signature_scheme"` - GroupClientID string `json:"group_client_id"` - GroupKey zcncrypto.SignatureScheme `json:"group_key"` - SignerClientIDs []string `json:"sig_client_ids"` - SignerKeys []zcncrypto.SignatureScheme `json:"signer_keys"` - T int `json:"threshold"` - N int `json:"num_subkeys"` -} - -func (msw *msWallet) UnmarshalJSON(data []byte) error { - m := &struct { - Id int `json:"id"` - SignatureScheme string `json:"signature_scheme"` - GroupClientID string `json:"group_client_id"` - SignerClientIDs []string `json:"sig_client_ids"` - T int `json:"threshold"` - N int `json:"num_subkeys"` - GroupKey interface{} `json:"group_key"` - SignerKeys interface{} `json:"signer_keys"` - }{} - - if err := json.Unmarshal(data, &m); err != nil { - return err - } - - msw.Id = m.Id - msw.SignatureScheme = m.SignatureScheme - msw.GroupClientID = m.GroupClientID - msw.SignerClientIDs = m.SignerClientIDs - msw.T = m.T - msw.N = m.N - - if m.GroupKey != nil { - groupKeyBuf, err := json.Marshal(m.GroupKey) - if err != nil { - return err - } - - ss := zcncrypto.NewSignatureScheme(m.SignatureScheme) - - if err := json.Unmarshal(groupKeyBuf, &ss); err != nil { - return err - } - - msw.GroupKey = ss - } - - signerKeys, err := zcncrypto.UnmarshalSignatureSchemes(m.SignatureScheme, m.SignerKeys) - if err != nil { - return err - } - msw.SignerKeys = signerKeys - - return nil -} - -// Marshal returns json string -func (msw *msWallet) Marshal() (string, error) { - msws, err := json.Marshal(msw) - if err != nil { - return "", errors.New("invalid wallet") - } - return string(msws), nil -} - -type MSVote interface { - GetProposalID() string - GetSignature() string - GetTransferClientID() string - GetTransferToClientID() string - GetTransferAmount() string -} - -type msVote struct { - ProposalID string `json:"proposal_id"` - - // Client ID in transfer is that of the multi-sig wallet, not the signer. - Transfer msTransfer `json:"transfer"` - - Signature string `json:"signature"` -} - -func (m *msVote) GetProposalID() string { - return m.ProposalID -} - -func (m *msVote) GetTransferClientID() string { - return m.Transfer.ClientID -} - -func (m *msVote) GetTransferToClientID() string { - return m.Transfer.ToClientID -} - -func (m *msVote) GetTransferAmount() string { - return strconv.FormatUint(m.Transfer.Amount, 10) -} - -func (m *msVote) GetSignature() string { - return m.Signature -} - -//msTransfer - a data structure to hold state transfer from one client to another -type msTransfer struct { - ClientID string `json:"from"` - ToClientID string `json:"to"` - Amount uint64 `json:"amount"` -} - -//GetMultisigVotePayload given a multisig vote as a string, makes a multisig vote payload to register -func GetMultisigVotePayload(msvstr string) (MSVote, error) { - var msv msVote - err := json.Unmarshal([]byte(msvstr), &msv) - if err != nil { - return nil, err - } - - return &msv, nil -} - -// CreateMSVote create a vote for multisig -func CreateMSVote(proposal, grpClientID, signerWalletstr, toClientID string, tokenStr string) (string, error) { - if proposal == "" || grpClientID == "" || toClientID == "" || signerWalletstr == "" { - return "", errors.New("proposal or groupClient or signer wallet or toClientID cannot be empty") - } - - token, err := strconv.ParseUint(tokenStr, 10, 64) - if err != nil { - return "", err - } - - if token < 1 { - return "", errors.New("token cannot be less than 1") - } - - signerWallet, err := getWallet(signerWalletstr) - if err != nil { - return "", err - } - - //Note: Is this honored by multisig sc? - transfer := msTransfer{ - ClientID: grpClientID, - ToClientID: toClientID, - Amount: token, - } - - buff, _ := json.Marshal(transfer) - hash := encryption.Hash(buff) - - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - if err := sigScheme.SetPrivateKey(signerWallet.Keys[0].PrivateKey); err != nil { - return "", err - } - - sig, err := sigScheme.Sign(hash) - if err != nil { - return "", err - } - - vote := msVote{ - Transfer: transfer, - ProposalID: proposal, - Signature: sig, - } - - vbytes, err := json.Marshal(vote) - if err != nil { - fmt.Printf("error in marshalling vote %v", vote) - return "", err - } - return string(vbytes), nil -} diff --git a/zcncore/networkworker.go b/zcncore/networkworker.go deleted file mode 100644 index 23fd7d991..000000000 --- a/zcncore/networkworker.go +++ /dev/null @@ -1,157 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "context" - "encoding/json" - "net/http" - "reflect" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/node" - "github.com/0chain/gosdk_common/core/util" - "go.uber.org/zap" -) - -const NETWORK_ENDPOINT = "/network" - -var networkWorkerTimerInHours = 1 - -// Network details of the network nodes -type Network struct { - Miners []string `json:"miners"` - Sharders []string `json:"sharders"` -} - -func updateNetworkDetailsWorker(ctx context.Context) { - ticker := time.NewTicker(time.Duration(networkWorkerTimerInHours) * time.Hour) - for { - select { - case <-ctx.Done(): - logging.Info("Network stopped by user") - return - case <-ticker.C: - err := UpdateNetworkDetails() - if err != nil { - logging.Error("Update network detail worker fail", zap.Error(err)) - return - } - logging.Info("Successfully updated network details") - return - } - } -} - -func UpdateNetworkDetails() error { - networkDetails, err := GetNetworkDetails() - if err != nil { - logging.Error("Failed to update network details ", zap.Error(err)) - return err - } - - shouldUpdate := UpdateRequired(networkDetails) - if shouldUpdate { - _config.isConfigured = false - _config.chain.Miners = networkDetails.Miners - _config.chain.Sharders = networkDetails.Sharders - consensus := _config.chain.SharderConsensous - if consensus < conf.DefaultSharderConsensous { - consensus = conf.DefaultSharderConsensous - } - if len(networkDetails.Sharders) < consensus { - consensus = len(networkDetails.Sharders) - } - - Sharders = node.NewHolder(networkDetails.Sharders, consensus) - node.InitCache(Sharders) - conf.InitChainNetwork(&conf.Network{ - Sharders: networkDetails.Sharders, - Miners: networkDetails.Miners, - }) - _config.isConfigured = true - } - return nil -} - -func UpdateRequired(networkDetails *Network) bool { - miners := _config.chain.Miners - sharders := _config.chain.Sharders - if len(miners) == 0 || len(sharders) == 0 { - return true - } - - minerSame := reflect.DeepEqual(miners, networkDetails.Miners) - sharderSame := reflect.DeepEqual(sharders, networkDetails.Sharders) - - if minerSame && sharderSame { - return false - } - return true -} - -func GetNetworkDetails() (*Network, error) { - req, err := util.NewHTTPGetRequest(_config.chain.BlockWorker + NETWORK_ENDPOINT) - if err != nil { - return nil, errors.New("get_network_details_error", "Unable to create new http request with error "+err.Error()) - } - - res, err := req.Get() - if err != nil { - return nil, errors.New("get_network_details_error", "Unable to get http request with error "+err.Error()) - } - - if res.StatusCode != http.StatusOK { - return nil, errors.New("get_network_details_error", "Unable to get http request with "+res.Status) - - } - var networkResponse Network - err = json.Unmarshal([]byte(res.Body), &networkResponse) - if err != nil { - return nil, errors.Wrap(err, "Error unmarshaling response :"+res.Body) - } - return &networkResponse, nil - -} - -// GetNetwork retrieve the registered network details. -func GetNetwork() *Network { - return &Network{ - Miners: _config.chain.Miners, - Sharders: _config.chain.Sharders, - } -} - -// 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 - - consensus := _config.chain.SharderConsensous - if consensus < conf.DefaultSharderConsensous { - consensus = conf.DefaultSharderConsensous - } - if len(sharders) < consensus { - consensus = len(sharders) - } - - Sharders = node.NewHolder(sharders, consensus) - node.InitCache(Sharders) - - conf.InitChainNetwork(&conf.Network{ - Miners: miners, - Sharders: sharders, - }) -} - -// GetNetworkJSON retrieve the registered network details in JSON format. -func GetNetworkJSON() string { - network := GetNetwork() - networkBytes, _ := json.Marshal(network) - return string(networkBytes) -} diff --git a/zcncore/networkworker_mobile.go b/zcncore/networkworker_mobile.go deleted file mode 100644 index d1bed08fd..000000000 --- a/zcncore/networkworker_mobile.go +++ /dev/null @@ -1,172 +0,0 @@ -//go:build mobile -// +build mobile - -package zcncore - -import ( - "context" - "encoding/json" - "reflect" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/node" - "github.com/0chain/gosdk_common/core/util" - "go.uber.org/zap" -) - -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) -} - -type network struct { - Miners []string `json:"miners"` - Sharders []string `json:"sharders"` -} - -func updateNetworkDetailsWorker(ctx context.Context) { - ticker := time.NewTicker(time.Duration(networkWorkerTimerInHours) * time.Hour) - for { - select { - case <-ctx.Done(): - logging.Info("Network stopped by user") - return - case <-ticker.C: - err := UpdateNetworkDetails() - if err != nil { - logging.Error("Update network detail worker fail", zap.Error(err)) - return - } - logging.Info("Successfully updated network details") - return - } - } -} - -// UpdateNetworkDetails update network details -func UpdateNetworkDetails() error { - networkDetails, err := GetNetworkDetails() - if err != nil { - logging.Error("Failed to update network details ", zap.Error(err)) - return err - } - - shouldUpdate := UpdateRequired(networkDetails) - if shouldUpdate { - _config.isConfigured = false - _config.chain.Miners = networkDetails.net.Miners - _config.chain.Sharders = networkDetails.net.Sharders - consensus := _config.chain.SharderConsensous - if consensus < conf.DefaultSharderConsensous { - consensus = conf.DefaultSharderConsensous - } - if len(networkDetails.net.Sharders) < consensus { - consensus = len(networkDetails.net.Sharders) - } - - Sharders = node.NewHolder(networkDetails.net.Sharders, consensus) - node.InitCache(Sharders) - conf.InitChainNetwork(&conf.Network{ - Sharders: networkDetails.net.Sharders, - Miners: networkDetails.net.Miners, - }) - _config.isConfigured = true - } - return nil -} - -func UpdateRequired(networkDetails *Network) bool { - miners := _config.chain.Miners - sharders := _config.chain.Sharders - if len(miners) == 0 || len(sharders) == 0 { - return true - } - - minerSame := reflect.DeepEqual(miners, networkDetails.net.Miners) - sharderSame := reflect.DeepEqual(sharders, networkDetails.net.Sharders) - - if minerSame && sharderSame { - return false - } - return true -} - -func GetNetworkDetails() (*Network, error) { - req, err := util.NewHTTPGetRequest(_config.chain.BlockWorker + NETWORK_ENDPOINT) - if err != nil { - return nil, errors.New("get_network_details_error", "Unable to create new http request with error "+err.Error()) - } - - res, err := req.Get() - if err != nil { - return nil, errors.New("get_network_details_error", "Unable to get http request with error "+err.Error()) - } - - var networkResponse network - err = json.Unmarshal([]byte(res.Body), &networkResponse) - if err != nil { - return nil, errors.Wrap(err, "Error unmarshaling response :") - } - return &Network{net: networkResponse}, nil -} - -// GetNetwork - get network details -func GetNetwork() *Network { - return &Network{ - net: network{ - Miners: _config.chain.Miners, - Sharders: _config.chain.Sharders, - }, - } -} - -// SetNetwork set network details -// - net: network details -func SetNetwork(net *Network) { - _config.chain.Miners = net.net.Miners - _config.chain.Sharders = net.net.Sharders - - consensus := _config.chain.SharderConsensous - if consensus < conf.DefaultSharderConsensous { - consensus = conf.DefaultSharderConsensous - } - if len(net.net.Sharders) < consensus { - consensus = len(net.net.Sharders) - } - - Sharders = node.NewHolder(_config.chain.Sharders, consensus) - - node.InitCache(Sharders) - - conf.InitChainNetwork(&conf.Network{ - Miners: net.net.Miners, - Sharders: net.net.Sharders, - }) -} - -func GetNetworkJSON() string { - network := GetNetwork() - networkBytes, _ := json.Marshal(network) - return string(networkBytes) -} diff --git a/zcncore/sample/0Wallet.go b/zcncore/sample/0Wallet.go deleted file mode 100644 index 07f109b25..000000000 --- a/zcncore/sample/0Wallet.go +++ /dev/null @@ -1,257 +0,0 @@ -//go:build ignore -// +build ignore - -// Sample usage of the Wallet SDK - do not use. -package main - -import ( - "encoding/json" - "flag" - "fmt" - "sync" - - "github.com/0chain/gosdk/zcncore" -) - -type StatusUI struct { - i int - wg sync.WaitGroup - txnout map[string]json.RawMessage -} - -// const ChainConfig = `{ -// "miners": [ -// "http://localhost:7071", -// "http://localhost:7072", -// "http://localhost:7073" -// ], -// "sharders": [ -// "http://localhost:7171" -// ], -// "signaturescheme": "bls0chain" -// }` - -const ChainConfig = `{ - "miners": [ - "http://ohio.devi.testnet-0chain.net:7071", - "http://ohio.devi.testnet-0chain.net:7072", - "http://ohio.devi.testnet-0chain.net:7073", - "http://ohio.devi.testnet-0chain.net:7074" - ], - "sharders": [ - "http://ohio.devi.testnet-0chain.net:7171" - ], - "signaturescheme": "bls0chain" -}` - -var wallet = ` -{"client_id":"0bc96a0980170045863d826f9eb579d8144013210602e88426408e9f83c236f6", -"client_key":"a4e58c66b072d27288b650db9a476fe66a1a4f69e0f8fb11499f9ec3a579e21e5dc0298b8c5ae5baa205730d06bc04b07a31943ab3bd620e8427c15d5c413b9e", -"keys":[ - { - "public_key":"a4e58c66b072d27288b650db9a476fe66a1a4f69e0f8fb11499f9ec3a579e21e5dc0298b8c5ae5baa205730d06bc04b07a31943ab3bd620e8427c15d5c413b9e", - "private_key":"c0f3a3100241888ea9c2cc5c7300e3e510a8e7190c2c20b03f80e3937a91530d" - }], -"mnemonics":"snake mixed bird cream cotton trouble small fee finger catalog measure spoon private second canal pact unable close predict dream mask delay path inflict", -"version":"1.0", -"date_created":"2019-06-19 13:37:50.466889 -0700 PDT m=+0.023873276"}` - -func (s *StatusUI) OnWalletCreateComplete(status int, w string, err string) { - defer s.wg.Done() - if status == zcncore.StatusError { - fmt.Println("Error: ", err) - } else { - fmt.Println("Wallet:", w) - } -} - -func (s *StatusUI) OnTransactionComplete(t *zcncore.Transaction, status int) { - defer s.wg.Done() - fmt.Println("========== TxnCompleted Status: ", status, "=======") - fmt.Println(" Txn Hash:", t.GetTransactionHash()) -} - -func (s *StatusUI) OnVerifyComplete(t *zcncore.Transaction, status int) { - defer s.wg.Done() - fmt.Println("========== VerifyCompleted Status: ", status, "=======") - fmt.Println(t.GetVerifyOutput()) -} - -func (s *StatusUI) OnBalanceAvailable(status int, value int64) { - defer s.wg.Done() - fmt.Println("=========== Balance Status:", status, "Value:", value, - "Token:", zcncore.ConvertToToken(value), - "Value:", zcncore.ConvertToValue(zcncore.ConvertToToken(value))) -} - -func (zcn *StatusUI) OnAuthComplete(t *zcncore.Transaction, status int) { - fmt.Println("Authorization complete on zauth.", status) -} - -func main() { - var cmd string - flag.StringVar(&cmd, "cmd", "", "create|recover|validate|send|store|faucet|getbalance|verify") - - var mnemonic string - flag.StringVar(&mnemonic, "mnemonic", "", "Mnemonic used for wallet creation.\nMandatory for -cmd recover") - - var value uint64 - flag.Uint64Var(&value, "value", 0, "Value to send") - - var txnhash string - flag.StringVar(&txnhash, "txnhash", "", "Transaction hash to verify.\nMandatory for -cmd verify") - - var txndata string - flag.StringVar(&txndata, "txndata", "", "Data to store.\nMandatory for -cmd store") - - var toclientID string - flag.StringVar(&toclientID, "toclientID", "", "Receipient client ID.\nMandatory for -cmd send") - - flag.Parse() - - switch cmd { - case "create": - case "faucet": - case "getbalance": - case "recover": - fallthrough - case "validate": - if mnemonic == "" { - flag.Usage() - return - } - case "send": - if value == 0 && toclientID == "" { - flag.Usage() - return - } - case "verify": - if txnhash == "" { - flag.Usage() - return - } - case "store": - if txndata == "" { - flag.Usage() - return - } - default: - fmt.Println("Unsupported command:", cmd) - flag.Usage() - return - } - - err := zcncore.Init(ChainConfig) - if err != nil { - fmt.Println("Init failed") - return - } - err = zcncore.SetWalletInfo(wallet, false) - if err != nil { - fmt.Println("set wallet info failed: ", err) - return - } - - s := &StatusUI{i: 1} - switch cmd { - case "create": - s.wg.Add(1) - err = zcncore.CreateWallet(s) - if err != nil { - fmt.Printf("Error create wallet: %v\n", err) - } - s.wg.Wait() - case "recover": - s.wg.Add(1) - err = zcncore.RecoverWallet(mnemonic, s) - if err != nil { - fmt.Printf("Error recover wallet %v\n", err) - } - s.wg.Wait() - case "validate": - ok := zcncore.IsMnemonicValid(mnemonic) - if ok != true { - fmt.Println("Validate mnemonic failed") - return - } - fmt.Println("**** Mnemonic is Valid ****") - case "send": - txn, err := zcncore.NewTransaction(s, 0, 0) - if err != nil { - fmt.Println(err) - return - } - s.wg.Add(1) - err = txn.Send(toclientID, value, "From 0Wallet sample app") - if err != nil { - fmt.Println("send failed: ", err) - return - } - s.wg.Wait() - s.wg.Add(1) - txn.Verify() - s.wg.Wait() - case "store": - txn, err := zcncore.NewTransaction(s, 0, 0) - if err != nil { - fmt.Println(err) - return - } - s.wg.Add(1) - err = txn.StoreData(txndata) - if err != nil { - fmt.Printf("store data failed: %v\n", err) - return - } - s.wg.Wait() - s.wg.Add(1) - txn.Verify() - s.wg.Wait() - case "faucet": - txn, err := zcncore.NewTransaction(s, 0, 0) - if err != nil { - fmt.Println(err) - return - } - s.wg.Add(1) - faucetAddress := "faucet smart contract address" - methodName := "pour" - jsonInput := "{}" - value = 0 - err = txn.ExecuteSmartContract(faucetAddress, methodName, jsonInput, value) - if err != nil { - fmt.Printf("execute faucet smart contract failed: %v\n", err) - return - } - s.wg.Wait() - s.wg.Add(1) - txn.Verify() - s.wg.Wait() - case "getbalance": - s.wg.Add(1) - err = zcncore.GetBalance(nil) - if err != nil { - fmt.Println("get balance failed: ", err) - return - } - s.wg.Wait() - case "getnonce": - s.wg.Add(1) - err = zcncore.GetNonce(nil) - if err != nil { - fmt.Println("get balance failed: ", err) - return - } - s.wg.Wait() - case "verify": - txn, err := zcncore.NewTransaction(s, 0, 0) - if err != nil { - fmt.Println(err) - return - } - txn.SetTransactionHash(txnhash) - s.wg.Add(1) - txn.Verify() - s.wg.Wait() - } -} diff --git a/zcncore/sample/snapshot_test.go b/zcncore/sample/snapshot_test.go deleted file mode 100644 index 84176319a..000000000 --- a/zcncore/sample/snapshot_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package sample - -import ( - "fmt" - "sync" - "testing" - - "github.com/0chain/gosdk/zcnbridge/wallet" - "github.com/0chain/gosdk/zcncore" -) - -type BlobberAggregate struct { - BlobberID string `json:"blobber_id" gorm:"index:idx_blobber_aggregate,unique"` - Round int64 `json:"round" gorm:"index:idx_blobber_aggregate,unique"` - - WritePrice uint64 `json:"write_price"` - Capacity int64 `json:"capacity"` // total blobber capacity - Allocated int64 `json:"allocated"` // allocated capacity - SavedData int64 `json:"saved_data"` - ReadData int64 `json:"read_data"` - OffersTotal uint64 `json:"offers_total"` - TotalStake uint64 `json:"total_stake"` - - TotalServiceCharge uint64 `json:"total_service_charge"` - ChallengesPassed uint64 `json:"challenges_passed"` - ChallengesCompleted uint64 `json:"challenges_completed"` - OpenChallenges uint64 `json:"open_challenges"` - InactiveRounds int64 `json:"InactiveRounds"` - RankMetric float64 `json:"rank_metric" gorm:"index:idx_ba_rankmetric"` -} - -const ChainConfig = ` - { - "chain_id":"0afc093ffb509f059c55478bc1a60351cef7b4e9c008a53a6cc8241ca8617dfe", - "signature_scheme" : "bls0chain", - "block_worker" : "http://dev.zus.network/dns", - "min_submit" : 50, - "min_confirmation" : 50, - "confirmation_chain_length" : 3, - "num_keys" : 1, - "eth_node" : "https://ropsten.infura.io/v3/xxxxxxxxxxxxxxx" - } -` - -func TestGetAggregates(t *testing.T) { - t.Skip("learning test") - err := zcncore.Init(ChainConfig) - if err != nil { - fmt.Println("Init failed") - return - } - - var w = ` - { - "client_id":"0bc96a0980170045863d826f9eb579d8144013210602e88426408e9f83c236f6", - "client_key":"a4e58c66b072d27288b650db9a476fe66a1a4f69e0f8fb11499f9ec3a579e21e5dc0298b8c5ae5baa205730d06bc04b07a31943ab3bd620e8427c15d5c413b9e", - "keys":[ - { - "public_key":"a4e58c66b072d27288b650db9a476fe66a1a4f69e0f8fb11499f9ec3a579e21e5dc0298b8c5ae5baa205730d06bc04b07a31943ab3bd620e8427c15d5c413b9e", - "private_key":"c0f3a3100241888ea9c2cc5c7300e3e510a8e7190c2c20b03f80e3937a91530d" - }], - "mnemonics":"snake mixed bird cream cotton trouble small fee finger catalog measure spoon private second canal pact unable close predict dream mask delay path inflict", - "version":"1.0", - "date_created":"2019-06-19 13:37:50.466889 -0700 PDT m=+0.023873276" - }` - - err = zcncore.SetWalletInfo(w, false) - if err != nil { - fmt.Println("set wallet info failed: ", err) - return - } - - wg := &sync.WaitGroup{} - var snaps []BlobberAggregate - statusBar := wallet.NewZCNStatus(&snaps) - statusBar.Wg = wg - wg.Add(5) - err = zcncore.GetBlobberSnapshots(int64(587), 20, 0, statusBar) - if err != nil { - t.Error(err) - return - } - - err = zcncore.GetSharderSnapshots(int64(587), 20, 0, statusBar) - if err != nil { - t.Error(err) - return - } - - err = zcncore.GetMinerSnapshots(int64(587), 20, 0, statusBar) - if err != nil { - t.Error(err) - return - } - - err = zcncore.GetAuthorizerSnapshots(int64(587), 20, 0, statusBar) - if err != nil { - t.Error(err) - return - } - - err = zcncore.GetValidatorSnapshots(int64(587), 20, 0, statusBar) - if err != nil { - t.Error(err) - return - } - - err = zcncore.GetUserSnapshots(int64(587), 20, 0, statusBar) - if err != nil { - t.Error(err) - return - } - - wg.Wait() - if !statusBar.Success { - t.Error(statusBar.Err) - } -} diff --git a/zcncore/transaction.go b/zcncore/transaction.go deleted file mode 100644 index 5047a92b1..000000000 --- a/zcncore/transaction.go +++ /dev/null @@ -1,1719 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "context" - "encoding/json" - "fmt" - "math" - "net/http" - "sync" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/block" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/node" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -// Provider represents the type of provider. -type Provider int - -const ( - ProviderMiner Provider = iota + 1 - ProviderSharder - ProviderBlobber - ProviderValidator - ProviderAuthorizer -) - -type TransactionVelocity = float64 - -// Transaction velocity vs cost factor -// TODO: Pass it to miner to calculate real time factor -const ( - RegularTransaction TransactionVelocity = 1.0 - FastTransaction TransactionVelocity = 1.3 - FasterTransaction TransactionVelocity = 1.6 -) - -type ConfirmationStatus int - -const ( - Undefined ConfirmationStatus = iota - Success - - // ChargeableError is an error that still charges the user for the transaction. - ChargeableError -) - -type Miner struct { - ID string `json:"id"` - N2NHost string `json:"n2n_host"` - Host string `json:"host"` - Port int `json:"port"` - PublicKey string `json:"public_key"` - ShortName string `json:"short_name"` - BuildTag string `json:"build_tag"` - TotalStake int64 `json:"total_stake"` - 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"` -} - -type VestingSCConfig struct { - MinLock common.Balance `json:"min_lock"` - MinDuration time.Duration `json:"min_duration"` - MaxDuration time.Duration `json:"max_duration"` - MaxDestinations int `json:"max_destinations"` - MaxDescriptionLength int `json:"max_description_length"` -} - -type DelegatePool struct { - Balance int64 `json:"balance"` - Reward int64 `json:"reward"` - Status int `json:"status"` - RoundCreated int64 `json:"round_created"` // used for cool down - DelegateID string `json:"delegate_id"` -} - -type StakePool struct { - Pools map[string]*DelegatePool `json:"pools"` - Reward int64 `json:"rewards"` - Settings StakePoolSettings `json:"settings"` - Minter int `json:"minter"` -} - -type stakePoolRequest struct { - ProviderType Provider `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` -} - -type MinerSCDelegatePoolInfo struct { - ID common.Key `json:"id"` - Balance common.Balance `json:"balance"` - Reward common.Balance `json:"reward"` // uncollected reread - RewardPaid common.Balance `json:"reward_paid"` // total reward all time - Status string `json:"status"` -} - -// MinerSCUserPoolsInfo represents the user stake pools information -type MinerSCUserPoolsInfo struct { - Pools map[string][]*MinerSCDelegatePoolInfo `json:"pools"` -} - -type TransactionCommon interface { - // ExecuteSmartContract implements wrapper for smart contract function - ExecuteSmartContract(address, methodName string, input interface{}, val uint64, feeOpts ...FeeOption) (*transaction.Transaction, error) - // Send implements sending token to a given clientid - Send(toClientID string, val uint64, desc string) error - - //RegisterMultiSig registers a group wallet and subwallets with MultisigSC - RegisterMultiSig(walletstr, mswallet string) error - - VestingAdd(ar *VestingAddRequest, value uint64) error - - MinerSCLock(providerId string, providerType Provider, lock uint64) error - MinerSCUnlock(providerId string, providerType Provider) error - MinerSCCollectReward(providerID string, providerType Provider) error - MinerSCKill(providerID string, providerType Provider) error - - StorageSCCollectReward(providerID string, providerType Provider) error - - FinalizeAllocation(allocID string) error - CancelAllocation(allocID string) error - CreateAllocation(car *CreateAllocationRequest, lock uint64) error // - CreateReadPool() error - ReadPoolLock(allocID string, blobberID string, duration int64, lock uint64) error - ReadPoolUnlock() error - StakePoolLock(providerId string, providerType Provider, lock uint64) error - StakePoolUnlock(providerId string, providerType Provider) error - UpdateBlobberSettings(blobber *Blobber) error - UpdateValidatorSettings(validator *Validator) error - UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock uint64) error - WritePoolLock(allocID string, blobberID string, duration int64, lock uint64) error - WritePoolUnlock(allocID string) error - - VestingUpdateConfig(*InputMap) error - MinerScUpdateConfig(*InputMap) error - MinerScUpdateGlobals(*InputMap) error - StorageScUpdateConfig(*InputMap) error - AddHardfork(ip *InputMap) (err error) - FaucetUpdateConfig(*InputMap) error - ZCNSCUpdateGlobalConfig(*InputMap) error - - MinerSCMinerSettings(*MinerSCMinerInfo) error - MinerSCSharderSettings(*MinerSCMinerInfo) error - MinerSCDeleteMiner(*MinerSCMinerInfo) error - MinerSCDeleteSharder(*MinerSCMinerInfo) error - - // ZCNSCUpdateAuthorizerConfig updates authorizer config by ID - ZCNSCUpdateAuthorizerConfig(*AuthorizerNode) error - // ZCNSCAddAuthorizer adds authorizer - ZCNSCAddAuthorizer(*AddAuthorizerPayload) error - - // ZCNSCAuthorizerHealthCheck provides health check for authorizer - ZCNSCAuthorizerHealthCheck(*AuthorizerHealthCheckPayload) error - - // GetVerifyConfirmationStatus implements the verification status from sharders - GetVerifyConfirmationStatus() ConfirmationStatus - - // ZCNSCDeleteAuthorizer deletes authorizer - ZCNSCDeleteAuthorizer(*DeleteAuthorizerPayload) error - - ZCNSCCollectReward(providerID string, providerType Provider) error -} - -// compiler time check -var ( - _ TransactionScheme = (*Transaction)(nil) - _ TransactionScheme = (*TransactionWithAuth)(nil) -) - -// TransactionScheme implements few methods for block chain. -// -// Note: to be buildable on MacOSX all arguments should have names. -type TransactionScheme interface { - TransactionCommon - // SetTransactionCallback implements storing the callback - // used to call after the transaction or verification is completed - SetTransactionCallback(cb TransactionCallback) error - // StoreData implements store the data to blockchain - StoreData(data string) error - // ExecuteFaucetSCWallet implements the `Faucet Smart contract` for a given wallet - ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error - // GetTransactionHash implements retrieval of hash of the submitted transaction - GetTransactionHash() string - // SetTransactionHash implements verify a previous transaction status - SetTransactionHash(hash string) error - // SetTransactionNonce implements method to set the transaction nonce - SetTransactionNonce(txnNonce int64) error - // Verify implements verify the transaction - Verify() error - // GetVerifyOutput implements the verification output from sharders - GetVerifyOutput() string - // GetTransactionError implements error string in case of transaction failure - GetTransactionError() string - // GetVerifyError implements error string in case of verify failure error - GetVerifyError() string - // GetTransactionNonce returns nonce - GetTransactionNonce() int64 - - // Output of transaction. - Output() []byte - - // Hash Transaction status regardless of status - Hash() string - - // Vesting SC - - VestingTrigger(poolID string) error - VestingStop(sr *VestingStopRequest) error - VestingUnlock(poolID string) error - VestingDelete(poolID string) error - - // Miner SC -} - -// PriceRange represents a price range allowed by user to filter blobbers. -type PriceRange struct { - Min common.Balance `json:"min"` - Max common.Balance `json:"max"` -} - -// CreateAllocationRequest is information to create allocation. -type CreateAllocationRequest struct { - DataShards int `json:"data_shards"` - ParityShards int `json:"parity_shards"` - Size common.Size `json:"size"` - Expiration common.Timestamp `json:"expiration_date"` - Owner string `json:"owner_id"` - OwnerPublicKey string `json:"owner_public_key"` - Blobbers []string `json:"blobbers"` - ReadPriceRange PriceRange `json:"read_price_range"` - WritePriceRange PriceRange `json:"write_price_range"` -} - -type StakePoolSettings struct { - DelegateWallet *string `json:"delegate_wallet,omitempty"` - NumDelegates *int `json:"num_delegates,omitempty"` - ServiceCharge *float64 `json:"service_charge,omitempty"` -} - -type Terms struct { - ReadPrice common.Balance `json:"read_price"` // tokens / GB - WritePrice common.Balance `json:"write_price"` // tokens / GB ` - MaxOfferDuration time.Duration `json:"max_offer_duration"` -} - -// Blobber represents a blobber node. -type Blobber struct { - // 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 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 { - ID common.Key `json:"id"` - BaseURL string `json:"url"` - 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"` -} - -type AuthorizerConfig struct { - Fee common.Balance `json:"fee"` -} - -// InputMap represents a map of input fields. -type InputMap struct { - Fields map[string]string `json:"Fields"` -} - -func newTransaction(cb TransactionCallback, txnFee uint64, nonce int64) (*Transaction, error) { - t := &Transaction{} - t.txn = transaction.NewTransactionEntity(_config.wallet.ClientID, _config.chain.ChainID, _config.wallet.ClientKey, nonce) - t.txnStatus, t.verifyStatus = StatusUnknown, StatusUnknown - t.txnCb = cb - t.txn.TransactionNonce = nonce - t.txn.TransactionFee = txnFee - return t, nil -} - -// 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 { - return nil, err - } - if _config.isSplitWallet { - logging.Info("New transaction interface with auth") - return newTransactionWithAuth(cb, txnFee, nonce) - } - - logging.Info("New transaction interface") - return newTransaction(cb, txnFee, nonce) -} - -func (t *Transaction) createSmartContractTxn(address, methodName string, input interface{}, value uint64, opts ...FeeOption) error { - sn := transaction.SmartContractTxnData{Name: methodName, InputArgs: input} - snBytes, err := json.Marshal(sn) - if err != nil { - return errors.Wrap(err, "create smart contract failed due to invalid data") - } - - t.txn.TransactionType = transaction.TxnTypeSmartContract - t.txn.ToClientID = address - t.txn.TransactionData = string(snBytes) - t.txn.Value = value - - if t.txn.TransactionFee > 0 { - return nil - } - - tf := &TxnFeeOption{} - for _, opt := range opts { - opt(tf) - } - - if tf.noEstimateFee { - return nil - } - - // TODO: check if transaction is exempt to avoid unnecessary fee estimation - minFee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, 0.2) - if err != nil { - return err - } - - t.txn.TransactionFee = minFee - - return nil -} - -func (t *Transaction) createFaucetSCWallet(walletStr string, methodName string, input []byte) (*zcncrypto.Wallet, error) { - w, err := getWallet(walletStr) - if err != nil { - fmt.Printf("Error while parsing the wallet. %v\n", err) - return nil, err - } - err = t.createSmartContractTxn(FaucetSmartContractAddress, methodName, input, 0) - if err != nil { - return nil, err - } - return w, nil -} - -func (t *Transaction) ExecuteSmartContract(address, methodName string, input interface{}, val uint64, opts ...FeeOption) (*transaction.Transaction, error) { - err := t.createSmartContractTxn(address, methodName, input, val, opts...) - if err != nil { - return nil, err - } - go func() { - t.setNonceAndSubmit() - }() - return t.txn, nil -} - -func (t *Transaction) Send(toClientID string, val uint64, desc string) error { - txnData, err := json.Marshal(transaction.SmartContractTxnData{Name: "transfer", InputArgs: SendTxnData{Note: desc}}) - if err != nil { - return errors.New("", "Could not serialize description to transaction_data") - } - - t.txn.TransactionType = transaction.TxnTypeSend - t.txn.ToClientID = toClientID - t.txn.Value = val - t.txn.TransactionData = string(txnData) - if t.txn.TransactionFee == 0 { - fee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, 0.2) - if err != nil { - return err - } - t.txn.TransactionFee = fee - } - - go func() { - t.setNonceAndSubmit() - }() - return nil -} - -func (t *Transaction) SendWithSignatureHash(toClientID string, val uint64, desc string, sig string, CreationDate int64, hash string) error { - txnData, err := json.Marshal(SendTxnData{Note: desc}) - if err != nil { - return errors.New("", "Could not serialize description to transaction_data") - } - t.txn.TransactionType = transaction.TxnTypeSend - t.txn.ToClientID = toClientID - t.txn.Value = val - t.txn.Hash = hash - t.txn.TransactionData = string(txnData) - t.txn.Signature = sig - t.txn.CreationDate = CreationDate - if t.txn.TransactionFee == 0 { - fee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, 0.2) - if err != nil { - return err - } - t.txn.TransactionFee = fee - } - - go func() { - t.setNonceAndSubmit() - }() - return nil -} - -type VestingDest struct { - ID string `json:"id"` // destination ID - Amount common.Balance `json:"amount"` // amount to vest for the destination -} - -type VestingAddRequest struct { - Description string `json:"description"` // allow empty - StartTime common.Timestamp `json:"start_time"` // - Duration time.Duration `json:"duration"` // - Destinations []*VestingDest `json:"destinations"` // -} - -func (t *Transaction) VestingAdd(ar *VestingAddRequest, value uint64) ( - err error) { - - err = t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_ADD, ar, value) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingStop(sr *VestingStopRequest) (err error) { - err = t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_STOP, sr, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) vestingPoolTxn(function string, poolID string, - value uint64) error { - - return t.createSmartContractTxn(VestingSmartContractAddress, - function, vestingRequest{PoolID: common.Key(poolID)}, value) -} - -func (t *Transaction) VestingTrigger(poolID string) (err error) { - - err = t.vestingPoolTxn(transaction.VESTING_TRIGGER, poolID, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingUnlock(poolID string) (err error) { - err = t.vestingPoolTxn(transaction.VESTING_UNLOCK, poolID, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingDelete(poolID string) (err error) { - err = t.vestingPoolTxn(transaction.VESTING_DELETE, poolID, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCLock(providerId string, providerType Provider, lock uint64) error { - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - pr := &stakePoolRequest{ - ProviderID: providerId, - ProviderType: providerType, - } - err := t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_LOCK, pr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} -func (t *Transaction) MinerSCUnlock(providerId string, providerType Provider) error { - pr := &stakePoolRequest{ - ProviderID: providerId, - ProviderType: providerType, - } - err := t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UNLOCK, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} - -func (t *Transaction) MinerSCCollectReward(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - err := t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_COLLECT_REWARD, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} - -func (t *Transaction) MinerSCKill(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - var name string - switch providerType { - case ProviderMiner: - name = transaction.MINERSC_KILL_MINER - case ProviderSharder: - name = transaction.MINERSC_KILL_SHARDER - default: - return fmt.Errorf("kill provider type %v not implimented", providerType) - } - - err := t.createSmartContractTxn(MinerSmartContractAddress, name, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} - -func (t *Transaction) StorageSCCollectReward(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_COLLECT_REWARD, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go t.setNonceAndSubmit() - return err -} - -// FinalizeAllocation transaction. -func (t *Transaction) FinalizeAllocation(allocID string) ( - err error) { - - type finiRequest struct { - AllocationID string `json:"allocation_id"` - } - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_FINALIZE_ALLOCATION, &finiRequest{ - AllocationID: allocID, - }, 0) - if err != nil { - logging.Error(err) - return - } - - go func() { t.setNonceAndSubmit() }() - return -} - -// CancelAllocation transaction. -func (t *Transaction) CancelAllocation(allocID string) ( - err error) { - - type cancelRequest struct { - AllocationID string `json:"allocation_id"` - } - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CANCEL_ALLOCATION, &cancelRequest{ - AllocationID: allocID, - }, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// CreateAllocation transaction. -func (t *Transaction) CreateAllocation(car *CreateAllocationRequest, - lock uint64) (err error) { - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_ALLOCATION, car, lock) - if err != nil { - logging.Error(err) - return - } - - go func() { t.setNonceAndSubmit() }() - return -} - -// CreateReadPool for current user. -func (t *Transaction) CreateReadPool() (err error) { - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_READ_POOL, nil, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// ReadPoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (t *Transaction) ReadPoolLock(allocID, blobberID string, duration int64, lock uint64) (err error) { - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type lockRequest struct { - Duration time.Duration `json:"duration"` - AllocationID string `json:"allocation_id"` - BlobberID string `json:"blobber_id,omitempty"` - } - - var lr lockRequest - lr.Duration = time.Duration(duration) - lr.AllocationID = allocID - lr.BlobberID = blobberID - - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// ReadPoolUnlock for current user and given pool. -func (t *Transaction) ReadPoolUnlock() (err error) { - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_UNLOCK, nil, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// StakePoolLock used to lock tokens in a stake pool of a blobber. -func (t *Transaction) StakePoolLock(providerId string, providerType Provider, lock uint64) error { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type stakePoolRequest struct { - ProviderType Provider `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_STAKE_POOL_LOCK, &spr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// StakePoolUnlock by blobberID and poolID. -func (t *Transaction) StakePoolUnlock(providerId string, providerType Provider) error { - - type stakePoolRequest struct { - ProviderType Provider `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := t.createSmartContractTxn(StorageSmartContractAddress, transaction.STORAGESC_STAKE_POOL_UNLOCK, &spr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// UpdateBlobberSettings update settings of a blobber. -func (t *Transaction) UpdateBlobberSettings(b *Blobber) (err error) { - - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_BLOBBER_SETTINGS, b, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// UpdateAllocation transaction. -func (t *Transaction) UpdateAllocation(allocID string, sizeDiff int64, - expirationDiff int64, lock uint64) (err error) { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type updateAllocationRequest struct { - ID string `json:"id"` // allocation id - Size int64 `json:"size"` // difference - Expiration int64 `json:"expiration_date"` // difference - } - - var uar updateAllocationRequest - uar.ID = allocID - uar.Size = sizeDiff - uar.Expiration = expirationDiff - - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_ALLOCATION, &uar, lock) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// WritePoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (t *Transaction) WritePoolLock(allocID, blobberID string, duration int64, - lock uint64) (err error) { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type lockRequest struct { - Duration time.Duration `json:"duration"` - AllocationID string `json:"allocation_id"` - BlobberID string `json:"blobber_id,omitempty"` - } - - var lr lockRequest - lr.Duration = time.Duration(duration) - lr.AllocationID = allocID - lr.BlobberID = blobberID - - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// WritePoolUnlock for current user and given pool. -func (t *Transaction) WritePoolUnlock(allocID string) ( - err error) { - - var ur = struct { - AllocationID string `json:"allocation_id"` - }{ - AllocationID: allocID, - } - - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_UNLOCK, &ur, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingUpdateConfig(vscc *InputMap) (err error) { - - err = t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_UPDATE_SETTINGS, vscc, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// faucet smart contract - -func (t *Transaction) FaucetUpdateConfig(ip *InputMap) (err error) { - - err = t.createSmartContractTxn(FaucetSmartContractAddress, - transaction.FAUCETSC_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// -// miner SC -// - -func (t *Transaction) MinerScUpdateConfig(ip *InputMap) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerScUpdateGlobals(ip *InputMap) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_GLOBALS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) StorageScUpdateConfig(ip *InputMap) (err error) { - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} -func (t *Transaction) AddHardfork(ip *InputMap) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.ADD_HARDFORK, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) ZCNSCUpdateGlobalConfig(ip *InputMap) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_UPDATE_GLOBAL_CONFIG, ip, 0) - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -func (t *Transaction) GetVerifyConfirmationStatus() ConfirmationStatus { - return ConfirmationStatus(t.verifyConfirmationStatus) -} - -// RegisterMultiSig register a multisig wallet with the SC. -func (t *Transaction) RegisterMultiSig(walletstr string, mswallet string) error { - w, err := GetWallet(walletstr) - if err != nil { - fmt.Printf("Error while parsing the wallet. %v\n", err) - return err - } - - msw, err := GetMultisigPayload(mswallet) - if err != nil { - fmt.Printf("\nError in registering. %v\n", err) - return err - } - sn := transaction.SmartContractTxnData{Name: MultiSigRegisterFuncName, InputArgs: msw} - snBytes, err := json.Marshal(sn) - if err != nil { - return errors.Wrap(err, "execute multisig register failed due to invalid data.") - } - go func() { - t.txn.TransactionType = transaction.TxnTypeSmartContract - t.txn.ToClientID = MultiSigSmartContractAddress - t.txn.TransactionData = string(snBytes) - t.txn.Value = 0 - nonce := t.txn.TransactionNonce - if nonce < 1 { - nonce = node.Cache.GetNextNonce(t.txn.ClientID) - } else { - node.Cache.Set(t.txn.ClientID, nonce) - } - t.txn.TransactionNonce = nonce - - if t.txn.TransactionFee == 0 { - fee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, 0.2) - if err != nil { - return - } - t.txn.TransactionFee = fee - } - - err = t.txn.ComputeHashAndSignWithWallet(signWithWallet, w) - if err != nil { - return - } - t.submitTxn() - }() - return nil -} - -// NewMSTransaction new transaction object for multisig operation -func NewMSTransaction(walletstr string, cb TransactionCallback) (*Transaction, error) { - w, err := GetWallet(walletstr) - if err != nil { - fmt.Printf("Error while parsing the wallet. %v", err) - return nil, err - } - t := &Transaction{} - t.txn = transaction.NewTransactionEntity(w.ClientID, _config.chain.ChainID, w.ClientKey, w.Nonce) - t.txnStatus, t.verifyStatus = StatusUnknown, StatusUnknown - t.txnCb = cb - return t, nil -} - -// RegisterVote register a multisig wallet with the SC. -func (t *Transaction) RegisterVote(signerwalletstr string, msvstr string) error { - - w, err := GetWallet(signerwalletstr) - if err != nil { - fmt.Printf("Error while parsing the wallet. %v", err) - return err - } - - msv, err := GetMultisigVotePayload(msvstr) - - if err != nil { - fmt.Printf("\nError in voting. %v\n", err) - return err - } - sn := transaction.SmartContractTxnData{Name: MultiSigVoteFuncName, InputArgs: msv} - snBytes, err := json.Marshal(sn) - if err != nil { - return errors.Wrap(err, "execute multisig vote failed due to invalid data.") - } - go func() { - t.txn.TransactionType = transaction.TxnTypeSmartContract - t.txn.ToClientID = MultiSigSmartContractAddress - t.txn.TransactionData = string(snBytes) - t.txn.Value = 0 - nonce := t.txn.TransactionNonce - if nonce < 1 { - nonce = node.Cache.GetNextNonce(t.txn.ClientID) - } else { - node.Cache.Set(t.txn.ClientID, nonce) - } - t.txn.TransactionNonce = nonce - - if t.txn.TransactionFee == 0 { - fee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, 0.2) - if err != nil { - return - } - t.txn.TransactionFee = fee - } - - err = t.txn.ComputeHashAndSignWithWallet(signWithWallet, w) - if err != nil { - return - } - t.submitTxn() - }() - return nil -} - -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"` -} - -func (t *Transaction) MinerSCMinerSettings(info *MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_SETTINGS, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCSharderSettings(info *MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_SETTINGS, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCDeleteMiner(info *MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_DELETE, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCDeleteSharder(info *MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_DELETE, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// AuthorizerNode represents an authorizer node in the network -type AuthorizerNode struct { - ID string `json:"id"` - URL string `json:"url"` - Config *AuthorizerConfig `json:"config"` -} - -func (t *Transaction) ZCNSCUpdateAuthorizerConfig(ip *AuthorizerNode) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_UPDATE_AUTHORIZER_CONFIG, ip, 0) - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -func (t *Transaction) Verify() error { - if t.txnHash == "" && t.txnStatus == StatusUnknown { - return errors.New("", "invalid transaction. cannot be verified.") - } - if t.txnHash == "" && t.txnStatus == StatusSuccess { - h := t.GetTransactionHash() - if h == "" { - node.Cache.Evict(t.txn.ClientID) - return errors.New("", "invalid transaction. cannot be verified.") - } - } - // If transaction is verify only start from current time - if t.txn.CreationDate == 0 { - t.txn.CreationDate = int64(common.Now()) - } - - tq, err := NewTransactionQuery(Sharders.Healthy(), _config.chain.Miners) - if err != nil { - logging.Error(err) - return err - } - - go func() { - - for { - - tq.Reset() - // Get transaction confirmationBlock from a random sharder - confirmBlockHeader, confirmationBlock, lfbBlockHeader, err := tq.getFastConfirmation(context.TODO(), t.txnHash) - if err != nil { - now := int64(common.Now()) - - // maybe it is a network or server error - if lfbBlockHeader == nil { - logging.Info(err, " now: ", now) - } else { - logging.Info(err, " now: ", now, ", LFB creation time:", lfbBlockHeader.CreationDate) - } - - // transaction is done or expired. it means random sharder might be outdated, try to query it from s/S sharders to confirm it - if util.MaxInt64(lfbBlockHeader.getCreationDate(now), now) >= (t.txn.CreationDate + int64(defaultTxnExpirationSeconds)) { - logging.Info("falling back to ", getMinShardersVerify(), " of ", len(_config.chain.Sharders), " Sharders") - confirmBlockHeader, confirmationBlock, lfbBlockHeader, err = tq.getConsensusConfirmation(context.TODO(), getMinShardersVerify(), t.txnHash) - } - - // txn not found in fast confirmation/consensus confirmation - if err != nil { - - if lfbBlockHeader == nil { - // no any valid lfb on all sharders. maybe they are network/server errors. try it again - continue - } - - // it is expired - if t.isTransactionExpired(lfbBlockHeader.getCreationDate(now), now) { - t.completeVerify(StatusError, "", errors.New("", `{"error": "verify transaction failed"}`)) - return - } - continue - } - } - - valid := validateChain(confirmBlockHeader) - if valid { - output, err := json.Marshal(confirmationBlock) - if err != nil { - t.completeVerify(StatusError, "", errors.New("", `{"error": "transaction confirmation json marshal error"`)) - return - } - confJson := confirmationBlock["confirmation"] - - var conf map[string]json.RawMessage - if err := json.Unmarshal(confJson, &conf); err != nil { - return - } - txnJson := conf["txn"] - - tt := transaction.Transaction{} - if err := json.Unmarshal(txnJson, &tt); err != nil { - return - } - - *t.txn = tt - txStatus := tt.Status - - switch txStatus { - case 1: - t.completeVerifyWithConStatus(StatusSuccess, int(Success), string(output), nil) - case 2: - t.completeVerifyWithConStatus(StatusSuccess, int(ChargeableError), tt.TransactionOutput, nil) - default: - t.completeVerify(StatusError, string(output), nil) - } - return - } - } - }() - return nil -} - -// ConvertToValue converts ZCN tokens to SAS tokens -// # Inputs -// - token: ZCN tokens -func ConvertToValue(token float64) uint64 { - return uint64(token * common.TokenUnit) -} - -func GetLatestFinalized(ctx context.Context, numSharders int) (b *block.Header, err error) { - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil { - logging.Error("block parse error: ", err) - err = nil - continue - } - - var h = encryption.FastHash([]byte(b.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "block info not found") - } - - 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) - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - type respObj struct { - MagicBlock *block.MagicBlock `json:"magic_block"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logging.Error(" magic block parse error: ", err) - err = nil - continue - } - - m = respo.MagicBlock - var h = encryption.FastHash([]byte(respo.MagicBlock.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "magic block info not found") - } - - return -} - -func GetChainStats(ctx context.Context) (b *block.ChainStats, err error) { - var result = make(chan *util.GetResponse, 1) - defer close(result) - - var numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result) - var rsp *util.GetResponse - for i := 0; i < numSharders; i++ { - var x = <-result - if x == nil { - logging.Error("nil response") - continue - } - if x.StatusCode != http.StatusOK { - continue - } - rsp = x - } - - if rsp == nil { - return nil, errors.New("http_request_failed", "Request failed with status not 200") - } - - if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil { - return nil, err - } - return -} - -func GetFeeStats(ctx context.Context) (b *block.FeeStats, err error) { - - var numMiners = 4 - - if numMiners > len(_config.chain.Miners) { - numMiners = len(_config.chain.Miners) - } - - var result = make(chan *util.GetResponse, numMiners) - - queryFromMinersContext(ctx, numMiners, GET_FEE_STATS, result) - var rsp *util.GetResponse - -loop: - for i := 0; i < numMiners; i++ { - select { - case x := <-result: - if x.StatusCode != http.StatusOK { - continue - } - rsp = x - if rsp != nil { - break loop - } - case <-ctx.Done(): - err = ctx.Err() - return nil, err - } - } - if rsp == nil { - return nil, errors.New("http_request_failed", "Request failed with status not 200") - } - if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil { - return nil, err - } - return -} - -func GetBlockByRound(ctx context.Context, numSharders int, round int64) (b *block.Block, err error) { - 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) -} - -func GetMagicBlockByNumber(ctx context.Context, numSharders int, number int64) (m *block.MagicBlock, err error) { - - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, - fmt.Sprintf("%smagic_block_number=%d", GET_MAGIC_BLOCK_INFO, number), - result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - type respObj struct { - MagicBlock *block.MagicBlock `json:"magic_block"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logging.Error(" magic block parse error: ", err) - err = nil - continue - } - - m = respo.MagicBlock - var h = encryption.FastHash([]byte(respo.MagicBlock.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "magic block info not found") - } - - return -} - -type NonceCache struct { - cache map[string]int64 - guard sync.Mutex -} - -func NewNonceCache() *NonceCache { - return &NonceCache{cache: make(map[string]int64)} -} - -func (nc *NonceCache) GetNextNonce(clientId string) int64 { - nc.guard.Lock() - defer nc.guard.Unlock() - if _, ok := nc.cache[clientId]; !ok { - back := &getNonceCallBack{ - nonceCh: make(chan int64), - err: nil, - } - if err := GetNonce(back); err != nil { - return 0 - } - - timeout, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - select { - case n := <-back.nonceCh: - if back.err != nil { - return 0 - } - nc.cache[clientId] = n - case <-timeout.Done(): - return 0 - } - } - - nc.cache[clientId] += 1 - return nc.cache[clientId] -} - -func (nc *NonceCache) Set(clientId string, nonce int64) { - nc.guard.Lock() - defer nc.guard.Unlock() - nc.cache[clientId] = nonce -} - -func (nc *NonceCache) Evict(clientId string) { - nc.guard.Lock() - defer nc.guard.Unlock() - 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 - return nil - } -} - -// 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 - return nil - } -} - -// 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 - return nil - } -} - -// 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 - return nil - } -} - -// 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 - return nil - } -} - -func WithSharderConsensous(m int) func(c *ChainConfig) error { - return func(c *ChainConfig) error { - c.SharderConsensous = m - return nil - } -} - -func WithIsSplitWallet(v bool) func(c *ChainConfig) error { - return func(c *ChainConfig) error { - c.IsSplitWallet = v - return nil - } -} - -// UpdateValidatorSettings update settings of a validator. -func (t *Transaction) UpdateValidatorSettings(v *Validator) (err error) { - - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_VALIDATOR_SETTINGS, v, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -type VestingClientList struct { - Pools []common.Key `json:"pools"` -} - -func GetVestingClientList(clientID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - if clientID == "" { - clientID = _config.wallet.ClientID // if not blank - } - go GetInfoFromSharders(WithParams(GET_VESTING_CLIENT_POOLS, Params{ - "client_id": clientID, - }), 0, cb) - return -} - -type VestingDestInfo struct { - ID common.Key `json:"id"` // identifier - Wanted common.Balance `json:"wanted"` // wanted amount for entire period - Earned common.Balance `json:"earned"` // can unlock - Vested common.Balance `json:"vested"` // already vested - Last common.Timestamp `json:"last"` // last time unlocked -} - -type VestingPoolInfo struct { - ID common.Key `json:"pool_id"` // pool ID - Balance common.Balance `json:"balance"` // real pool balance - Left common.Balance `json:"left"` // owner can unlock - Description string `json:"description"` // description - StartTime common.Timestamp `json:"start_time"` // from - ExpireAt common.Timestamp `json:"expire_at"` // until - Destinations []*VestingDestInfo `json:"destinations"` // receivers - ClientID common.Key `json:"client_id"` // owner -} - -func GetVestingPoolInfo(poolID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - GetInfoFromSharders(WithParams(GET_VESTING_POOL_INFO, Params{ - "pool_id": poolID, - }), 0, cb) - return -} - -func GetVestingSCConfig(cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - go GetInfoFromSharders(GET_VESTING_CONFIG, 0, cb) - return -} - -// faucet - -func GetFaucetSCConfig(cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - go GetInfoFromSharders(GET_FAUCETSC_CONFIG, 0, cb) - return -} - -func (t *Transaction) ZCNSCAddAuthorizer(ip *AddAuthorizerPayload) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_ADD_AUTHORIZER, ip, 0) - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -func (t *Transaction) ZCNSCAuthorizerHealthCheck(ip *AuthorizerHealthCheckPayload) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_AUTHORIZER_HEALTH_CHECK, ip, 0) - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -func (t *Transaction) ZCNSCDeleteAuthorizer(ip *DeleteAuthorizerPayload) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_DELETE_AUTHORIZER, ip, 0) - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -func (t *Transaction) ZCNSCCollectReward(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - err := t.createSmartContractTxn(ZCNSCSmartContractAddress, - transaction.ZCNSC_COLLECT_REWARD, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} diff --git a/zcncore/transaction_base.go b/zcncore/transaction_base.go deleted file mode 100644 index 505e9d818..000000000 --- a/zcncore/transaction_base.go +++ /dev/null @@ -1,786 +0,0 @@ -package zcncore - -import ( - "context" - "encoding/json" - stdErrors "errors" - "fmt" - "net/http" - "sync/atomic" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/node" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/fileref" - - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/core/version" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -var ( - errNetwork = errors.New("", "network error. host not reachable") - errUserRejected = errors.New("", "rejected by user") - errAuthVerifyFailed = errors.New("", "verification failed for auth response") - errAuthTimeout = errors.New("", "auth timed out") - errAddSignature = errors.New("", "error adding signature") -) - -// TransactionCallback needs to be implemented by the caller for transaction related APIs -type TransactionCallback interface { - OnTransactionComplete(t *Transaction, status int) - OnVerifyComplete(t *Transaction, status int) - OnAuthComplete(t *Transaction, status int) -} - -type localConfig struct { - chain ChainConfig - wallet zcncrypto.Wallet - authUrl string - isConfigured bool - isValidWallet bool - isSplitWallet bool -} - -type ChainConfig struct { - ChainID string `json:"chain_id,omitempty"` - BlockWorker string `json:"block_worker"` - Miners []string `json:"miners"` - Sharders []string `json:"sharders"` - SignatureScheme string `json:"signature_scheme"` - MinSubmit int `json:"min_submit"` - MinConfirmation int `json:"min_confirmation"` - ConfirmationChainLength int `json:"confirmation_chain_length"` - EthNode string `json:"eth_node"` - SharderConsensous int `json:"sharder_consensous"` - IsSplitWallet bool `json:"is_split_wallet"` -} - -var Sharders *node.NodeHolder - -// 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") - } - _config.chain.BlockWorker = blockWorker - _config.chain.SignatureScheme = signscheme - - err := UpdateNetworkDetails() - if err != nil { - fmt.Println("UpdateNetworkDetails:", err) - return err - } - - go updateNetworkDetailsWorker(context.Background()) - - for _, conf := range configs { - err := conf(&_config.chain) - if err != nil { - return errors.Wrap(err, "invalid/unsupported options.") - } - } - _config.isSplitWallet = _config.chain.IsSplitWallet - assertConfig() - _config.isConfigured = true - logging.Info("******* Wallet SDK Version:", version.VERSIONSTR, " ******* (InitZCNSDK)") - - cfg := &conf.Config{ - BlockWorker: _config.chain.BlockWorker, - MinSubmit: _config.chain.MinSubmit, - MinConfirmation: _config.chain.MinConfirmation, - ConfirmationChainLength: _config.chain.ConfirmationChainLength, - SignatureScheme: _config.chain.SignatureScheme, - ChainID: _config.chain.ChainID, - EthereumNode: _config.chain.EthNode, - SharderConsensous: _config.chain.SharderConsensous, - } - - conf.InitClientConfig(cfg) - - return nil -} - -func IsSplitWallet() bool { - return _config.isSplitWallet -} - -/*Confirmation - a data structure that provides the confirmation that a transaction is included into the block chain */ -type confirmation struct { - Version string `json:"version"` - Hash string `json:"hash"` - BlockHash string `json:"block_hash"` - PreviousBlockHash string `json:"previous_block_hash"` - Transaction *transaction.Transaction `json:"txn,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - Status int `json:"transaction_status" msgpack:"sot"` - RoundRandomSeed int64 `json:"round_random_seed"` - StateChangesCount int `json:"state_changes_count"` - MerkleTreeRoot string `json:"merkle_tree_root"` - MerkleTreePath *util.MTPath `json:"merkle_tree_path"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` -} - -type blockHeader struct { - Version string `json:"version,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - Hash string `json:"hash,omitempty"` - MinerId string `json:"miner_id,omitempty"` - Round int64 `json:"round,omitempty"` - RoundRandomSeed int64 `json:"round_random_seed,omitempty"` - StateChangesCount int `json:"state_changes_count"` - MerkleTreeRoot string `json:"merkle_tree_root,omitempty"` - StateHash string `json:"state_hash,omitempty"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root,omitempty"` - NumTxns int64 `json:"num_txns,omitempty"` -} - -func (bh *blockHeader) getCreationDate(defaultTime int64) int64 { - if bh == nil { - return defaultTime - } - - return bh.CreationDate -} - -// Transaction data structure that provides the transaction details -type Transaction struct { - txn *transaction.Transaction - txnOut string - txnHash string - txnStatus int - txnError error - txnCb TransactionCallback - verifyStatus int - verifyConfirmationStatus int - verifyOut string - verifyError error -} - -type SendTxnData struct { - Note string `json:"note"` -} - -func Sign(hash string) (string, error) { - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := sigScheme.SetPrivateKey(_config.wallet.Keys[0].PrivateKey) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} - -func SignWithKey(privateKey, hash string) (string, error) { - sigScheme := zcncrypto.NewSignatureScheme("bls0chain") - err := sigScheme.SetPrivateKey(privateKey) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} - -func VerifyWithKey(pubKey, signature, hash string) (bool, error) { - sigScheme := zcncrypto.NewSignatureScheme("bls0chain") - err := sigScheme.SetPublicKey(pubKey) - if err != nil { - return false, err - } - return sigScheme.Verify(signature, hash) -} - -var SignFn = func(hash string) (string, error) { - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := sigScheme.SetPrivateKey(_config.wallet.Keys[0].PrivateKey) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} - -var AddSignature = func(privateKey, signature string, hash string) (string, error) { - var ( - ss = zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err error - ) - - err = ss.SetPrivateKey(privateKey) - if err != nil { - return "", err - } - - return ss.Add(signature, hash) -} - -func signWithWallet(hash string, wi interface{}) (string, error) { - w, ok := wi.(*zcncrypto.Wallet) - - if !ok { - fmt.Printf("Error in casting to wallet") - return "", errors.New("", "error in casting to wallet") - } - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := sigScheme.SetPrivateKey(w.Keys[0].PrivateKey) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} - -func txnTypeString(t int) string { - switch t { - case transaction.TxnTypeSend: - return "send" - case transaction.TxnTypeLockIn: - return "lock-in" - case transaction.TxnTypeData: - return "data" - case transaction.TxnTypeSmartContract: - return "smart contract" - default: - return "unknown" - } -} - -// 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 -} - -func (t *Transaction) completeTxn(status int, out string, err error) { - t.txnStatus = status - t.txnOut = out - t.txnError = err - if t.txnCb != nil { - t.txnCb.OnTransactionComplete(t, t.txnStatus) - } -} - -func (t *Transaction) completeVerify(status int, out string, err error) { - t.completeVerifyWithConStatus(status, 0, out, err) -} - -func (t *Transaction) completeVerifyWithConStatus(status int, conStatus int, out string, err error) { - t.verifyStatus = status - t.verifyConfirmationStatus = conStatus - t.verifyOut = out - t.verifyError = err - if status == StatusError { - node.Cache.Evict(t.txn.ClientID) - } - if t.txnCb != nil { - t.txnCb.OnVerifyComplete(t, t.verifyStatus) - } -} - -type getNonceCallBack struct { - nonceCh chan int64 - err error -} - -func (g getNonceCallBack) OnNonceAvailable(status int, nonce int64, info string) { - if status != StatusSuccess { - g.err = errors.New("get_nonce", "failed respond nonce") //nolint - } - - g.nonceCh <- nonce -} - -func (t *Transaction) setNonceAndSubmit() { - t.setNonce() - t.submitTxn() -} - -func (t *Transaction) setNonce() { - nonce := t.txn.TransactionNonce - if nonce < 1 { - nonce = node.Cache.GetNextNonce(t.txn.ClientID) - } else { - node.Cache.Set(t.txn.ClientID, nonce) - } - t.txn.TransactionNonce = nonce -} - -func (t *Transaction) submitTxn() { - // Clear the status, in case transaction object reused - t.txnStatus = StatusUnknown - t.txnOut = "" - t.txnError = nil - - // If Signature is not passed compute signature - if t.txn.Signature == "" { - err := t.txn.ComputeHashAndSign(SignFn) - if err != nil { - t.completeTxn(StatusError, "", err) - node.Cache.Evict(t.txn.ClientID) - return - } - } - - var ( - randomMiners = GetStableMiners() - minersN = len(randomMiners) - failedCount int32 - failC = make(chan struct{}) - resultC = make(chan *util.PostResponse, minersN) - ) - - for _, miner := range randomMiners { - go func(minerurl string) { - url := minerurl + PUT_TRANSACTION - logging.Info("Submitting ", txnTypeString(t.txn.TransactionType), " transaction to ", minerurl, " with JSON ", string(t.txn.DebugJSON())) - req, err := util.NewHTTPPostRequest(url, t.txn) - if err != nil { - logging.Error(minerurl, " new post request failed. ", err.Error()) - - if int(atomic.AddInt32(&failedCount, 1)) == minersN { - close(failC) - } - return - } - - res, err := req.Post() - if err != nil { - logging.Error(minerurl, " submit transaction error. ", err.Error()) - if int(atomic.AddInt32(&failedCount, 1)) == minersN { - close(failC) - } - return - } - - if res.StatusCode != http.StatusOK { - logging.Error(minerurl, " submit transaction failed with status code ", res.StatusCode) - if int(atomic.AddInt32(&failedCount, 1)) == minersN { - resultC <- res - } - return - } - - resultC <- res - }(miner) - } - - select { - case <-failC: - logging.Error("failed to submit transaction") - t.completeTxn(StatusError, "", fmt.Errorf("failed to submit transaction to all miners")) - node.Cache.Evict(t.txn.ClientID) - ResetStableMiners() - return - case ret := <-resultC: - logging.Debug("finish txn submitting, ", ret.Url, ", Status: ", ret.Status, ", output:", ret.Body) - if ret.StatusCode == http.StatusOK { - t.completeTxn(StatusSuccess, ret.Body, nil) - } else { - t.completeTxn(StatusError, "", fmt.Errorf("submit transaction failed. %s", ret.Body)) - node.Cache.Evict(t.txn.ClientID) - ResetStableMiners() - } - } -} - -// 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.") - } - t.txnCb = cb - 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.") - } - t.txn.TransactionNonce = txnNonce - return nil -} - -// StoreData implements store the data to blockchain -func (t *Transaction) StoreData(data string) error { - go func() { - t.txn.TransactionType = transaction.TxnTypeData - t.txn.TransactionData = data - t.setNonceAndSubmit() - }() - return nil -} - -type TxnFeeOption struct { - // stop estimate txn fee, usually if txn fee was 0, the createSmartContractTxn method would - // estimate the txn fee by calling API from 0chain network. With this option, we could force - // the txn to have zero fee for those exempt transactions. - noEstimateFee bool -} - -// FeeOption represents txn fee related option type -type FeeOption func(*TxnFeeOption) - -// WithNoEstimateFee would prevent txn fee estimation from remote -func WithNoEstimateFee() FeeOption { - return func(o *TxnFeeOption) { - o.noEstimateFee = true - } -} - -// ExecuteFaucetSCWallet implements the Faucet Smart contract for a given wallet -func (t *Transaction) ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error { - w, err := t.createFaucetSCWallet(walletStr, methodName, input) - if err != nil { - return err - } - go func() { - nonce := t.txn.TransactionNonce - if nonce < 1 { - nonce = node.Cache.GetNextNonce(t.txn.ClientID) - } else { - node.Cache.Set(t.txn.ClientID, nonce) - } - t.txn.TransactionNonce = nonce - err = t.txn.ComputeHashAndSignWithWallet(signWithWallet, w) - if err != nil { - return - } - fmt.Printf("submitted transaction\n") - t.submitTxn() - }() - 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.") - } - t.txnHash = hash - return nil -} - -// GetTransactionHash implements retrieval of hash of the submitted transaction -func (t *Transaction) GetTransactionHash() string { - if t.txnHash != "" { - return t.txnHash - } - if t.txnStatus != StatusSuccess { - return "" - } - var txnout map[string]json.RawMessage - err := json.Unmarshal([]byte(t.txnOut), &txnout) - if err != nil { - fmt.Println("Error in parsing", err) - } - var entity map[string]interface{} - err = json.Unmarshal(txnout["entity"], &entity) - if err != nil { - logging.Error("json unmarshal error on GetTransactionHash()") - return t.txnHash - } - if hash, ok := entity["hash"].(string); ok { - t.txnHash = hash - } - return t.txnHash -} - -func queryFromMinersContext(ctx context.Context, numMiners int, query string, result chan *util.GetResponse) { - - randomMiners := util.Shuffle(_config.chain.Miners)[:numMiners] - for _, miner := range randomMiners { - go func(minerurl string) { - logging.Info("Query from ", minerurl+query) - url := fmt.Sprintf("%v%v", minerurl, query) - req, err := util.NewHTTPGetRequestContext(ctx, url) - if err != nil { - logging.Error(minerurl, " new get request failed. ", err.Error()) - return - } - res, err := req.Get() - if err != nil { - logging.Error(minerurl, " get error. ", err.Error()) - } - result <- res - }(miner) - } - -} - -func getBlockHeaderFromTransactionConfirmation(txnHash string, cfmBlock map[string]json.RawMessage) (*blockHeader, error) { - block := &blockHeader{} - if cfmBytes, ok := cfmBlock["confirmation"]; ok { - var cfm confirmation - err := json.Unmarshal(cfmBytes, &cfm) - if err != nil { - return nil, errors.Wrap(err, "txn confirmation parse error.") - } - if cfm.Transaction == nil { - return nil, fmt.Errorf("missing transaction %s in block confirmation", txnHash) - } - if txnHash != cfm.Transaction.Hash { - return nil, fmt.Errorf("invalid transaction hash. Expected: %s. Received: %s", txnHash, cfm.Transaction.Hash) - } - if !util.VerifyMerklePath(cfm.Transaction.Hash, cfm.MerkleTreePath, cfm.MerkleTreeRoot) { - return nil, errors.New("", "txn merkle validation failed.") - } - txnRcpt := transaction.NewTransactionReceipt(cfm.Transaction) - if !util.VerifyMerklePath(txnRcpt.GetHash(), cfm.ReceiptMerkleTreePath, cfm.ReceiptMerkleTreeRoot) { - return nil, errors.New("", "txn receipt cmerkle validation failed.") - } - prevBlockHash := cfm.PreviousBlockHash - block.MinerId = cfm.MinerID - block.Hash = cfm.BlockHash - block.CreationDate = cfm.CreationDate - block.Round = cfm.Round - block.RoundRandomSeed = cfm.RoundRandomSeed - block.StateChangesCount = cfm.StateChangesCount - block.MerkleTreeRoot = cfm.MerkleTreeRoot - block.ReceiptMerkleTreeRoot = cfm.ReceiptMerkleTreeRoot - // Verify the block - if isBlockExtends(prevBlockHash, block) { - return block, nil - } - - return nil, errors.New("", "block hash verification failed in confirmation") - } - - return nil, errors.New("", "txn confirmation not found.") -} - -func getBlockInfoByRound(round int64, content string) (*blockHeader, error) { - numSharders := len(Sharders.Healthy()) // overwrite, use all - resultC := make(chan *util.GetResponse, numSharders) - Sharders.QueryFromSharders(numSharders, fmt.Sprintf("%vround=%v&content=%v", GET_BLOCK_INFO, round, content), resultC) - var ( - maxConsensus int - roundConsensus = make(map[string]int) - waitTime = time.NewTimer(10 * time.Second) - failedCount int - ) - - type blockRound struct { - Header blockHeader `json:"header"` - } - - for i := 0; i < numSharders; i++ { - select { - case <-waitTime.C: - return nil, stdErrors.New("failed to get block info by round with consensus, timeout") - case rsp := <-resultC: - if rsp == nil { - logging.Error("nil response") - continue - } - logging.Debug(rsp.Url, rsp.Status) - if failedCount*100/numSharders > 100-consensusThresh { - return nil, stdErrors.New("failed to get block info by round with consensus, too many failures") - } - - if rsp.StatusCode != http.StatusOK { - logging.Debug(rsp.Url, "no round confirmation. Resp:", rsp.Body) - failedCount++ - continue - } - - var br blockRound - err := json.Unmarshal([]byte(rsp.Body), &br) - if err != nil { - logging.Error("round info parse error. ", err) - failedCount++ - continue - } - - if len(br.Header.Hash) == 0 { - failedCount++ - continue - } - - h := br.Header.Hash - roundConsensus[h]++ - if roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - if maxConsensus*100/numSharders >= consensusThresh { - return &br.Header, nil - } - } - } - } - - return nil, stdErrors.New("failed to get block info by round with consensus") -} - -func isBlockExtends(prevHash string, block *blockHeader) bool { - data := fmt.Sprintf("%v:%v:%v:%v:%v:%v:%v:%v", block.MinerId, prevHash, block.CreationDate, block.Round, - block.RoundRandomSeed, block.StateChangesCount, block.MerkleTreeRoot, block.ReceiptMerkleTreeRoot) - h := encryption.Hash(data) - return block.Hash == h -} - -func validateChain(confirmBlock *blockHeader) bool { - confirmRound := confirmBlock.Round - logging.Debug("Confirmation round: ", confirmRound) - currentBlockHash := confirmBlock.Hash - round := confirmRound + 1 - for { - nextBlock, err := getBlockInfoByRound(round, "header") - if err != nil { - logging.Info(err, " after a second falling thru to ", getMinShardersVerify(), "of ", len(_config.chain.Sharders), "Sharders", len(Sharders.Healthy()), "Healthy sharders") - sys.Sleep(1 * time.Second) - nextBlock, err = getBlockInfoByRound(round, "header") - if err != nil { - logging.Error(err, " block chain stalled. waiting", defaultWaitSeconds, "...") - sys.Sleep(defaultWaitSeconds) - continue - } - } - if isBlockExtends(currentBlockHash, nextBlock) { - currentBlockHash = nextBlock.Hash - round++ - } - if (round > confirmRound) && (round-confirmRound < getMinRequiredChainLength()) { - continue - } - if round < confirmRound { - return false - } - // Validation success - break - } - return true -} -func (t *Transaction) isTransactionExpired(lfbCreationTime, currentTime int64) bool { - // latest finalized block zero implies no response. use currentTime as lfb - if lfbCreationTime == 0 { - lfbCreationTime = currentTime - } - if util.MinInt64(lfbCreationTime, currentTime) > (t.txn.CreationDate + int64(defaultTxnExpirationSeconds)) { - return true - } - // Wait for next retry - sys.Sleep(defaultWaitSeconds) - return false -} - -// GetVerifyOutput implements the verification output from sharders -func (t *Transaction) GetVerifyOutput() string { - if t.verifyStatus == StatusSuccess { - return t.verifyOut - } - return "" -} - -// GetTransactionError implements error string in case of transaction failure -func (t *Transaction) GetTransactionError() string { - if t.txnStatus != StatusSuccess { - return t.txnError.Error() - } - return "" -} - -// GetVerifyError implements error string in case of verify failure error -func (t *Transaction) GetVerifyError() string { - if t.verifyStatus != StatusSuccess { - return t.verifyError.Error() - } - return "" -} - -// GetTransactionNonce returns nonce -func (t *Transaction) GetTransactionNonce() int64 { - return t.txn.TransactionNonce -} - -// ========================================================================== // -// vesting pool // -// ========================================================================== // - -type vestingRequest struct { - PoolID common.Key `json:"pool_id"` -} - -type VestingStopRequest struct { - PoolID string `json:"pool_id"` - Destination string `json:"destination"` -} - -type scCollectReward struct { - ProviderId string `json:"provider_id"` - ProviderType int `json:"provider_type"` -} - -type MinerSCLock struct { - ID string `json:"id"` -} - -type MinerSCUnlock struct { - ID string `json:"id"` -} - -type CommitMetaData struct { - CrudType string - MetaData *ConsolidatedFileMeta -} - -type CommitMetaResponse struct { - TxnID string - MetaData *ConsolidatedFileMeta -} - -type ConsolidatedFileMeta struct { - Name string - Type string - Path string - LookupHash string - Hash string - MimeType string - Size int64 - NumBlocks int64 - ActualFileSize int64 - ActualNumBlocks int64 - EncryptedKey string - - ActualThumbnailSize int64 - ActualThumbnailHash string - - Collaborators []fileref.Collaborator -} - -func VerifyContentHash(metaTxnDataJSON string) (bool, error) { - var metaTxnData CommitMetaResponse - err := json.Unmarshal([]byte(metaTxnDataJSON), &metaTxnData) - if err != nil { - return false, errors.New("metaTxnData_decode_error", "Unable to decode metaTxnData json") - } - - t, err := transaction.VerifyTransaction(metaTxnData.TxnID) - if err != nil { - return false, errors.New("fetch_txm_details", "Unable to fetch txn details") - } - - var metaOperation CommitMetaData - err = json.Unmarshal([]byte(t.TransactionData), &metaOperation) - if err != nil { - logging.Error("Unmarshal of transaction data to fileMeta failed, Maybe not a commit meta txn :", t.Hash) - return false, nil - } - - return metaOperation.MetaData.Hash == metaTxnData.MetaData.Hash, nil -} - -// -// Storage SC transactions -// diff --git a/zcncore/transaction_mobile.go b/zcncore/transaction_mobile.go deleted file mode 100644 index 643a82da1..000000000 --- a/zcncore/transaction_mobile.go +++ /dev/null @@ -1,1686 +0,0 @@ -//go:build mobile -// +build mobile - -package zcncore - -import ( - "context" - "encoding/json" - stderrors "errors" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/block" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/node" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -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 ( - ProviderMiner Provider = iota + 1 - ProviderSharder - ProviderBlobber - ProviderValidator - ProviderAuthorizer -) - -type stakePoolRequest struct { - ProviderType int `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` -} - -// compiler time check -var ( - _ TransactionScheme = (*Transaction)(nil) - _ TransactionScheme = (*TransactionWithAuth)(nil) -) - -type TransactionCommon interface { - ExecuteSmartContract(address string, methodName string, input string, val string) error - - Send(toClientID string, val string, desc string) error - - VestingAdd(ar VestingAddRequest, value string) error - - MinerSCLock(providerId string, providerType int, lock string) error - MinerSCUnlock(providerId string, providerType int) error - MinerSCCollectReward(providerId string, providerType int) error - StorageSCCollectReward(providerId string, providerType int) error - - FinalizeAllocation(allocID string) error - CancelAllocation(allocID string) error - CreateAllocation(car *CreateAllocationRequest, lock string) error - CreateReadPool() error - ReadPoolLock(allocID string, blobberID string, duration int64, lock string) error - ReadPoolUnlock() error - StakePoolLock(providerId string, providerType int, lock string) error - StakePoolUnlock(providerId string, providerType int) error - UpdateBlobberSettings(blobber Blobber) error - UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock string) error - WritePoolLock(allocID string, lock string) error - WritePoolUnlock(allocID string) error - - VestingUpdateConfig(InputMap) error - MinerScUpdateConfig(InputMap) error - MinerScUpdateGlobals(InputMap) error - StorageScUpdateConfig(InputMap) error - FaucetUpdateConfig(InputMap) error - ZCNSCUpdateGlobalConfig(InputMap) error - - MinerSCMinerSettings(MinerSCMinerInfo) error - MinerSCSharderSettings(MinerSCMinerInfo) error - MinerSCDeleteMiner(MinerSCMinerInfo) error - MinerSCDeleteSharder(MinerSCMinerInfo) error - - // ZCNSCUpdateAuthorizerConfig updates authorizer config by ID - ZCNSCUpdateAuthorizerConfig(AuthorizerNode) error - // ZCNSCAddAuthorizer adds authorizer - ZCNSCAddAuthorizer(AddAuthorizerPayload) error - - GetVerifyConfirmationStatus() int -} - -// TransactionScheme implements few methods for block chain. -// -// Note: to be buildable on MacOSX all arguments should have names. -type TransactionScheme interface { - TransactionCommon - // SetTransactionCallback implements storing the callback - // used to call after the transaction or verification is completed - SetTransactionCallback(cb TransactionCallback) error - // StoreData implements store the data to blockchain - StoreData(data string) error - // ExecuteFaucetSCWallet implements the `Faucet Smart contract` for a given wallet - ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error - // GetTransactionHash implements retrieval of hash of the submitted transaction - GetTransactionHash() string - // SetTransactionHash implements verify a previous transaction status - SetTransactionHash(hash string) error - // SetTransactionNonce implements method to set the transaction nonce - SetTransactionNonce(txnNonce int64) error - // Verify implements verify the transaction - Verify() error - // GetVerifyOutput implements the verification output from sharders - GetVerifyOutput() string - // GetTransactionError implements error string in case of transaction failure - GetTransactionError() string - // GetVerifyError implements error string in case of verify failure error - GetVerifyError() string - // GetTransactionNonce returns nonce - GetTransactionNonce() int64 - - // GetDetails returns transaction scheme details. - GetDetails() *transaction.Transaction - - // Output of transaction. - Output() []byte - - // Hash Transaction status regardless of status - Hash() string - - // Vesting SC - - VestingTrigger(poolID string) error - VestingStop(sr *VestingStopRequest) error - VestingUnlock(poolID string) error - VestingDelete(poolID string) error -} - -// priceRange represents a price range allowed by user to filter blobbers. -type priceRange struct { - Min int64 `json:"min"` - Max int64 `json:"max"` -} - -// createAllocationRequest is information to create allocation. -type createAllocationRequest struct { - 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"` - Blobbers []string `json:"blobbers"` - ReadPriceRange priceRange `json:"read_price_range"` - WritePriceRange priceRange `json:"write_price_range"` -} - -type CreateAllocationRequest struct { - DataShards int - ParityShards int - Size int64 - Expiration int64 - Owner string - OwnerPublicKey string - ReadPriceMin int64 - ReadPriceMax int64 - WritePriceMin int64 - WritePriceMax int64 - - blobbers []string -} - -func (car *CreateAllocationRequest) AddBlobber(blobber string) { - car.blobbers = append(car.blobbers, blobber) -} - -func (car *CreateAllocationRequest) toCreateAllocationSCInput() *createAllocationRequest { - return &createAllocationRequest{ - DataShards: car.DataShards, - ParityShards: car.ParityShards, - Size: car.Size, - Expiration: car.Expiration, - Owner: car.Owner, - OwnerPublicKey: car.OwnerPublicKey, - Blobbers: car.blobbers, - ReadPriceRange: priceRange{Min: car.ReadPriceMin, Max: car.ReadPriceMax}, - WritePriceRange: priceRange{Min: car.WritePriceMin, Max: car.WritePriceMax}, - } -} - -type StakePoolSettings struct { - DelegateWallet string `json:"delegate_wallet"` - NumDelegates int `json:"num_delegates"` - ServiceCharge float64 `json:"service_charge"` -} - -type Terms struct { - ReadPrice int64 `json:"read_price"` // tokens / GB - WritePrice int64 `json:"write_price"` // tokens / GB - MaxOfferDuration int64 `json:"max_offer_duration"` -} - -type Blobber interface { - SetTerms(readPrice int64, writePrice int64, minLockDemand float64, maxOfferDuration int64) - SetStakePoolSettings(delegateWallet string, numDelegates int, serviceCharge float64) - SetAvailable(bool) -} - -func NewBlobber(id, baseUrl string, capacity, allocated, lastHealthCheck int64) Blobber { - return &blobber{ - ID: id, - BaseURL: baseUrl, - Capacity: capacity, - Allocated: allocated, - LastHealthCheck: lastHealthCheck, - } -} - -type blobber struct { - ID string `json:"id"` - BaseURL string `json:"url"` - Capacity int64 `json:"capacity"` - Allocated int64 `json:"allocated"` - LastHealthCheck int64 `json:"last_health_check"` - Terms Terms `json:"terms"` - StakePoolSettings StakePoolSettings `json:"stake_pool_settings"` - NotAvailable bool `json:"not_available"` -} - -func (b *blobber) SetStakePoolSettings(delegateWallet string, numDelegates int, serviceCharge float64) { - b.StakePoolSettings = StakePoolSettings{ - DelegateWallet: delegateWallet, - NumDelegates: numDelegates, - ServiceCharge: serviceCharge, - } -} - -func (b *blobber) SetTerms(readPrice int64, writePrice int64, minLockDemand float64, maxOfferDuration int64) { - b.Terms = Terms{ - ReadPrice: readPrice, - WritePrice: writePrice, - MaxOfferDuration: maxOfferDuration, - } -} - -func (b *blobber) SetAvailable(availability bool) { - b.NotAvailable = availability -} - -type Validator interface { - SetStakePoolSettings(delegateWallet string, numDelegates int, serviceCharge float64) -} - -func NewValidator(id string, baseUrl string) Validator { - return &validator{ - ID: common.Key(id), - BaseURL: baseUrl, - } -} - -type validator struct { - ID common.Key `json:"id"` - BaseURL string `json:"url"` - StakePoolSettings StakePoolSettings `json:"stake_pool_settings"` -} - -func (v *validator) SetStakePoolSettings(delegateWallet string, numDelegates int, serviceCharge float64) { - v.StakePoolSettings = StakePoolSettings{ - DelegateWallet: delegateWallet, - NumDelegates: numDelegates, - ServiceCharge: serviceCharge, - } -} - -// 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, - URL: url, - } -} - -type addAuthorizerPayload struct { - PublicKey string `json:"public_key"` - URL string `json:"url"` - 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, - NumDelegates: numDelegates, - ServiceCharge: serviceCharge, - } -} - -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"` -} - -type VestingDest struct { - ID string `json:"id"` // destination ID - Amount int64 `json:"amount"` // amount to vest for the destination -} - -type VestingAddRequest interface { - AddDestinations(id string, amount int64) -} - -func NewVestingAddRequest(desc string, startTime int64, duration int64) VestingAddRequest { - return &vestingAddRequest{ - Description: desc, - StartTime: startTime, - Duration: duration, - } -} - -type vestingAddRequest struct { - Description string `json:"description"` // allow empty - StartTime int64 `json:"start_time"` // - Duration int64 `json:"duration"` // - Destinations []*VestingDest `json:"destinations"` // -} - -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) -} - -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), - } -} - -func (im *inputMap) AddField(key, value string) { - im.Fields[key] = value -} - -func parseCoinStr(vs string) (uint64, error) { - if vs == "" { - return 0, nil - } - - v, err := strconv.ParseUint(vs, 10, 64) - if err != nil { - return 0, fmt.Errorf("invalid token value: %v, err: %v", vs, err) - } - - return v, nil -} - -func newTransaction(cb TransactionCallback, txnFee string, nonce int64) (*Transaction, error) { - t := &Transaction{} - t.txn = transaction.NewTransactionEntity(_config.wallet.ClientID, _config.chain.ChainID, _config.wallet.ClientKey, nonce) - t.txnStatus, t.verifyStatus = StatusUnknown, StatusUnknown - t.txnCb = cb - t.txn.TransactionNonce = nonce - t.txn.TransactionFee = txnFee - return t, nil -} - -// 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 string, nonce int64) (TransactionScheme, error) { - err := CheckConfig() - if err != nil { - return nil, err - } - - if _config.isSplitWallet { - if _config.authUrl == "" { - return nil, errors.New("", "auth url not set") - } - logging.Info("New transaction interface with auth") - return newTransactionWithAuth(cb, txnFee, nonce) - } - - logging.Info("New transaction interface") - t, err := newTransaction(cb, txnFee, nonce) - return t, err -} - -func (t *Transaction) GetDetails() *transaction.Transaction { - return t.txn -} - -func (t *Transaction) createSmartContractTxn(address, methodName string, input interface{}, value string, opts ...FeeOption) error { - sn := transaction.SmartContractTxnData{Name: methodName, InputArgs: input} - snBytes, err := json.Marshal(sn) - if err != nil { - return errors.Wrap(err, "create smart contract failed due to invalid data") - } - - t.txn.TransactionType = transaction.TxnTypeSmartContract - t.txn.ToClientID = address - t.txn.TransactionData = string(snBytes) - t.txn.Value = value - - transactionFeeRaw, err := strconv.ParseUint(t.txn.TransactionFee, 0, 64) - if err != nil { - return err - } - - if transactionFeeRaw > 0 { - return nil - } - - tf := &TxnFeeOption{} - for _, opt := range opts { - opt(tf) - } - - if tf.noEstimateFee { - return nil - } - - // TODO: check if transaction is exempt to avoid unnecessary fee estimation - minFee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, 0.2) - if err != nil { - return err - } - - t.txn.TransactionFee = strconv.FormatUint(minFee, 10) - - return nil -} - -func (t *Transaction) createFaucetSCWallet(walletStr string, methodName string, input []byte) (*zcncrypto.Wallet, error) { - w, err := getWallet(walletStr) - if err != nil { - fmt.Printf("Error while parsing the wallet. %v\n", err) - return nil, err - } - err = t.createSmartContractTxn(FaucetSmartContractAddress, methodName, input, "0") - if err != nil { - return nil, err - } - return w, nil -} - -// ExecuteSmartContract prepare and send a smart contract transaction to the blockchain -func (t *Transaction) ExecuteSmartContract(address string, methodName string, input string, val string) error { - err := t.createSmartContractTxn(address, methodName, input, val) - if err != nil { - return err - } - go func() { - t.setNonceAndSubmit() - }() - - return nil -} - -// Send to send a transaction to a given clientID -func (t *Transaction) Send(toClientID string, val string, desc string) error { - txnData, err := json.Marshal(SendTxnData{Note: desc}) - if err != nil { - return errors.New("", "Could not serialize description to transaction_data") - } - go func() { - t.txn.TransactionType = transaction.TxnTypeSend - t.txn.ToClientID = toClientID - t.txn.Value = val - t.txn.TransactionData = string(txnData) - t.setNonceAndSubmit() - }() - 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 { - txnData, err := json.Marshal(SendTxnData{Note: desc}) - if err != nil { - return errors.New("", "Could not serialize description to transaction_data") - } - go func() { - t.txn.TransactionType = transaction.TxnTypeSend - t.txn.ToClientID = toClientID - t.txn.Value = val - t.txn.Hash = hash - t.txn.TransactionData = string(txnData) - t.txn.Signature = sig - t.txn.CreationDate = CreationDate - t.setNonceAndSubmit() - }() - return nil -} - -func (t *Transaction) VestingAdd(ar VestingAddRequest, value string) ( - err error) { - err = t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_ADD, ar, value) - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingStop(sr *VestingStopRequest) (err error) { - err = t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_STOP, sr, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) vestingPoolTxn(function string, poolID string, value string) error { - - return t.createSmartContractTxn(VestingSmartContractAddress, - function, vestingRequest{PoolID: common.Key(poolID)}, value) -} - -func (t *Transaction) VestingTrigger(poolID string) (err error) { - err = t.vestingPoolTxn(transaction.VESTING_TRIGGER, poolID, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingUnlock(poolID string) (err error) { - err = t.vestingPoolTxn(transaction.VESTING_UNLOCK, poolID, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) VestingDelete(poolID string) (err error) { - err = t.vestingPoolTxn(transaction.VESTING_DELETE, poolID, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCLock(providerId string, providerType int, lock string) error { - pr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - err := t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_LOCK, pr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} - -func (t *Transaction) MinerSCUnlock(providerId string, providerType int) error { - pr := &stakePoolRequest{ - ProviderID: providerId, - ProviderType: providerType, - } - err := t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UNLOCK, pr, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} - -func (t *Transaction) MinerSCCollectReward(providerId string, providerType int) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: providerType, - } - - err := t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_COLLECT_REWARD, pr, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return err -} - -func (t *Transaction) StorageSCCollectReward(providerId string, providerType int) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: providerType, - } - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_COLLECT_REWARD, pr, "0") - if err != nil { - logging.Error(err) - return err - } - go t.setNonceAndSubmit() - return err -} - -// FinalizeAllocation transaction. -func (t *Transaction) FinalizeAllocation(allocID string) (err error) { - type finiRequest struct { - AllocationID string `json:"allocation_id"` - } - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_FINALIZE_ALLOCATION, &finiRequest{ - AllocationID: allocID, - }, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// CancelAllocation transaction. -func (t *Transaction) CancelAllocation(allocID string) error { - type cancelRequest struct { - AllocationID string `json:"allocation_id"` - } - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CANCEL_ALLOCATION, &cancelRequest{ - AllocationID: allocID, - }, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// CreateAllocation transaction. -func (t *Transaction) CreateAllocation(car *CreateAllocationRequest, lock string) error { - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_ALLOCATION, car.toCreateAllocationSCInput(), lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// CreateReadPool for current user. -func (t *Transaction) CreateReadPool() error { - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_READ_POOL, nil, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// ReadPoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (t *Transaction) ReadPoolLock(allocID, blobberID string, - duration int64, lock string) error { - - type lockRequest struct { - Duration time.Duration `json:"duration"` - AllocationID string `json:"allocation_id"` - BlobberID string `json:"blobber_id,omitempty"` - } - - var lr lockRequest - lr.Duration = time.Duration(duration) - lr.AllocationID = allocID - lr.BlobberID = blobberID - - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// ReadPoolUnlock for current user and given pool. -func (t *Transaction) ReadPoolUnlock() error { - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_UNLOCK, nil, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// StakePoolLock used to lock tokens in a stake pool of a blobber. -func (t *Transaction) StakePoolLock(providerId string, providerType int, lock string) error { - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_STAKE_POOL_LOCK, &spr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// StakePoolUnlock by blobberID -func (t *Transaction) StakePoolUnlock(providerId string, providerType int) error { - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := t.createSmartContractTxn(StorageSmartContractAddress, transaction.STORAGESC_STAKE_POOL_UNLOCK, &spr, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// UpdateBlobberSettings update settings of a blobber. -func (t *Transaction) UpdateBlobberSettings(b Blobber) error { - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_BLOBBER_SETTINGS, b, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// UpdateAllocation transaction. -func (t *Transaction) UpdateAllocation(allocID string, sizeDiff int64, - expirationDiff int64, lock string) error { - type updateAllocationRequest struct { - ID string `json:"id"` // allocation id - Size int64 `json:"size"` // difference - Expiration int64 `json:"expiration_date"` // difference - } - - var uar updateAllocationRequest - uar.ID = allocID - uar.Size = sizeDiff - uar.Expiration = expirationDiff - - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_ALLOCATION, &uar, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// WritePoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (t *Transaction) WritePoolLock(allocID, lock string) error { - var lr = struct { - AllocationID string `json:"allocation_id"` - }{ - AllocationID: allocID, - } - - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -// WritePoolUnlock for current user and given pool. -func (t *Transaction) WritePoolUnlock(allocID string) error { - var ur = struct { - AllocationID string `json:"allocation_id"` - }{ - AllocationID: allocID, - } - - err := t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_UNLOCK, &ur, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { t.setNonceAndSubmit() }() - return nil -} - -func (t *Transaction) VestingUpdateConfig(vscc InputMap) (err error) { - err = t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_UPDATE_SETTINGS, vscc, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// faucet smart contract - -func (t *Transaction) FaucetUpdateConfig(ip InputMap) (err error) { - err = t.createSmartContractTxn(FaucetSmartContractAddress, - transaction.FAUCETSC_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -// -// miner SC -// - -func (t *Transaction) MinerScUpdateConfig(ip InputMap) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerScUpdateGlobals(ip InputMap) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_GLOBALS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) StorageScUpdateConfig(ip InputMap) (err error) { - err = t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) ZCNSCUpdateGlobalConfig(ip InputMap) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, - transaction.ZCNSC_UPDATE_GLOBAL_CONFIG, ip, "0") - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -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{ - simpleMiner: simpleMiner{ID: id}, - minerSCDelegatePool: minerSCDelegatePool{ - Settings: StakePoolSettings{ - DelegateWallet: delegateWallet, - NumDelegates: numDelegates, - ServiceCharge: serviceCharge, - }, - }, - } -} - -type minerSCMinerInfo struct { - simpleMiner `json:"simple_miner"` - minerSCDelegatePool `json:"stake_pool"` -} - -func (mi *minerSCMinerInfo) GetID() string { - return mi.ID -} - -type minerSCDelegatePool struct { - Settings StakePoolSettings `json:"settings"` -} - -type simpleMiner struct { - ID string `json:"id"` -} - -func (t *Transaction) MinerSCMinerSettings(info MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_SETTINGS, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCSharderSettings(info MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_SETTINGS, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCDeleteMiner(info MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_DELETE, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - return -} - -func (t *Transaction) MinerSCDeleteSharder(info MinerSCMinerInfo) (err error) { - err = t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_DELETE, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { t.setNonceAndSubmit() }() - 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, - Config: &AuthorizerConfig{Fee: fee}, - } -} - -type authorizerNode struct { - ID string `json:"id"` - Config *AuthorizerConfig `json:"config"` -} - -func (a *authorizerNode) GetID() string { - return a.ID -} - -func (t *Transaction) ZCNSCUpdateAuthorizerConfig(ip AuthorizerNode) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_UPDATE_AUTHORIZER_CONFIG, ip, "0") - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -func (t *Transaction) Verify() error { - if t.txnHash == "" && t.txnStatus == StatusUnknown { - return errors.New("", "invalid transaction. cannot be verified.") - } - if t.txnHash == "" && t.txnStatus == StatusSuccess { - h := t.GetTransactionHash() - if h == "" { - node.Cache.Evict(t.txn.ClientID) - return errors.New("", "invalid transaction. cannot be verified.") - } - } - // If transaction is verify only start from current time - if t.txn.CreationDate == 0 { - t.txn.CreationDate = int64(common.Now()) - } - - tq, err := newTransactionQuery(Sharders.Healthy()) - if err != nil { - logging.Error(err) - return err - } - - go func() { - - for { - - tq.Reset() - // Get transaction confirmationBlock from a random sharder - confirmBlockHeader, confirmationBlock, lfbBlockHeader, err := tq.getFastConfirmation(t.txnHash, nil) - - if err != nil { - now := int64(common.Now()) - - // maybe it is a network or server error - if lfbBlockHeader == nil { - logging.Info(err, " now: ", now) - } else { - logging.Info(err, " now: ", now, ", LFB creation time:", lfbBlockHeader.CreationDate) - } - - // transaction is done or expired. it means random sharder might be outdated, try to query it from s/S sharders to confirm it - if util.MaxInt64(lfbBlockHeader.getCreationDate(now), now) >= (t.txn.CreationDate + int64(defaultTxnExpirationSeconds)) { - logging.Info("falling back to ", getMinShardersVerify(), " of ", len(_config.chain.Sharders), " Sharders", len(Sharders.Healthy()), "Healthy sharders") - confirmBlockHeader, confirmationBlock, lfbBlockHeader, err = tq.getConsensusConfirmation(getMinShardersVerify(), t.txnHash, nil) - } - - // txn not found in fast confirmation/consensus confirmation - if err != nil { - - if lfbBlockHeader == nil { - // no any valid lfb on all sharders. maybe they are network/server errors. try it again - continue - } - - // it is expired - if t.isTransactionExpired(lfbBlockHeader.getCreationDate(now), now) { - t.completeVerify(StatusError, "", errors.New("", `{"error": "verify transaction failed"}`)) - return - } - continue - } - - } - - valid := validateChain(confirmBlockHeader) - if valid { - output, err := json.Marshal(confirmationBlock) - if err != nil { - t.completeVerify(StatusError, "", errors.New("", `{"error": "transaction confirmation json marshal error"`)) - return - } - confJson := confirmationBlock["confirmation"] - - var conf map[string]json.RawMessage - if err := json.Unmarshal(confJson, &conf); err != nil { - return - } - txnJson := conf["txn"] - - var tr map[string]json.RawMessage - if err := json.Unmarshal(txnJson, &tr); err != nil { - return - } - - txStatus := tr["transaction_status"] - switch string(txStatus) { - case "1": - t.completeVerifyWithConStatus(StatusSuccess, Success, string(output), nil) - case "2": - txOutput := tr["transaction_output"] - t.completeVerifyWithConStatus(StatusSuccess, ChargeableError, string(txOutput), nil) - default: - t.completeVerify(StatusError, string(output), nil) - } - return - } - } - }() - return nil -} - -func (t *Transaction) ZCNSCAddAuthorizer(ip AddAuthorizerPayload) (err error) { - err = t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_ADD_AUTHORIZER, ip, "0") - if err != nil { - logging.Error(err) - return - } - go t.setNonceAndSubmit() - return -} - -// EstimateFee estimates transaction fee -func (t *Transaction) EstimateFee(reqPercent float32) (int64, error) { - fee, err := transaction.EstimateFee(t.txn, _config.chain.Miners, reqPercent) - return int64(fee), err -} - -// ConvertTokenToSAS converts ZCN tokens to SAS tokens -// # Inputs -// - token: ZCN tokens -func ConvertTokenToSAS(token float64) uint64 { - return uint64(token * common.TokenUnit) -} - -// ConvertToValue converts ZCN tokens to SAS tokens with string format -// - token: ZCN tokens -func ConvertToValue(token float64) string { - return strconv.FormatUint(ConvertTokenToSAS(token), 10) -} - -func makeTimeoutContext(tm RequestTimeout) (context.Context, func()) { - - if tm != nil && tm.Get() > 0 { - return context.WithTimeout(context.Background(), time.Millisecond*time.Duration(tm.Get())) - - } - return context.Background(), func() {} - -} - -func GetLatestFinalized(numSharders int, timeout RequestTimeout) (b *BlockHeader, err error) { - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil { - logging.Error("block parse error: ", err) - err = nil - continue - } - - var h = encryption.FastHash([]byte(b.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "block info not found") - } - - 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) - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - m *block.MagicBlock - err error - ) - - type respObj struct { - MagicBlock *block.MagicBlock `json:"magic_block"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logging.Error(" magic block parse error: ", err) - err = nil - continue - } - - m = respo.MagicBlock - var h = encryption.FastHash([]byte(respo.MagicBlock.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "magic block info not found") - } - - if m != nil { - return json.Marshal(m) - } - - return nil, err -} - -// GetChainStats gets chain stats with time out -// timeout in milliseconds -func GetChainStats(timeout RequestTimeout) ([]byte, error) { - var result = make(chan *util.GetResponse, 1) - defer close(result) - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - var ( - b *block.ChainStats - err error - ) - - var numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result) - var rsp *util.GetResponse - for i := 0; i < numSharders; i++ { - var x = <-result - if x == nil { - logging.Error("nil response") - continue - } - if x.StatusCode != http.StatusOK { - continue - } - rsp = x - } - - if rsp == nil { - return nil, errors.New("http_request_failed", "Request failed with status not 200") - } - - if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil { - return nil, err - } - - return []byte(rsp.Body), nil -} - -func GetFeeStats(timeout RequestTimeout) ([]byte, error) { - - var numMiners = 4 - - if numMiners > len(_config.chain.Miners) { - numMiners = len(_config.chain.Miners) - } - - var result = make(chan *util.GetResponse, numMiners) - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - var ( - b *block.FeeStats - err error - ) - - queryFromMinersContext(ctx, numMiners, GET_FEE_STATS, result) - var rsp *util.GetResponse - -loop: - for i := 0; i < numMiners; i++ { - select { - case x := <-result: - if x.StatusCode != http.StatusOK { - continue - } - rsp = x - if rsp != nil { - break loop - } - case <-ctx.Done(): - return nil, ctx.Err() - } - } - if rsp == nil { - return nil, errors.New("http_request_failed", "Request failed with status not 200") - } - - if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil { - return nil, err - } - - return []byte(rsp.Body), nil -} - -type BlockHeader struct { - Version string `json:"version,omitempty"` - CreationDate int64 `json:"creation_date,omitempty"` - Hash string `json:"hash,omitempty"` - MinerID string `json:"miner_id,omitempty"` - Round int64 `json:"round,omitempty"` - RoundRandomSeed int64 `json:"round_random_seed,omitempty"` - MerkleTreeRoot string `json:"merkle_tree_root,omitempty"` - StateHash string `json:"state_hash,omitempty"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root,omitempty"` - NumTxns int64 `json:"num_txns,omitempty"` -} - -type Block struct { - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - RoundRandomSeed int64 `json:"round_random_seed"` - RoundTimeoutCount int `json:"round_timeout_count"` - - Hash string `json:"hash"` - Signature string `json:"signature"` - ChainID string `json:"chain_id"` - ChainWeight float64 `json:"chain_weight"` - RunningTxnCount int64 `json:"running_txn_count"` - - Version string `json:"version"` - CreationDate int64 `json:"creation_date"` - - MagicBlockHash string `json:"magic_block_hash"` - PrevHash string `json:"prev_hash"` - - ClientStateHash string `json:"state_hash"` - - // unexported fields - header *BlockHeader `json:"-"` - txns []*transaction.Transaction `json:"transactions,omitempty"` -} - -func (b *Block) GetHeader() *BlockHeader { - return b.header -} - -type IterTxnFunc func(idx int, txn *transaction.Transaction) - -type Transactions struct { - txns []*transaction.Transaction -} - -func (tm *Transactions) Len() int { - return len(tm.txns) -} - -func (tm *Transactions) Get(idx int) (*transaction.Transaction, error) { - if idx < 0 && idx >= len(tm.txns) { - return nil, stderrors.New("index out of bounds") - } - - return tm.txns[idx], nil -} - -func (b *Block) GetTxns() *Transactions { - return &Transactions{ - txns: b.txns, - } -} - -func toMobileBlock(b *block.Block) *Block { - lb := &Block{ - header: &BlockHeader{ - Version: b.Header.Version, - CreationDate: b.Header.CreationDate, - Hash: b.Header.Hash, - MinerID: b.Header.MinerID, - Round: b.Header.Round, - RoundRandomSeed: b.Header.RoundRandomSeed, - MerkleTreeRoot: b.Header.MerkleTreeRoot, - StateHash: b.Header.StateHash, - ReceiptMerkleTreeRoot: b.Header.ReceiptMerkleTreeRoot, - NumTxns: b.Header.NumTxns, - }, - MinerID: string(b.MinerID), - Round: b.Round, - RoundRandomSeed: b.RoundRandomSeed, - RoundTimeoutCount: b.RoundTimeoutCount, - - Hash: string(b.Hash), - Signature: b.Signature, - ChainID: string(b.ChainID), - ChainWeight: b.ChainWeight, - RunningTxnCount: b.RunningTxnCount, - - Version: b.Version, - CreationDate: int64(b.CreationDate), - - MagicBlockHash: b.MagicBlockHash, - PrevHash: b.PrevHash, - - ClientStateHash: string(b.ClientStateHash), - } - - lb.txns = make([]*transaction.Transaction, len(b.Txns)) - for i, txn := range b.Txns { - lb.txns[i] = txn - } - - return lb -} - -// RequestTimeout will be used for setting requests with timeout -type RequestTimeout interface { - Set(int64) // milliseconds - Get() int64 // milliseconds -} - -type timeoutCtx struct { - millisecond int64 -} - -func NewRequestTimeout(timeout int64) RequestTimeout { - return &timeoutCtx{millisecond: timeout} -} - -func (t *timeoutCtx) Set(tm int64) { - t.millisecond = tm -} - -func (t *timeoutCtx) Get() int64 { - return t.millisecond -} - -func GetBlockByRound(numSharders int, round int64, timeout RequestTimeout) (b *Block, err error) { - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, - fmt.Sprintf("%sround=%d&content=full,header", GET_BLOCK_INFO, round), - result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - type respObj struct { - Block *block.Block `json:"block"` - Header *block.Header `json:"header"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logging.Error("block parse error: ", err) - err = nil - continue - } - - if respo.Block == nil { - logging.Debug(rsp.Url, "no block in response:", rsp.Body) - continue - } - - if respo.Header == nil { - logging.Debug(rsp.Url, "no block header in response:", rsp.Body) - continue - } - - if respo.Header.Hash != string(respo.Block.Hash) { - logging.Debug(rsp.Url, "header and block hash mismatch:", rsp.Body) - continue - } - - b = toMobileBlock(respo.Block) - - b.header = &BlockHeader{ - Version: respo.Header.Version, - CreationDate: respo.Header.CreationDate, - Hash: respo.Header.Hash, - MinerID: respo.Header.MinerID, - Round: respo.Header.Round, - RoundRandomSeed: respo.Header.RoundRandomSeed, - MerkleTreeRoot: respo.Header.MerkleTreeRoot, - StateHash: respo.Header.StateHash, - ReceiptMerkleTreeRoot: respo.Header.ReceiptMerkleTreeRoot, - NumTxns: respo.Header.NumTxns, - } - - var h = encryption.FastHash([]byte(b.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "round info not found") - } - - return -} - -func GetMagicBlockByNumber(numSharders int, number int64, timeout RequestTimeout) ([]byte, error) { - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - numSharders = len(Sharders.Healthy()) // overwrite, use all - Sharders.QueryFromShardersContext(ctx, numSharders, - fmt.Sprintf("%smagic_block_number=%d", GET_MAGIC_BLOCK_INFO, number), - result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ret []byte - err error - ) - - type respObj struct { - MagicBlock *block.MagicBlock `json:"magic_block"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - if rsp == nil { - logging.Error("nil response") - continue - } - - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logging.Error(" magic block parse error: ", err) - err = nil - continue - } - - ret = []byte(rsp.Body) - var h = encryption.FastHash([]byte(respo.MagicBlock.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "magic block info not found") - } - - if err != nil { - return nil, err - } - - return ret, nil -} - -// GetFeesTable get fee tables -func GetFeesTable(reqPercent float32) (string, error) { - - fees, err := transaction.GetFeesTable(_config.chain.Miners, reqPercent) - if err != nil { - return "", err - } - - js, err := json.Marshal(fees) - if err != nil { - return "", err - } - - return string(js), nil -} diff --git a/zcncore/transaction_query.go b/zcncore/transaction_query.go deleted file mode 100644 index 31520c4aa..000000000 --- a/zcncore/transaction_query.go +++ /dev/null @@ -1,599 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "context" - "encoding/json" - "errors" - stderrors "errors" - "net/http" - "strconv" - "strings" - "sync" - "time" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/resty" - "github.com/0chain/gosdk_common/core/util" -) - -var ( - ErrNoAvailableSharders = errors.New("zcn: no available sharders") - ErrNoEnoughSharders = errors.New("zcn: sharders is not enough") - ErrNoEnoughOnlineSharders = errors.New("zcn: online sharders is not enough") - ErrInvalidNumSharder = errors.New("zcn: number of sharders is invalid") - ErrNoOnlineSharders = errors.New("zcn: no any online sharder") - ErrSharderOffline = errors.New("zcn: sharder is offline") - ErrInvalidConsensus = errors.New("zcn: invalid consensus") - ErrTransactionNotFound = errors.New("zcn: transaction not found") - ErrTransactionNotConfirmed = errors.New("zcn: transaction not confirmed") - ErrNoAvailableMiners = errors.New("zcn: no available miners") -) - -const ( - SharderEndpointHealthCheck = "/v1/healthcheck" -) - -type QueryResult struct { - Content []byte - StatusCode int - Error error -} - -// QueryResultHandle handle query response, return true if it is a consensus-result -type QueryResultHandle func(result QueryResult) bool - -type TransactionQuery struct { - sync.RWMutex - max int - sharders []string - miners []string - numShardersToBatch int - - selected map[string]interface{} - offline map[string]interface{} -} - -func NewTransactionQuery(sharders []string, miners []string) (*TransactionQuery, error) { - - if len(sharders) == 0 { - return nil, ErrNoAvailableSharders - } - - tq := &TransactionQuery{ - max: len(sharders), - sharders: sharders, - numShardersToBatch: 3, - } - tq.selected = make(map[string]interface{}) - tq.offline = make(map[string]interface{}) - - return tq, nil -} - -func (tq *TransactionQuery) Reset() { - tq.selected = make(map[string]interface{}) - tq.offline = make(map[string]interface{}) -} - -// validate validate data and input -func (tq *TransactionQuery) validate(num int) error { - if tq == nil || tq.max == 0 { - return ErrNoAvailableSharders - } - - if num < 1 { - return ErrInvalidNumSharder - } - - if num > tq.max { - return ErrNoEnoughSharders - } - - if num > (tq.max - len(tq.offline)) { - return ErrNoEnoughOnlineSharders - } - - return nil - -} - -// buildUrl build url with host and parts -func (tq *TransactionQuery) buildUrl(host string, parts ...string) string { - var sb strings.Builder - - sb.WriteString(strings.TrimSuffix(host, "/")) - - for _, it := range parts { - sb.WriteString(it) - } - - return sb.String() -} - -// checkSharderHealth checks the health of a sharder (denoted by host) and returns if it is healthy -// or ErrNoOnlineSharders if no sharders are healthy/up at the moment. -func (tq *TransactionQuery) checkSharderHealth(ctx context.Context, host string) error { - tq.RLock() - _, ok := tq.offline[host] - tq.RUnlock() - if ok { - return ErrSharderOffline - } - - // check health - ctx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - r := resty.New() - requestUrl := tq.buildUrl(host, SharderEndpointHealthCheck) - logging.Info("zcn: check health ", requestUrl) - r.DoGet(ctx, requestUrl) - r.Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - // 5xx: it is a server error, not client error - if resp.StatusCode >= http.StatusInternalServerError { - return thrown.Throw(ErrSharderOffline, resp.Status) - } - - return nil - }) - errs := r.Wait() - - if len(errs) > 0 { - if errors.Is(errs[0], context.DeadlineExceeded) { - return context.DeadlineExceeded - } - tq.Lock() - tq.offline[host] = true - tq.Unlock() - return ErrSharderOffline - } - return nil -} - -// getRandomSharder returns a random healthy sharder -func (tq *TransactionQuery) getRandomSharder(ctx context.Context) (string, error) { - if tq.sharders == nil || len(tq.sharders) == 0 { - return "", ErrNoAvailableMiners - } - - shuffledSharders := util.Shuffle(tq.sharders) - - return shuffledSharders[0], nil -} - -//nolint:unused -func (tq *TransactionQuery) getRandomSharderWithHealthcheck(ctx context.Context) (string, error) { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - shuffledSharders := util.Shuffle(tq.sharders) - for i := 0; i < len(shuffledSharders); i += tq.numShardersToBatch { - var mu sync.Mutex - done := false - errCh := make(chan error, tq.numShardersToBatch) - successCh := make(chan string) - last := i + tq.numShardersToBatch - 1 - - if last > len(shuffledSharders)-1 { - last = len(shuffledSharders) - 1 - } - numShardersOffline := 0 - for j := i; j <= last; j++ { - sharder := shuffledSharders[j] - go func(sharder string) { - err := tq.checkSharderHealth(ctx, sharder) - if err != nil { - errCh <- err - } else { - mu.Lock() - if !done { - successCh <- sharder - done = true - } - mu.Unlock() - } - }(sharder) - } - innerLoop: - for { - select { - case e := <-errCh: - switch e { - case ErrSharderOffline: - tq.RLock() - if len(tq.offline) >= tq.max { - tq.RUnlock() - return "", ErrNoOnlineSharders - } - tq.RUnlock() - numShardersOffline++ - if numShardersOffline >= tq.numShardersToBatch { - break innerLoop - } - case context.DeadlineExceeded: - return "", e - } - case s := <-successCh: - return s, nil - case <-ctx.Done(): - if ctx.Err() == context.DeadlineExceeded { - return "", context.DeadlineExceeded - } - } - } - } - return "", ErrNoOnlineSharders -} - -//getRandomMiner returns a random miner -func (tq *TransactionQuery) getRandomMiner(ctx context.Context) (string, error) { - - if tq.miners == nil || len(tq.miners) == 0 { - return "", ErrNoAvailableMiners - } - - shuffledMiners := util.Shuffle(tq.miners) - - return shuffledMiners[0], nil -} - -// FromAll query transaction from all sharders whatever it is selected or offline in previous queires, and return consensus result -func (tq *TransactionQuery) FromAll(ctx context.Context, query string, handle QueryResultHandle) error { - if tq == nil || tq.max == 0 { - return ErrNoAvailableSharders - } - - urls := make([]string, 0, tq.max) - for _, host := range tq.sharders { - urls = append(urls, tq.buildUrl(host, query)) - } - - r := resty.New() - r.DoGet(ctx, urls...). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - res := QueryResult{ - Content: respBody, - Error: err, - StatusCode: http.StatusBadRequest, - } - - if resp != nil { - res.StatusCode = resp.StatusCode - - logging.Debug(req.URL.String() + " " + resp.Status) - logging.Debug(string(respBody)) - } else { - logging.Debug(req.URL.String()) - - } - - if handle != nil { - if handle(res) { - - cf() - } - } - - return nil - }) - - r.Wait() - - return nil -} - -func (tq *TransactionQuery) GetInfo(ctx context.Context, query string) (*QueryResult, error) { - - consensuses := make(map[int]int) - var maxConsensus int - var consensusesResp QueryResult - // {host}{query} - err := tq.FromAll(ctx, query, - func(qr QueryResult) bool { - //ignore response if it is network error - if qr.StatusCode >= 500 { - return false - } - - consensuses[qr.StatusCode]++ - if consensuses[qr.StatusCode] > maxConsensus { - maxConsensus = consensuses[qr.StatusCode] - consensusesResp = qr - } - - // If number of 200's is equal to number of some other status codes, use 200's. - if qr.StatusCode == http.StatusOK && consensuses[qr.StatusCode] == maxConsensus { - maxConsensus = consensuses[qr.StatusCode] - consensusesResp = qr - } - - return false - - }) - - if err != nil { - return nil, err - } - - if maxConsensus == 0 { - return nil, stderrors.New("zcn: query not found") - } - - rate := maxConsensus * 100 / tq.max - if rate < consensusThresh { - return nil, ErrInvalidConsensus - } - - if consensusesResp.StatusCode != http.StatusOK { - return nil, stderrors.New(string(consensusesResp.Content)) - } - - return &consensusesResp, nil -} - -// FromAny queries transaction from any sharder that is not selected in previous queries. -// use any used sharder if there is not any unused sharder -func (tq *TransactionQuery) FromAny(ctx context.Context, query string, provider Provider) (QueryResult, error) { - - res := QueryResult{ - StatusCode: http.StatusBadRequest, - } - - err := tq.validate(1) - - if err != nil { - return res, err - } - - var host string - - // host, err := tq.getRandomSharder(ctx) - - switch provider { - case ProviderMiner: - host, err = tq.getRandomMiner(ctx) - case ProviderSharder: - host, err = tq.getRandomSharder(ctx) - } - - if err != nil { - return res, err - } - - r := resty.New() - requestUrl := tq.buildUrl(host, query) - - logging.Debug("GET", requestUrl) - - r.DoGet(ctx, requestUrl). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - res.Error = err - if err != nil { - return err - } - - res.Content = respBody - logging.Debug(string(respBody)) - - if resp != nil { - res.StatusCode = resp.StatusCode - } - - return nil - }) - - errs := r.Wait() - - if len(errs) > 0 { - return res, errs[0] - } - - return res, nil - -} - -func (tq *TransactionQuery) getConsensusConfirmation(ctx context.Context, numSharders int, txnHash string) (*blockHeader, map[string]json.RawMessage, *blockHeader, error) { - maxConfirmation := int(0) - txnConfirmations := make(map[string]int) - var confirmationBlockHeader *blockHeader - var confirmationBlock map[string]json.RawMessage - var lfbBlockHeader *blockHeader - maxLfbBlockHeader := int(0) - lfbBlockHeaders := make(map[string]int) - - // {host}/v1/transaction/get/confirmation?hash={txnHash}&content=lfb - err := tq.FromAll(ctx, - tq.buildUrl("", TXN_VERIFY_URL, txnHash, "&content=lfb"), - func(qr QueryResult) bool { - if qr.StatusCode != http.StatusOK { - return false - } - - var cfmBlock map[string]json.RawMessage - err := json.Unmarshal([]byte(qr.Content), &cfmBlock) - if err != nil { - logging.Error("txn confirmation parse error", err) - return false - } - - // parse `confirmation` section as block header - cfmBlockHeader, err := getBlockHeaderFromTransactionConfirmation(txnHash, cfmBlock) - if err != nil { - logging.Error("txn confirmation parse header error", err) - - // parse `latest_finalized_block` section - if lfbRaw, ok := cfmBlock["latest_finalized_block"]; ok { - var lfb blockHeader - err := json.Unmarshal([]byte(lfbRaw), &lfb) - if err != nil { - logging.Error("round info parse error.", err) - return false - } - - lfbBlockHeaders[lfb.Hash]++ - if lfbBlockHeaders[lfb.Hash] > maxLfbBlockHeader { - maxLfbBlockHeader = lfbBlockHeaders[lfb.Hash] - lfbBlockHeader = &lfb - } - } - - return false - } - - txnConfirmations[cfmBlockHeader.Hash]++ - if txnConfirmations[cfmBlockHeader.Hash] > maxConfirmation { - maxConfirmation = txnConfirmations[cfmBlockHeader.Hash] - - if maxConfirmation >= numSharders { - confirmationBlockHeader = cfmBlockHeader - confirmationBlock = cfmBlock - - // it is consensus by enough sharders, and latest_finalized_block is valid - // return true to cancel other requests - return true - } - } - - return false - - }) - - if err != nil { - return nil, nil, lfbBlockHeader, err - } - - if maxConfirmation == 0 { - return nil, nil, lfbBlockHeader, stderrors.New("zcn: transaction not found") - } - - if maxConfirmation < numSharders { - return nil, nil, lfbBlockHeader, ErrInvalidConsensus - } - - return confirmationBlockHeader, confirmationBlock, lfbBlockHeader, nil -} - -// getFastConfirmation get txn confirmation from a random online sharder -func (tq *TransactionQuery) getFastConfirmation(ctx context.Context, txnHash string) (*blockHeader, map[string]json.RawMessage, *blockHeader, error) { - var confirmationBlockHeader *blockHeader - var confirmationBlock map[string]json.RawMessage - var lfbBlockHeader blockHeader - - // {host}/v1/transaction/get/confirmation?hash={txnHash}&content=lfb - result, err := tq.FromAny(ctx, tq.buildUrl("", TXN_VERIFY_URL, txnHash, "&content=lfb"), ProviderSharder) - if err != nil { - return nil, nil, nil, err - } - - if result.StatusCode == http.StatusOK { - - err = json.Unmarshal(result.Content, &confirmationBlock) - if err != nil { - logging.Error("txn confirmation parse error", err) - return nil, nil, nil, err - } - - // parse `confirmation` section as block header - confirmationBlockHeader, err = getBlockHeaderFromTransactionConfirmation(txnHash, confirmationBlock) - if err == nil { - return confirmationBlockHeader, confirmationBlock, nil, nil - } - - logging.Error("txn confirmation parse header error", err) - - // parse `latest_finalized_block` section - lfbRaw, ok := confirmationBlock["latest_finalized_block"] - if !ok { - return confirmationBlockHeader, confirmationBlock, nil, err - } - - err = json.Unmarshal([]byte(lfbRaw), &lfbBlockHeader) - if err == nil { - return confirmationBlockHeader, confirmationBlock, &lfbBlockHeader, ErrTransactionNotConfirmed - } - - logging.Error("round info parse error.", err) - return nil, nil, nil, err - - } - - return nil, nil, nil, thrown.Throw(ErrTransactionNotFound, strconv.Itoa(result.StatusCode)) -} - -func GetInfoFromSharders(urlSuffix string, op int, cb GetInfoCallback) { - - tq, err := NewTransactionQuery(util.Shuffle(Sharders.Healthy()), []string{}) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - qr, err := tq.GetInfo(context.TODO(), urlSuffix) - if err != nil { - if qr != nil && op == OpGetMintNonce { - logging.Debug("OpGetMintNonce QueryResult error", "; Content = ", qr.Content, "; Error = ", qr.Error.Error(), "; StatusCode = ", qr.StatusCode) - cb.OnInfoAvailable(op, qr.StatusCode, "", qr.Error.Error()) - return - } - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - cb.OnInfoAvailable(op, StatusSuccess, string(qr.Content), "") -} - -func GetInfoFromAnySharder(urlSuffix string, op int, cb GetInfoCallback) { - - tq, err := NewTransactionQuery(util.Shuffle(Sharders.Healthy()), []string{}) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - qr, err := tq.FromAny(context.TODO(), urlSuffix, ProviderSharder) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - cb.OnInfoAvailable(op, StatusSuccess, string(qr.Content), "") -} - -func GetInfoFromAnyMiner(urlSuffix string, op int, cb getInfoCallback) { - - tq, err := NewTransactionQuery([]string{}, util.Shuffle(_config.chain.Miners)) - - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - qr, err := tq.FromAny(context.TODO(), urlSuffix, ProviderMiner) - - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - cb.OnInfoAvailable(op, StatusSuccess, string(qr.Content), "") -} - -func GetEvents(cb GetInfoCallback, filters map[string]string) (err error) { - if err = CheckConfig(); err != nil { - return - } - go GetInfoFromSharders(WithParams(GET_MINERSC_EVENTS, Params{ - "block_number": filters["block_number"], - "tx_hash": filters["tx_hash"], - "type": filters["type"], - "tag": filters["tag"], - }), 0, cb) - return -} - -func WithParams(uri string, params Params) string { - return withParams(uri, params) -} diff --git a/zcncore/transaction_query_base.go b/zcncore/transaction_query_base.go deleted file mode 100644 index 74eb52630..000000000 --- a/zcncore/transaction_query_base.go +++ /dev/null @@ -1,81 +0,0 @@ -package zcncore - -import ( - "encoding/json" - stderrors "errors" - - thrown "github.com/0chain/errors" -) - -// GetUserLockedTotal get total token user locked -// # Inputs -// - clientID wallet id -func GetUserLockedTotal(clientID string) (int64, error) { - - err := checkSdkInit() - if err != nil { - return 0, err - } - - var url = withParams(STORAGESC_GET_USER_LOCKED_TOTAL, Params{ - "client_id": clientID, - }) - cb := createGetInfoCallback() - go GetInfoFromSharders(url, OpStorageSCGetStakePoolInfo, cb) - info, err := cb.Wait() - if err != nil { - return 0, err - } - - result := make(map[string]int64) - - err = json.Unmarshal([]byte(info), &result) - if err != nil { - return 0, thrown.Throw(err, "invalid json format") - } - - total, ok := result["total"] - if ok { - return total, nil - } - - return 0, stderrors.New("invalid result") - -} - -func createGetInfoCallback() *getInfoCallback { - return &getInfoCallback{ - callback: make(chan bool), - } -} - -type getInfoCallback struct { - callback chan bool - status int - info string - err string -} - -func (cb *getInfoCallback) OnInfoAvailable(op int, status int, info string, err string) { - - // if status == StatusSuccess then info is valid - // is status != StatusSuccess then err will give the reason - - cb.status = status - if status == StatusSuccess { - cb.info = info - } else { - cb.err = err - } - - cb.callback <- true -} - -func (cb *getInfoCallback) Wait() (string, error) { - <-cb.callback - if cb.err == "" { - return cb.info, nil - } - - return "", stderrors.New(cb.err) -} diff --git a/zcncore/transaction_query_mobile.go b/zcncore/transaction_query_mobile.go deleted file mode 100644 index cd9e80399..000000000 --- a/zcncore/transaction_query_mobile.go +++ /dev/null @@ -1,491 +0,0 @@ -//go:build mobile -// +build mobile - -package zcncore - -import ( - "context" - "encoding/json" - "errors" - stderrors "errors" - "math/rand" - "net/http" - "strconv" - "strings" - "time" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/resty" - "github.com/0chain/gosdk_common/core/util" -) - -var ( - ErrNoAvailableSharders = errors.New("zcn: no available sharders") - ErrNoEnoughSharders = errors.New("zcn: sharders is not enough") - ErrNoEnoughOnlineSharders = errors.New("zcn: online sharders is not enough") - ErrInvalidNumSharder = errors.New("zcn: number of sharders is invalid") - ErrNoOnlineSharders = errors.New("zcn: no any online sharder") - ErrSharderOffline = errors.New("zcn: sharder is offline") - ErrInvalidConsensus = errors.New("zcn: invalid consensus") - ErrTransactionNotFound = errors.New("zcn: transaction not found") - ErrTransactionNotConfirmed = errors.New("zcn: transaction not confirmed") -) - -const ( - SharderEndpointHealthCheck = "/_health_check" -) - -type QueryResult struct { - Content []byte - StatusCode int - Error error -} - -// queryResultHandle handle query response, return true if it is a consensus-result -type queryResultHandle func(result QueryResult) bool - -type transactionQuery struct { - max int - sharders []string - - selected map[string]interface{} - offline map[string]interface{} -} - -func (tq *transactionQuery) Reset() { - tq.selected = make(map[string]interface{}) - tq.offline = make(map[string]interface{}) -} - -// validate validate data and input -func (tq *transactionQuery) validate(num int) error { - if tq == nil || tq.max == 0 { - return ErrNoAvailableSharders - } - - if num < 1 { - return ErrInvalidNumSharder - } - - if num > tq.max { - return ErrNoEnoughSharders - } - - if num > (tq.max - len(tq.offline)) { - return ErrNoEnoughOnlineSharders - } - - return nil - -} - -// buildUrl build url with host and parts -func (tq *transactionQuery) buildUrl(host string, parts ...string) string { - var sb strings.Builder - - sb.WriteString(strings.TrimSuffix(host, "/")) - - for _, it := range parts { - sb.WriteString(it) - } - - return sb.String() -} - -// checkHealth check health -func (tq *transactionQuery) checkHealth(ctx context.Context, host string) error { - - _, ok := tq.offline[host] - if ok { - return ErrSharderOffline - } - - // check health - r := resty.New() - requestUrl := tq.buildUrl(host, SharderEndpointHealthCheck) - logging.Info("zcn: check health ", requestUrl) - r.DoGet(ctx, requestUrl) - r.Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - if err != nil { - return err - } - - // 5xx: it is a server error, not client error - if resp.StatusCode >= http.StatusInternalServerError { - return thrown.Throw(ErrSharderOffline, resp.Status) - } - - return nil - }) - errs := r.Wait() - - if len(errs) > 0 { - tq.offline[host] = true - - if len(tq.offline) >= tq.max { - return ErrNoOnlineSharders - } - } - - return nil -} - -// randOne random one health sharder -func (tq *transactionQuery) randOne(ctx context.Context) (string, error) { - - randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - for { - - // reset selected if all sharders were selected - if len(tq.selected) >= tq.max { - tq.selected = make(map[string]interface{}) - } - - i := randGen.Intn(len(tq.sharders)) - host := tq.sharders[i] - - _, ok := tq.selected[host] - - // it was selected, try next - if ok { - continue - } - - tq.selected[host] = true - - err := tq.checkHealth(ctx, host) - - if err != nil { - if errors.Is(err, ErrNoOnlineSharders) { - return "", err - } - - // it is offline, try next one - continue - } - - return host, nil - } -} - -func newTransactionQuery(sharders []string) (*transactionQuery, error) { - - if len(sharders) == 0 { - return nil, ErrNoAvailableSharders - } - - tq := &transactionQuery{ - max: len(sharders), - sharders: sharders, - } - tq.selected = make(map[string]interface{}) - tq.offline = make(map[string]interface{}) - - return tq, nil -} - -// fromAll query transaction from all sharders whatever it is selected or offline in previous queires, and return consensus result -func (tq *transactionQuery) fromAll(query string, handle queryResultHandle, timeout RequestTimeout) error { - if tq == nil || tq.max == 0 { - return ErrNoAvailableSharders - } - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - urls := make([]string, 0, tq.max) - for _, host := range tq.sharders { - urls = append(urls, tq.buildUrl(host, query)) - } - - r := resty.New() - r.DoGet(ctx, urls...). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - res := QueryResult{ - Content: respBody, - Error: err, - StatusCode: http.StatusBadRequest, - } - - if resp != nil { - res.StatusCode = resp.StatusCode - - logging.Debug(req.URL.String() + " " + resp.Status) - logging.Debug(string(respBody)) - } else { - logging.Debug(req.URL.String()) - - } - - if handle != nil { - if handle(res) { - - cf() - } - } - - return nil - }) - - r.Wait() - - return nil -} - -// fromAny query transaction from any sharder that is not selected in previous queires. use any used sharder if there is not any unused sharder -func (tq *transactionQuery) fromAny(query string, timeout RequestTimeout) (QueryResult, error) { - res := QueryResult{ - StatusCode: http.StatusBadRequest, - } - - ctx, cancel := makeTimeoutContext(timeout) - defer cancel() - - err := tq.validate(1) - - if err != nil { - return res, err - } - - host, err := tq.randOne(ctx) - - if err != nil { - return res, err - } - - r := resty.New() - requestUrl := tq.buildUrl(host, query) - - logging.Debug("GET", requestUrl) - - r.DoGet(ctx, requestUrl). - Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { - res.Error = err - if err != nil { - return err - } - - res.Content = respBody - logging.Debug(string(respBody)) - - if resp != nil { - res.StatusCode = resp.StatusCode - } - - return nil - }) - - errs := r.Wait() - - if len(errs) > 0 { - return res, errs[0] - } - - return res, nil - -} - -func (tq *transactionQuery) getInfo(query string, timeout RequestTimeout) (*QueryResult, error) { - - consensuses := make(map[int]int) - var maxConsensus int - var consensusesResp QueryResult - // {host}{query} - - err := tq.fromAll(query, - func(qr QueryResult) bool { - //ignore response if it is network error - if qr.StatusCode >= 500 { - return false - } - - consensuses[qr.StatusCode]++ - if consensuses[qr.StatusCode] >= maxConsensus { - maxConsensus = consensuses[qr.StatusCode] - consensusesResp = qr - } - - return false - - }, timeout) - - if err != nil { - return nil, err - } - - if maxConsensus == 0 { - return nil, stderrors.New("zcn: query not found") - } - - rate := float32(maxConsensus*100) / float32(tq.max) - if rate < consensusThresh { - return nil, ErrInvalidConsensus - } - - if consensusesResp.StatusCode != http.StatusOK { - return nil, stderrors.New(string(consensusesResp.Content)) - } - - return &consensusesResp, nil -} - -func (tq *transactionQuery) getConsensusConfirmation(numSharders int, txnHash string, timeout RequestTimeout) (*blockHeader, map[string]json.RawMessage, *blockHeader, error) { - var maxConfirmation int - txnConfirmations := make(map[string]int) - var confirmationBlockHeader *blockHeader - var confirmationBlock map[string]json.RawMessage - var lfbBlockHeader *blockHeader - maxLfbBlockHeader := int(0) - lfbBlockHeaders := make(map[string]int) - - // {host}/v1/transaction/get/confirmation?hash={txnHash}&content=lfb - err := tq.fromAll(tq.buildUrl("", TXN_VERIFY_URL, txnHash, "&content=lfb"), - func(qr QueryResult) bool { - if qr.StatusCode != http.StatusOK { - return false - } - - var cfmBlock map[string]json.RawMessage - err := json.Unmarshal([]byte(qr.Content), &cfmBlock) - if err != nil { - logging.Error("txn confirmation parse error", err) - return false - } - - // parse `confirmation` section as block header - cfmBlockHeader, err := getBlockHeaderFromTransactionConfirmation(txnHash, cfmBlock) - if err != nil { - logging.Error("txn confirmation parse header error", err) - - // parse `latest_finalized_block` section - if lfbRaw, ok := cfmBlock["latest_finalized_block"]; ok { - var lfb blockHeader - err := json.Unmarshal([]byte(lfbRaw), &lfb) - if err != nil { - logging.Error("round info parse error.", err) - return false - } - - lfbBlockHeaders[lfb.Hash]++ - if lfbBlockHeaders[lfb.Hash] > maxLfbBlockHeader { - maxLfbBlockHeader = lfbBlockHeaders[lfb.Hash] - lfbBlockHeader = &lfb - } - } - - return false - } - - txnConfirmations[cfmBlockHeader.Hash]++ - if txnConfirmations[cfmBlockHeader.Hash] > maxConfirmation { - maxConfirmation = txnConfirmations[cfmBlockHeader.Hash] - - if maxConfirmation >= numSharders { - confirmationBlockHeader = cfmBlockHeader - confirmationBlock = cfmBlock - - // it is consensus by enough sharders, and latest_finalized_block is valid - // return true to cancel other requests - return true - } - } - - return false - - }, timeout) - - if err != nil { - return nil, nil, lfbBlockHeader, err - } - - if maxConfirmation == 0 { - return nil, nil, lfbBlockHeader, stderrors.New("zcn: transaction not found") - } - - if maxConfirmation < numSharders { - return nil, nil, lfbBlockHeader, ErrInvalidConsensus - } - - return confirmationBlockHeader, confirmationBlock, lfbBlockHeader, nil -} - -// getFastConfirmation get txn confirmation from a random online sharder -func (tq *transactionQuery) getFastConfirmation(txnHash string, timeout RequestTimeout) (*blockHeader, map[string]json.RawMessage, *blockHeader, error) { - var confirmationBlockHeader *blockHeader - var confirmationBlock map[string]json.RawMessage - var lfbBlockHeader blockHeader - - // {host}/v1/transaction/get/confirmation?hash={txnHash}&content=lfb - result, err := tq.fromAny(tq.buildUrl("", TXN_VERIFY_URL, txnHash, "&content=lfb"), timeout) - if err != nil { - return nil, nil, nil, err - } - - if result.StatusCode == http.StatusOK { - - err = json.Unmarshal(result.Content, &confirmationBlock) - if err != nil { - logging.Error("txn confirmation parse error", err) - return nil, nil, nil, err - } - - // parse `confirmation` section as block header - confirmationBlockHeader, err = getBlockHeaderFromTransactionConfirmation(txnHash, confirmationBlock) - if err == nil { - return confirmationBlockHeader, confirmationBlock, nil, nil - } - - logging.Error("txn confirmation parse header error", err) - - // parse `latest_finalized_block` section - lfbRaw, ok := confirmationBlock["latest_finalized_block"] - if !ok { - return confirmationBlockHeader, confirmationBlock, nil, err - } - - err = json.Unmarshal([]byte(lfbRaw), &lfbBlockHeader) - if err == nil { - return confirmationBlockHeader, confirmationBlock, &lfbBlockHeader, ErrTransactionNotConfirmed - } - - logging.Error("round info parse error.", err) - return nil, nil, nil, err - - } - - return nil, nil, nil, thrown.Throw(ErrTransactionNotFound, strconv.Itoa(result.StatusCode)) -} - -func GetInfoFromSharders(urlSuffix string, op int, cb GetInfoCallback) { - - tq, err := newTransactionQuery(util.Shuffle(Sharders.Healthy())) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - qr, err := tq.getInfo(urlSuffix, nil) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - cb.OnInfoAvailable(op, StatusSuccess, string(qr.Content), "") -} - -func GetInfoFromAnySharder(urlSuffix string, op int, cb GetInfoCallback) { - - tq, err := newTransactionQuery(util.Shuffle(Sharders.Healthy())) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - qr, err := tq.fromAny(urlSuffix, nil) - if err != nil { - cb.OnInfoAvailable(op, StatusError, "", err.Error()) - return - } - - cb.OnInfoAvailable(op, StatusSuccess, string(qr.Content), "") -} diff --git a/zcncore/transaction_query_test.go b/zcncore/transaction_query_test.go deleted file mode 100644 index 1bf8da5fb..000000000 --- a/zcncore/transaction_query_test.go +++ /dev/null @@ -1,250 +0,0 @@ -package zcncore - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "log" - "math/rand" - "net" - "net/http" - "os" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -const ( - keyServerAddr = "serverAddr" - addrPrefix = "http://localhost" -) - -var tq *TransactionQuery -var numSharders int -var avgTimeToFindSharder float32 -var maxTimePerIteration float32 -var sharders []string - -type SharderHealthStatus struct { - Host string `json:"host"` - HealthStatus string `json:"health"` -} - -func TestMain(m *testing.M) { - numSharders = 10 - sharders = make([]string, 0) - for i := 0; i < numSharders; i++ { - port := fmt.Sprintf(":600%d", i) - sharders = append(sharders, addrPrefix+port) - } - startMockSharderServers(sharders) - // wait for 2s for all servers to start - time.Sleep(2 * time.Second) - exitVal := m.Run() - os.Exit(exitVal) -} - -func TestGetRandomSharder(t *testing.T) { - var err error - tq, err = NewTransactionQuery(sharders, []string{}) - if err != nil { - t.Fatalf("Failed to create new transaction query: %v", err) - } - - for _, tc := range []struct { - name string - onlineSharders []string - expectedErr error - setupContext func(ctx context.Context) context.Context - }{ - { - name: "context deadline exceeded", - onlineSharders: []string{"http://localhost:6009"}, - expectedErr: context.DeadlineExceeded, - setupContext: func(ct context.Context) context.Context { - ctx, cancel := context.WithTimeout(ct, 100*time.Microsecond) - go func() { - <-ctx.Done() - cancel() - }() - return ctx - }, - }, - { - name: "all sharders online", - onlineSharders: sharders, - expectedErr: nil, - }, - { - name: "only one sharder online", - onlineSharders: []string{"http://localhost:6000"}, - expectedErr: nil, - }, - { - name: "few sharders online", - onlineSharders: []string{"http://localhost:6001", "http://localhost:6006", "http://localhost:6009"}, - expectedErr: nil, - }, - { - name: "all sharders offline", - onlineSharders: []string{}, - expectedErr: ErrNoOnlineSharders, - }, - } { - t.Run(tc.name, func(t *testing.T) { - tq.Reset() - - for _, s := range sharders { - if !contains(tc.onlineSharders, s) { - tq.Lock() - tq.offline[s] = true - tq.Unlock() - } - } - ctx := context.Background() - if tc.setupContext != nil { - ctx = tc.setupContext(ctx) - } - sharder, err := tq.getRandomSharderWithHealthcheck(ctx) - if tc.expectedErr == nil { - require.NoError(t, err) - require.Subset(t, tc.onlineSharders, []string{sharder}) - } else { - require.EqualError(t, err, tc.expectedErr.Error()) - } - }) - } -} - -// Maybe replace this with the standard go benchmark later on -func TestGetRandomSharderAndBenchmark(t *testing.T) { - var err error - tq, err = NewTransactionQuery(sharders, []string{}) - if err != nil { - t.Fatalf("Failed to create new transaction query: %v", err) - } - - done := make(chan struct{}) - go startAndStopShardersRandomly(done) - fetchRandomSharderAndBenchmark(t) - close(done) -} - -func startMockSharderServers(sharders []string) { - for i := range sharders { - url := fmt.Sprintf(":600%d", i) - go func(url string) { - ctx, cancel := context.WithCancel(context.Background()) - mx := http.NewServeMux() - mx.HandleFunc(SharderEndpointHealthCheck, getSharderHealth) - httpServer := &http.Server{ - Addr: url, - Handler: mx, - BaseContext: func(l net.Listener) context.Context { - ctx := context.WithValue(ctx, keyServerAddr, url) // nolint - return ctx - }, - } - log.Printf("Starting sharder server at: %v", url) - err := httpServer.ListenAndServe() - if errors.Is(err, http.ErrServerClosed) { - log.Printf("server %v closed\n", httpServer.Addr) - } else if err != nil { - log.Printf("error listening for server one: %s\n", err) - } - cancel() - }(url) - } -} - -func getSharderHealth(w http.ResponseWriter, req *http.Request) { - ctx := req.Context() - sharderHost := ctx.Value(keyServerAddr).(string) - tq.RLock() - _, ok := tq.offline[sharderHost] - tq.RUnlock() - if ok { - errorAny(w, 404, fmt.Sprintf("sharder %v is offline", sharderHost)) - } else { - healthStatus := &SharderHealthStatus{ - Host: sharderHost, - HealthStatus: "healthy", - } - err := json.NewEncoder(w).Encode(healthStatus) - if err != nil { - errorAny(w, http.StatusInternalServerError, "failed to encode json") - } - } -} - -func startAndStopShardersRandomly(done chan struct{}) { - for { - select { - case <-time.After(5 * time.Millisecond): - tq.Lock() - // mark a random sharder offline every 5ms - randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - randomSharder := tq.sharders[randGen.Intn(numSharders)] - tq.offline[randomSharder] = true - tq.Unlock() - - case <-time.After(3 * time.Millisecond): - tq.Lock() - // mark a random sharder online every 3ms - randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - randomSharder := tq.sharders[randGen.Intn(numSharders)] - delete(tq.offline, randomSharder) - tq.Unlock() - - case <-time.After(5 * time.Second): - //Randomly mark all sharders online every 5s - tq.Lock() - tq.Reset() - tq.Unlock() - case <-done: - return - } - } -} - -func fetchRandomSharderAndBenchmark(t *testing.T) { - numIterations := 5 - for i := 0; i < numIterations; i++ { - // Sleep for sometime to have some random sharders started and stopped - time.Sleep(20 * time.Millisecond) - ctx := context.Background() - start := time.Now() - _, err := tq.getRandomSharderWithHealthcheck(ctx) - if err != nil { - t.Fatalf("Failed to get a random sharder err: %v", err) - } - end := float32(time.Since(start) / time.Microsecond) - if end > maxTimePerIteration { - maxTimePerIteration = end - } - avgTimeToFindSharder += end - - } - avgTimeToFindSharder = (avgTimeToFindSharder / float32(numIterations)) / 1000 - maxTimePerIteration /= 1000 - t.Logf("Average time to find a random sharder: %vms and max time for an iteration: %vms", avgTimeToFindSharder, maxTimePerIteration) -} - -func errorAny(w http.ResponseWriter, status int, msg string) { - httpMsg := fmt.Sprintf("%d %s", status, http.StatusText(status)) - if msg != "" { - httpMsg = fmt.Sprintf("%s - %s", httpMsg, msg) - } - http.Error(w, httpMsg, status) -} - -func contains(list []string, e string) bool { - for _, l := range list { - if l == e { - return true - } - } - return false -} diff --git a/zcncore/transactionauth.go b/zcncore/transactionauth.go deleted file mode 100644 index 74ff88278..000000000 --- a/zcncore/transactionauth.go +++ /dev/null @@ -1,663 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "encoding/json" - "fmt" - "math" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/transaction" -) - -func newTransactionWithAuth(cb TransactionCallback, txnFee uint64, nonce int64) (*TransactionWithAuth, error) { - ta := &TransactionWithAuth{} - var err error - ta.t, err = newTransaction(cb, txnFee, nonce) - return ta, err -} - -func (ta *TransactionWithAuth) ExecuteSmartContract(address, methodName string, - input interface{}, val uint64, feeOpts ...FeeOption) (*transaction.Transaction, error) { - err := ta.t.createSmartContractTxn(address, methodName, input, val, feeOpts...) - if err != nil { - return nil, err - } - go func() { - ta.submitTxn() - }() - return ta.t.txn, nil -} - -func (ta *TransactionWithAuth) Send(toClientID string, val uint64, desc string) error { - txnData, err := json.Marshal(transaction.SmartContractTxnData{Name: "transfer", InputArgs: SendTxnData{Note: desc}}) - if err != nil { - return errors.New("", "Could not serialize description to transaction_data") - } - - ta.t.txn.TransactionType = transaction.TxnTypeSend - ta.t.txn.ToClientID = toClientID - ta.t.txn.Value = val - ta.t.txn.TransactionData = string(txnData) - if ta.t.txn.TransactionFee == 0 { - fee, err := transaction.EstimateFee(ta.t.txn, _config.chain.Miners, 0.2) - if err != nil { - return err - } - ta.t.txn.TransactionFee = fee - } - - go func() { - ta.submitTxn() - }() - - return nil -} - -func (ta *TransactionWithAuth) VestingAdd(ar *VestingAddRequest, - value uint64) (err error) { - - err = ta.t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_ADD, ar, value) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCLock(providerId string, providerType Provider, lock uint64) error { - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - pr := &stakePoolRequest{ - ProviderID: providerId, - ProviderType: providerType, - } - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_LOCK, pr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -func (ta *TransactionWithAuth) MinerSCUnlock(providerId string, providerType Provider) error { - pr := &stakePoolRequest{ - ProviderID: providerId, - ProviderType: providerType, - } - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_LOCK, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return err -} - -// FinalizeAllocation transaction. -func (ta *TransactionWithAuth) FinalizeAllocation(allocID string) ( - err error) { - - type finiRequest struct { - AllocationID string `json:"allocation_id"` - } - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_FINALIZE_ALLOCATION, &finiRequest{ - AllocationID: allocID, - }, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// CancelAllocation transaction. -func (ta *TransactionWithAuth) CancelAllocation(allocID string) ( - err error) { - - type cancelRequest struct { - AllocationID string `json:"allocation_id"` - } - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CANCEL_ALLOCATION, &cancelRequest{ - AllocationID: allocID, - }, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// CreateAllocation transaction. -func (ta *TransactionWithAuth) CreateAllocation(car *CreateAllocationRequest, - lock uint64) (err error) { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_ALLOCATION, car, lock) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// CreateReadPool for current user. -func (ta *TransactionWithAuth) CreateReadPool() (err error) { - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_READ_POOL, nil, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// ReadPoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (ta *TransactionWithAuth) ReadPoolLock(allocID, blobberID string, - duration int64, lock uint64) (err error) { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type lockRequest struct { - Duration time.Duration `json:"duration"` - AllocationID string `json:"allocation_id"` - BlobberID string `json:"blobber_id,omitempty"` - } - - var lr lockRequest - lr.Duration = time.Duration(duration) - lr.AllocationID = allocID - lr.BlobberID = blobberID - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// ReadPoolUnlock for current user and given pool. -func (ta *TransactionWithAuth) ReadPoolUnlock() ( - err error) { - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_UNLOCK, nil, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// StakePoolLock used to lock tokens in a stake pool of a blobber. -func (ta *TransactionWithAuth) StakePoolLock(providerId string, providerType Provider, lock uint64) error { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type stakePoolRequest struct { - ProviderType Provider `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_STAKE_POOL_LOCK, &spr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// StakePoolUnlock by blobberID -func (ta *TransactionWithAuth) StakePoolUnlock(providerId string, providerType Provider) error { - - type stakePoolRequest struct { - ProviderType Provider `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_STAKE_POOL_UNLOCK, &spr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// UpdateBlobberSettings update settings of a blobber. -func (ta *TransactionWithAuth) UpdateBlobberSettings(blob *Blobber) ( - err error) { - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_BLOBBER_SETTINGS, blob, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// UpdateValidatorSettings update settings of a validator. -func (ta *TransactionWithAuth) UpdateValidatorSettings(v *Validator) ( - err error) { - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_VALIDATOR_SETTINGS, v, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// UpdateAllocation transaction. -func (ta *TransactionWithAuth) UpdateAllocation(allocID string, sizeDiff int64, - expirationDiff int64, lock uint64) (err error) { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type updateAllocationRequest struct { - ID string `json:"id"` // allocation id - Size int64 `json:"size"` // difference - Expiration int64 `json:"expiration_date"` // difference - } - - var uar updateAllocationRequest - uar.ID = allocID - uar.Size = sizeDiff - uar.Expiration = expirationDiff - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_ALLOCATION, &uar, lock) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// WritePoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (ta *TransactionWithAuth) WritePoolLock(allocID, blobberID string, - duration int64, lock uint64) (err error) { - - if lock > math.MaxInt64 { - return errors.New("invalid_lock", "int64 overflow on lock value") - } - - type lockRequest struct { - Duration time.Duration `json:"duration"` - AllocationID string `json:"allocation_id"` - BlobberID string `json:"blobber_id,omitempty"` - } - - var lr lockRequest - lr.Duration = time.Duration(duration) - lr.AllocationID = allocID - lr.BlobberID = blobberID - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// WritePoolUnlock for current user and given pool. -func (ta *TransactionWithAuth) WritePoolUnlock(allocID string) (err error) { - type unlockRequest struct { - AllocationID string `json:"allocation_id"` - } - - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_UNLOCK, &unlockRequest{ - AllocationID: allocID, - }, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCCollectReward(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_COLLECT_REWARD, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go ta.submitTxn() - return err -} - -func (ta *TransactionWithAuth) MinerSCKill(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - var name string - switch providerType { - case ProviderMiner: - name = transaction.MINERSC_KILL_MINER - case ProviderSharder: - name = transaction.MINERSC_KILL_SHARDER - default: - return fmt.Errorf("kill provider type %v not implimented", providerType) - } - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, name, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go ta.submitTxn() - return err -} - -func (ta *TransactionWithAuth) StorageSCCollectReward(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_COLLECT_REWARD, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return err -} - -func (ta *TransactionWithAuth) VestingUpdateConfig(ip *InputMap) (err error) { - err = ta.t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// faucet smart contract - -func (ta *TransactionWithAuth) FaucetUpdateConfig(ip *InputMap) (err error) { - err = ta.t.createSmartContractTxn(FaucetSmartContractAddress, - transaction.FAUCETSC_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerScUpdateConfig(ip *InputMap) (err error) { - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerScUpdateGlobals(ip *InputMap) (err error) { - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_GLOBALS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) StorageScUpdateConfig(ip *InputMap) (err error) { - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_SETTINGS, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (t *TransactionWithAuth) AddHardfork(ip *InputMap) (err error) { - err = t.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.ADD_HARDFORK, ip, 0) - if err != nil { - logging.Error(err) - return - } - go func() { t.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) ZCNSCUpdateGlobalConfig(ip *InputMap) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_UPDATE_GLOBAL_CONFIG, ip, 0) - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) GetVerifyConfirmationStatus() ConfirmationStatus { - return ta.t.GetVerifyConfirmationStatus() //nolint -} - -func (ta *TransactionWithAuth) MinerSCMinerSettings(info *MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_SETTINGS, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCSharderSettings(info *MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_SETTINGS, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCDeleteMiner(info *MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_DELETE, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCDeleteSharder(info *MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_DELETE, info, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) ZCNSCUpdateAuthorizerConfig(ip *AuthorizerNode) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_UPDATE_AUTHORIZER_CONFIG, ip, 0) - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) ZCNSCAddAuthorizer(ip *AddAuthorizerPayload) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_ADD_AUTHORIZER, ip, 0) - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) ZCNSCAuthorizerHealthCheck(ip *AuthorizerHealthCheckPayload) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_AUTHORIZER_HEALTH_CHECK, ip, 0) - if err != nil { - logging.Error(err) - return - } - go ta.t.setNonceAndSubmit() - return -} - -func (ta *TransactionWithAuth) ZCNSCDeleteAuthorizer(ip *DeleteAuthorizerPayload) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_DELETE_AUTHORIZER, ip, 0) - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) ZCNSCCollectReward(providerId string, providerType Provider) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: int(providerType), - } - err := ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, - transaction.ZCNSC_COLLECT_REWARD, pr, 0) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.t.setNonceAndSubmit() }() - return err -} - -// ========================================================================== // -// vesting pool // -// ========================================================================== // - -func (ta *TransactionWithAuth) VestingTrigger(poolID string) (err error) { - err = ta.t.vestingPoolTxn(transaction.VESTING_TRIGGER, poolID, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) VestingStop(sr *VestingStopRequest) (err error) { - err = ta.t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_STOP, sr, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) VestingUnlock(poolID string) (err error) { - - err = ta.t.vestingPoolTxn(transaction.VESTING_UNLOCK, poolID, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) VestingDelete(poolID string) (err error) { - err = ta.t.vestingPoolTxn(transaction.VESTING_DELETE, poolID, 0) - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} diff --git a/zcncore/transactionauth_base.go b/zcncore/transactionauth_base.go deleted file mode 100644 index ad41c099f..000000000 --- a/zcncore/transactionauth_base.go +++ /dev/null @@ -1,206 +0,0 @@ -package zcncore - -import ( - "encoding/json" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/node" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/zboxcore/client" -) - -type TransactionWithAuth struct { - t *Transaction -} - -func (ta *TransactionWithAuth) Hash() string { - return ta.t.txnHash -} - -func (ta *TransactionWithAuth) SetTransactionNonce(txnNonce int64) error { - return ta.t.SetTransactionNonce(txnNonce) -} - -func (ta *TransactionWithAuth) getAuthorize() (*transaction.Transaction, error) { - ta.t.txn.PublicKey = _config.wallet.ClientKey - err := ta.t.txn.ComputeHashAndSign(SignFn) - if err != nil { - return nil, errors.Wrap(err, "signing error.") - } - - jsonByte, err := json.Marshal(ta.t.txn) - if err != nil { - return nil, err - } - - if sys.Authorize == nil { - return nil, errors.New("not_initialized", "no authorize func is set, define it in native code and set in sys") - } - authorize, err := sys.Authorize(string(jsonByte)) - if err != nil { - return nil, err - } - - var txnResp transaction.Transaction - err = json.Unmarshal([]byte(authorize), &txnResp) - if err != nil { - return nil, errors.Wrap(err, "invalid json on auth response.") - } - // Verify the split key signed signature - ok, err := txnResp.VerifySigWith(client.GetClientPublicKey(), sys.VerifyWith) - if err != nil { - logging.Error("verification failed for txn from auth", err.Error()) - return nil, errAuthVerifyFailed - } - if !ok { - return nil, errAuthVerifyFailed - } - return &txnResp, nil -} - -func (ta *TransactionWithAuth) completeTxn(status int, out string, err error) { - // do error code translation - if status != StatusSuccess { - switch err { - case errNetwork: - status = StatusNetworkError - case errUserRejected: - status = StatusRejectedByUser - case errAuthVerifyFailed: - status = StatusAuthVerifyFailed - case errAuthTimeout: - status = StatusAuthTimeout - } - } - ta.t.completeTxn(status, out, err) //nolint -} - -func verifyFn(signature, msgHash, publicKey string) (bool, error) { - v := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := v.SetPublicKey(publicKey) - if err != nil { - return false, err - } - - ok, err := v.Verify(signature, msgHash) - if err != nil || !ok { - return false, errors.New("", `{"error": "signature_mismatch"}`) - } - return true, nil -} - -func (ta *TransactionWithAuth) sign(otherSig string) error { - ta.t.txn.ComputeHashData() - - sig, err := AddSignature(_config.wallet.Keys[0].PrivateKey, otherSig, ta.t.txn.Hash) - if err != nil { - return err - } - ta.t.txn.Signature = sig - return nil -} - -func (ta *TransactionWithAuth) submitTxn() { - nonce := ta.t.txn.TransactionNonce - if nonce < 1 { - nonce = node.Cache.GetNextNonce(ta.t.txn.ClientID) - } else { - node.Cache.Set(ta.t.txn.ClientID, nonce) - } - ta.t.txn.TransactionNonce = nonce - authTxn, err := ta.getAuthorize() - if err != nil { - logging.Error("get auth error for send, err: ", err.Error()) - ta.completeTxn(StatusAuthError, "", err) - return - } - - // Use the timestamp from auth and sign - ta.t.txn.CreationDate = authTxn.CreationDate - ta.t.txn.Signature = authTxn.Signature - ta.t.submitTxn() -} - -func (ta *TransactionWithAuth) StoreData(data string) error { - go func() { - ta.t.txn.TransactionType = transaction.TxnTypeData - ta.t.txn.TransactionData = data - ta.submitTxn() - }() - return nil -} - -// ExecuteFaucetSCWallet impements the Faucet Smart contract for a given wallet -func (ta *TransactionWithAuth) ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error { - w, err := ta.t.createFaucetSCWallet(walletStr, methodName, input) - if err != nil { - return err - } - go func() { - nonce := ta.t.txn.TransactionNonce - if nonce < 1 { - nonce = node.Cache.GetNextNonce(ta.t.txn.ClientID) - } else { - node.Cache.Set(ta.t.txn.ClientID, nonce) - } - ta.t.txn.TransactionNonce = nonce - err = ta.t.txn.ComputeHashAndSignWithWallet(signWithWallet, w) - if err != nil { - return - } - ta.submitTxn() - }() - return nil -} - -func (ta *TransactionWithAuth) SetTransactionCallback(cb TransactionCallback) error { - return ta.t.SetTransactionCallback(cb) -} - -func (ta *TransactionWithAuth) SetTransactionHash(hash string) error { - return ta.t.SetTransactionHash(hash) -} - -func (ta *TransactionWithAuth) GetTransactionHash() string { - return ta.t.GetTransactionHash() -} - -func (ta *TransactionWithAuth) Verify() error { - return ta.t.Verify() -} - -func (ta *TransactionWithAuth) GetVerifyOutput() string { - return ta.t.GetVerifyOutput() -} - -func (ta *TransactionWithAuth) GetTransactionError() string { - return ta.t.GetTransactionError() -} - -func (ta *TransactionWithAuth) GetVerifyError() string { - return ta.t.GetVerifyError() -} - -func (ta *TransactionWithAuth) Output() []byte { - return []byte(ta.t.txnOut) -} - -// GetTransactionNonce returns nonce -func (ta *TransactionWithAuth) GetTransactionNonce() int64 { - return ta.t.txn.TransactionNonce -} - -// -// miner sc -// - -// RegisterMultiSig register a multisig wallet with the SC. -func (ta *TransactionWithAuth) RegisterMultiSig(walletstr string, mswallet string) error { - return errors.New("", "not implemented") -} - -// -// Storage SC -// diff --git a/zcncore/transactionauth_mobile.go b/zcncore/transactionauth_mobile.go deleted file mode 100644 index 54de85427..000000000 --- a/zcncore/transactionauth_mobile.go +++ /dev/null @@ -1,522 +0,0 @@ -//go:build mobile -// +build mobile - -package zcncore - -import ( - "encoding/json" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/transaction" -) - -func newTransactionWithAuth(cb TransactionCallback, txnFee string, nonce int64) (*TransactionWithAuth, error) { - ta := &TransactionWithAuth{} - var err error - ta.t, err = newTransaction(cb, txnFee, nonce) - return ta, err -} - -func (ta *TransactionWithAuth) GetDetails() *transaction.Transaction { - return ta.t.txn -} - -func (ta *TransactionWithAuth) ExecuteSmartContract(address string, methodName string, input string, val string) error { - err := ta.t.createSmartContractTxn(address, methodName, input, val) - if err != nil { - return err - } - go func() { - ta.submitTxn() - }() - - return nil -} - -func (ta *TransactionWithAuth) Send(toClientID string, val string, desc string) error { - txnData, err := json.Marshal(SendTxnData{Note: desc}) - if err != nil { - return errors.New("", "Could not serialize description to transaction_data") - } - go func() { - ta.t.txn.TransactionType = transaction.TxnTypeSend - ta.t.txn.ToClientID = toClientID - ta.t.txn.Value = val - ta.t.txn.TransactionData = string(txnData) - ta.submitTxn() - }() - return nil -} - -func (ta *TransactionWithAuth) VestingAdd(ar VestingAddRequest, value string) error { - err := ta.t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_ADD, ar, value) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -func (ta *TransactionWithAuth) MinerSCLock(providerId string, providerType int, lock string) error { - pr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_LOCK, &pr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -func (ta *TransactionWithAuth) MinerSCUnlock(providerId string, providerType int) error { - pr := &stakePoolRequest{ - ProviderID: providerId, - ProviderType: providerType, - } - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_LOCK, pr, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return err -} - -// FinalizeAllocation transaction. -func (ta *TransactionWithAuth) FinalizeAllocation(allocID string) error { - type finiRequest struct { - AllocationID string `json:"allocation_id"` - } - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_FINALIZE_ALLOCATION, &finiRequest{ - AllocationID: allocID, - }, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// CancelAllocation transaction. -func (ta *TransactionWithAuth) CancelAllocation(allocID string) error { - type cancelRequest struct { - AllocationID string `json:"allocation_id"` - } - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CANCEL_ALLOCATION, &cancelRequest{ - AllocationID: allocID, - }, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// CreateAllocation transaction. -func (ta *TransactionWithAuth) CreateAllocation(car *CreateAllocationRequest, - lock string) error { - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_ALLOCATION, car, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// CreateReadPool for current user. -func (ta *TransactionWithAuth) CreateReadPool() error { - if err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_CREATE_READ_POOL, nil, "0"); err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// ReadPoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (ta *TransactionWithAuth) ReadPoolLock(allocID, blobberID string, - duration int64, lock string) error { - type lockRequest struct { - Duration time.Duration `json:"duration"` - AllocationID string `json:"allocation_id"` - BlobberID string `json:"blobber_id,omitempty"` - } - - var lr lockRequest - lr.Duration = time.Duration(duration) - lr.AllocationID = allocID - lr.BlobberID = blobberID - - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// ReadPoolUnlock for current user and given pool. -func (ta *TransactionWithAuth) ReadPoolUnlock() error { - if err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_READ_POOL_UNLOCK, nil, "0"); err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// StakePoolLock used to lock tokens in a stake pool of a blobber. -func (ta *TransactionWithAuth) StakePoolLock(providerId string, providerType int, - lock string) error { - type stakePoolRequest struct { - ProviderType int `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_STAKE_POOL_LOCK, &spr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// StakePoolUnlock by blobberID -func (ta *TransactionWithAuth) StakePoolUnlock(providerId string, providerType int) error { - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerId, - } - - if err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_STAKE_POOL_UNLOCK, &spr, "0"); err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// UpdateBlobberSettings update settings of a blobber. -func (ta *TransactionWithAuth) UpdateBlobberSettings(blob Blobber) error { - if err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_BLOBBER_SETTINGS, blob, "0"); err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// UpdateAllocation transaction. -func (ta *TransactionWithAuth) UpdateAllocation(allocID string, sizeDiff int64, - expirationDiff int64, lock string) error { - type updateAllocationRequest struct { - ID string `json:"id"` // allocation id - Size int64 `json:"size"` // difference - Expiration int64 `json:"expiration_date"` // difference - } - - var uar updateAllocationRequest - uar.ID = allocID - uar.Size = sizeDiff - uar.Expiration = expirationDiff - - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_ALLOCATION, &uar, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// WritePoolLock locks tokens for current user and given allocation, using given -// duration. If blobberID is not empty, then tokens will be locked for given -// allocation->blobber only. -func (ta *TransactionWithAuth) WritePoolLock(allocID, lock string) error { - var lr = struct { - AllocationID string `json:"allocation_id"` - }{ - AllocationID: allocID, - } - - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_LOCK, &lr, lock) - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -// WritePoolUnlock for current user and given pool. -func (ta *TransactionWithAuth) WritePoolUnlock(allocID string) error { - var ur = struct { - AllocationID string `json:"allocation_id"` - }{ - AllocationID: allocID, - } - - if err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_WRITE_POOL_UNLOCK, &ur, "0"); err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return nil -} - -func (ta *TransactionWithAuth) MinerSCCollectReward(providerId string, providerType int) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: providerType, - } - err := ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_COLLECT_REWARD, pr, "0") - if err != nil { - logging.Error(err) - return err - } - go ta.submitTxn() - return err -} - -func (ta *TransactionWithAuth) StorageSCCollectReward(providerId string, providerType int) error { - pr := &scCollectReward{ - ProviderId: providerId, - ProviderType: providerType, - } - err := ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_COLLECT_REWARD, pr, "0") - if err != nil { - logging.Error(err) - return err - } - go func() { ta.submitTxn() }() - return err -} - -func (ta *TransactionWithAuth) VestingUpdateConfig(ip InputMap) (err error) { - err = ta.t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -// faucet smart contract - -func (ta *TransactionWithAuth) FaucetUpdateConfig(ip InputMap) (err error) { - err = ta.t.createSmartContractTxn(FaucetSmartContractAddress, - transaction.FAUCETSC_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerScUpdateConfig(ip InputMap) (err error) { - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerScUpdateGlobals(ip InputMap) (err error) { - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_UPDATE_GLOBALS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) StorageScUpdateConfig(ip InputMap) (err error) { - err = ta.t.createSmartContractTxn(StorageSmartContractAddress, - transaction.STORAGESC_UPDATE_SETTINGS, ip, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) ZCNSCUpdateGlobalConfig(ip InputMap) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, - transaction.ZCNSC_UPDATE_GLOBAL_CONFIG, ip, "0") - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) GetVerifyConfirmationStatus() int { - return ta.t.GetVerifyConfirmationStatus() -} - -func (ta *TransactionWithAuth) MinerSCMinerSettings(info MinerSCMinerInfo) ( - err error) { - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_SETTINGS, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCSharderSettings(info MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_SETTINGS, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCDeleteMiner(info MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_MINER_DELETE, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) MinerSCDeleteSharder(info MinerSCMinerInfo) ( - err error) { - - err = ta.t.createSmartContractTxn(MinerSmartContractAddress, - transaction.MINERSC_SHARDER_DELETE, info, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) ZCNSCUpdateAuthorizerConfig(ip AuthorizerNode) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_UPDATE_AUTHORIZER_CONFIG, ip, "0") - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) ZCNSCAddAuthorizer(ip AddAuthorizerPayload) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_ADD_AUTHORIZER, ip, "0") - if err != nil { - logging.Error(err) - return - } - go ta.submitTxn() - return -} - -func (ta *TransactionWithAuth) ZCNSCAuthorizerHealthCheck(ip *AuthorizerHealthCheckPayload) (err error) { - err = ta.t.createSmartContractTxn(ZCNSCSmartContractAddress, transaction.ZCNSC_AUTHORIZER_HEALTH_CHECK, ip, "0") - if err != nil { - logging.Error(err) - return - } - go ta.t.setNonceAndSubmit() - return -} - -func (ta *TransactionWithAuth) VestingTrigger(poolID string) (err error) { - err = ta.t.vestingPoolTxn(transaction.VESTING_TRIGGER, poolID, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) VestingStop(sr *VestingStopRequest) (err error) { - err = ta.t.createSmartContractTxn(VestingSmartContractAddress, - transaction.VESTING_STOP, sr, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) VestingUnlock(poolID string) (err error) { - - err = ta.t.vestingPoolTxn(transaction.VESTING_UNLOCK, poolID, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} - -func (ta *TransactionWithAuth) VestingDelete(poolID string) (err error) { - err = ta.t.vestingPoolTxn(transaction.VESTING_DELETE, poolID, "0") - if err != nil { - logging.Error(err) - return - } - go func() { ta.submitTxn() }() - return -} diff --git a/zcncore/wallet.go b/zcncore/wallet.go deleted file mode 100644 index 7f2b15e3d..000000000 --- a/zcncore/wallet.go +++ /dev/null @@ -1,29 +0,0 @@ -//go:build !mobile -// +build !mobile - -package zcncore - -import ( - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -// GetWallet get a wallet object from a wallet string -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) -} - -func SignWith0Wallet(hash string, w *zcncrypto.Wallet) (string, error) { - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := sigScheme.SetPrivateKey(w.Keys[0].PrivateKey) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go deleted file mode 100644 index 5b89e7fd5..000000000 --- a/zcncore/wallet_base.go +++ /dev/null @@ -1,1449 +0,0 @@ -package zcncore - -import ( - "context" - "encoding/hex" - "encoding/json" - "fmt" - "math" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - stdErrors "errors" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/core/tokenrate" - "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/core/version" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/zboxcore/encryption" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" - openssl "github.com/Luzifer/go-openssl/v3" - "gopkg.in/natefinch/lumberjack.v2" -) - -const ( - GET_CLIENT = `/v1/client/get` - PUT_TRANSACTION = `/v1/transaction/put` - TXN_VERIFY_URL = `/v1/transaction/get/confirmation?hash=` - GET_BLOCK_INFO = `/v1/block/get?` - GET_MAGIC_BLOCK_INFO = `/v1/block/magic/get?` - GET_LATEST_FINALIZED = `/v1/block/get/latest_finalized` - GET_LATEST_FINALIZED_MAGIC_BLOCK = `/v1/block/get/latest_finalized_magic_block` - GET_FEE_STATS = `/v1/block/get/fee_stats` - GET_CHAIN_STATS = `/v1/chain/get/stats` - // vesting SC - - VESTINGSC_PFX = `/v1/screst/` + VestingSmartContractAddress - - GET_VESTING_CONFIG = VESTINGSC_PFX + `/vesting-config` - GET_VESTING_POOL_INFO = VESTINGSC_PFX + `/getPoolInfo` - GET_VESTING_CLIENT_POOLS = VESTINGSC_PFX + `/getClientPools` - - // faucet sc - - FAUCETSC_PFX = `/v1/screst/` + FaucetSmartContractAddress - GET_FAUCETSC_CONFIG = FAUCETSC_PFX + `/faucet-config` - - // zcn sc - ZCNSC_PFX = `/v1/screst/` + ZCNSCSmartContractAddress - GET_MINT_NONCE = ZCNSC_PFX + `/v1/mint_nonce` - GET_NOT_PROCESSED_BURN_TICKETS = ZCNSC_PFX + `/v1/not_processed_burn_tickets` - GET_AUTHORIZER = ZCNSC_PFX + `/getAuthorizer` - - // miner SC - - MINERSC_PFX = `/v1/screst/` + MinerSmartContractAddress - GET_MINERSC_NODE = MINERSC_PFX + "/nodeStat" - GET_MINERSC_POOL = MINERSC_PFX + "/nodePoolStat" - GET_MINERSC_CONFIG = MINERSC_PFX + "/configs" - GET_MINERSC_GLOBALS = MINERSC_PFX + "/globalSettings" - GET_MINERSC_USER = MINERSC_PFX + "/getUserPools" - GET_MINERSC_MINERS = MINERSC_PFX + "/getMinerList" - GET_MINERSC_SHARDERS = MINERSC_PFX + "/getSharderList" - GET_MINERSC_EVENTS = MINERSC_PFX + "/getEvents" - - // storage SC - - STORAGESC_PFX = "/v1/screst/" + StorageSmartContractAddress - - STORAGESC_GET_SC_CONFIG = STORAGESC_PFX + "/storage-config" - STORAGESC_GET_CHALLENGE_POOL_INFO = STORAGESC_PFX + "/getChallengePoolStat" - STORAGESC_GET_ALLOCATION = STORAGESC_PFX + "/allocation" - STORAGESC_GET_ALLOCATIONS = STORAGESC_PFX + "/allocations" - STORAGESC_GET_READ_POOL_INFO = STORAGESC_PFX + "/getReadPoolStat" - STORAGESC_GET_STAKE_POOL_INFO = STORAGESC_PFX + "/getStakePoolStat" - STORAGESC_GET_STAKE_POOL_USER_INFO = STORAGESC_PFX + "/getUserStakePoolStat" - STORAGESC_GET_USER_LOCKED_TOTAL = STORAGESC_PFX + "/getUserLockedTotal" - STORAGESC_GET_BLOBBERS = STORAGESC_PFX + "/getblobbers" - STORAGESC_GET_BLOBBER = STORAGESC_PFX + "/getBlobber" - STORAGESC_GET_VALIDATOR = STORAGESC_PFX + "/get_validator" - STORAGESC_GET_TRANSACTIONS = STORAGESC_PFX + "/transactions" - - STORAGE_GET_SNAPSHOT = STORAGESC_PFX + "/replicate-snapshots" - STORAGE_GET_BLOBBER_SNAPSHOT = STORAGESC_PFX + "/replicate-blobber-aggregates" - STORAGE_GET_MINER_SNAPSHOT = STORAGESC_PFX + "/replicate-miner-aggregates" - STORAGE_GET_SHARDER_SNAPSHOT = STORAGESC_PFX + "/replicate-sharder-aggregates" - STORAGE_GET_AUTHORIZER_SNAPSHOT = STORAGESC_PFX + "/replicate-authorizer-aggregates" - STORAGE_GET_VALIDATOR_SNAPSHOT = STORAGESC_PFX + "/replicate-validator-aggregates" - STORAGE_GET_USER_SNAPSHOT = STORAGESC_PFX + "/replicate-user-aggregates" -) - -const ( - StorageSmartContractAddress = `6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d7` - VestingSmartContractAddress = `2bba5b05949ea59c80aed3ac3474d7379d3be737e8eb5a968c52295e48333ead` - FaucetSmartContractAddress = `6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d3` - MultiSigSmartContractAddress = `27b5ef7120252b79f9dd9c05505dd28f328c80f6863ee446daede08a84d651a7` - MinerSmartContractAddress = `6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d9` - ZCNSCSmartContractAddress = `6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712e0` - MultiSigRegisterFuncName = "register" - MultiSigVoteFuncName = "vote" -) - -// In percentage -const consensusThresh = 25 - -const ( - defaultMinSubmit = int(10) - defaultMinConfirmation = int(10) - defaultConfirmationChainLength = int(3) - defaultTxnExpirationSeconds = 60 - defaultWaitSeconds = 3 * time.Second -) - -const ( - StatusSuccess int = 0 - StatusNetworkError int = 1 - // TODO: Change to specific error - StatusError int = 2 - StatusRejectedByUser int = 3 - StatusInvalidSignature int = 4 - StatusAuthError int = 5 - StatusAuthVerifyFailed int = 6 - StatusAuthTimeout int = 7 - StatusUnknown int = -1 -) - -var defaultLogLevel = logger.DEBUG -var logging logger.Logger - -// GetLogger returns the logger instance -func GetLogger() *logger.Logger { - return &logging -} - -// CloseLog closes log file -func CloseLog() { - logging.Close() -} - -const TOKEN_UNIT int64 = 1e10 - -const ( - OpGetTokenLockConfig int = iota - OpGetLockedTokens - OpGetUserPools - OpGetUserPoolDetail - 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 -) - -// WalletCallback needs to be implemented for wallet creation. -type WalletCallback interface { - OnWalletCreateComplete(status int, wallet string, err string) -} - -// GetBalanceCallback needs to be implemented by the caller of GetBalance() to get the status -type GetBalanceCallback interface { - OnBalanceAvailable(status int, value int64, info string) -} - -// 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"` - Nonce int64 `json:"nonce"` -} - -// GetNonceCallback needs to be implemented by the caller of GetNonce() to get the status -type GetNonceCallback interface { - OnNonceAvailable(status int, nonce int64, info string) -} - -type GetNonceCallbackStub struct { - status int - nonce int64 - info string -} - -func (g *GetNonceCallbackStub) OnNonceAvailable(status int, nonce int64, info string) { - g.status = status - g.nonce = nonce - g.info = info -} - -// 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 - // is status != StatusSuccess then err will give the reason - OnInfoAvailable(op int, status int, info string, err string) -} - -// AuthCallback needs to be implemented by the caller SetupAuth() -type AuthCallback interface { - // This call back gives the status of the Two factor authenticator(zauth) setup. - OnSetupComplete(status int, err string) -} - -// Singleton -var _config localConfig -var miners []string -var mGuard sync.Mutex - -func init() { - logging.Init(defaultLogLevel, "0chain-core-sdk") -} - -func GetStableMiners() []string { - mGuard.Lock() - defer mGuard.Unlock() - if len(miners) == 0 { - miners = util.GetRandom(_config.chain.Miners, getMinMinersSubmit()) - } - - return miners -} -func ResetStableMiners() { - mGuard.Lock() - defer mGuard.Unlock() - miners = util.GetRandom(_config.chain.Miners, getMinMinersSubmit()) -} - -func checkSdkInit() error { - if !_config.isConfigured || len(_config.chain.Miners) < 1 || len(_config.chain.Sharders) < 1 { - return errors.New("", "SDK not initialized") - } - return nil -} -func checkWalletConfig() error { - if !_config.isValidWallet || _config.wallet.ClientID == "" { - logging.Error("wallet info not found. returning error.") - return errors.New("", "wallet info not found. set wallet info") - } - return nil -} -func CheckConfig() error { - - err := checkSdkInit() - if err != nil { - return err - } - err = checkWalletConfig() - if err != nil { - return err - } - return nil -} - -func assertConfig() { - if _config.chain.MinSubmit <= 0 { - _config.chain.MinSubmit = defaultMinSubmit - } - if _config.chain.MinConfirmation <= 0 { - _config.chain.MinConfirmation = defaultMinConfirmation - } - if _config.chain.ConfirmationChainLength <= 0 { - _config.chain.ConfirmationChainLength = defaultConfirmationChainLength - } -} -func getMinMinersSubmit() int { - minMiners := util.MaxInt(calculateMinRequired(float64(_config.chain.MinSubmit), float64(len(_config.chain.Miners))/100), 1) - logging.Info("Minimum miners used for submit :", minMiners) - return minMiners -} - -func GetMinShardersVerify() int { - return getMinShardersVerify() -} - -func getMinShardersVerify() int { - minSharders := util.MaxInt(calculateMinRequired(float64(_config.chain.MinConfirmation), float64(len(Sharders.Healthy()))/100), 1) - logging.Info("Minimum sharders used for verify :", minSharders) - return minSharders -} -func getMinRequiredChainLength() int64 { - return int64(_config.chain.ConfirmationChainLength) -} - -func calculateMinRequired(minRequired, percent float64) int { - return int(math.Ceil(minRequired * percent)) -} - -// GetVersion - returns version string -func GetVersion() string { - return version.VERSIONSTR -} - -// SetLogLevel set the log level. -// - lvl: 0 disabled; higher number (upto 4) more verbosity -func SetLogLevel(lvl int) { - logging.SetLevel(lvl) -} - -// SetLogFile - sets file path to write log -// - logFile: log file path -// - verbose: true - console output; false - no console output -func SetLogFile(logFile string, verbose bool) { - ioWriter := &lumberjack.Logger{ - Filename: logFile, - MaxSize: 100, // MB - MaxBackups: 5, // number of backups - MaxAge: 28, //days - LocalTime: false, - Compress: false, // disabled by default - } - logging.SetLogFile(ioWriter, verbose) - logging.Info("******* Wallet SDK Version:", version.VERSIONSTR, " ******* (SetLogFile)") -} - -// Init initialize the SDK with miner, sharder and signature scheme provided in configuration provided in JSON format -// # Inputs -// - chainConfigJSON: json format of zcn config -// { -// "block_worker": "https://dev.0chain.net/dns", -// "signature_scheme": "bls0chain", -// "min_submit": 50, -// "min_confirmation": 50, -// "confirmation_chain_length": 3, -// "max_txn_query": 5, -// "query_sleep_time": 5, -// "preferred_blobbers": ["https://dev.0chain.net/blobber02","https://dev.0chain.net/blobber03"], -// "chain_id":"0afc093ffb509f059c55478bc1a60351cef7b4e9c008a53a6cc8241ca8617dfe", -// "ethereum_node":"https://ropsten.infura.io/v3/xxxxxxxxxxxxxxx", -// "zbox_host":"https://0box.dev.0chain.net", -// "zbox_app_type":"vult", -// "sharder_consensous": 2, -// } -func Init(chainConfigJSON string) error { - err := json.Unmarshal([]byte(chainConfigJSON), &_config.chain) - if err == nil { - // Check signature scheme is supported - if _config.chain.SignatureScheme != "ed25519" && _config.chain.SignatureScheme != "bls0chain" { - return errors.New("", "invalid/unsupported signature scheme") - } - - err = UpdateNetworkDetails() - if err != nil { - return err - } - - go updateNetworkDetailsWorker(context.Background()) - - assertConfig() - _config.isConfigured = true - - cfg := &conf.Config{ - BlockWorker: _config.chain.BlockWorker, - MinSubmit: _config.chain.MinSubmit, - MinConfirmation: _config.chain.MinConfirmation, - ConfirmationChainLength: _config.chain.ConfirmationChainLength, - SignatureScheme: _config.chain.SignatureScheme, - ChainID: _config.chain.ChainID, - EthereumNode: _config.chain.EthNode, - SharderConsensous: _config.chain.SharderConsensous, - } - - conf.InitClientConfig(cfg) - } - logging.Info("0chain: test logging") - logging.Info("******* Wallet SDK Version:", version.VERSIONSTR, " ******* (Init) Test") - return err -} - -// InitSignatureScheme initializes signature scheme only. -// - scheme: signature scheme -func InitSignatureScheme(scheme string) { - _config.chain.SignatureScheme = scheme -} - -// CreateWalletOffline creates the wallet for the config signature scheme. -func CreateWalletOffline() (string, error) { - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - wallet, err := sigScheme.GenerateKeys() - if err != nil { - return "", errors.Wrap(err, "failed to generate keys") - } - w, err := wallet.Marshal() - if err != nil { - return "", errors.Wrap(err, "wallet encoding failed") - } - return w, nil -} - -// 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") - } - - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - wallet, err := sigScheme.RecoverKeys(mnemonic) - if err != nil { - return "", err - } - - walletString, err := wallet.Marshal() - if err != nil { - return "", err - } - - return walletString, nil -} - -// RecoverWallet recovers the previously generated wallet using the mnemonic. -// It also registers the wallet again to block chain. -func RecoverWallet(mnemonic string, statusCb WalletCallback) error { - if !zcncrypto.IsMnemonicValid(mnemonic) { - return errors.New("", "Invalid mnemonic") - } - go func() { - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - _, err := sigScheme.RecoverKeys(mnemonic) - if err != nil { - statusCb.OnWalletCreateComplete(StatusError, "", err.Error()) - return - } - }() - return nil -} - -// Split keys from the primary master key -func SplitKeys(privateKey string, numSplits int) (string, error) { - w, err := SplitKeysWallet(privateKey, numSplits) - if err != nil { - return "", errors.Wrap(err, "split key failed.") - } - wStr, err := w.Marshal() - if err != nil { - return "", errors.Wrap(err, "wallet encoding failed.") - } - return wStr, nil -} - -func SplitKeysWallet(privateKey string, numSplits int) (*zcncrypto.Wallet, error) { - if _config.chain.SignatureScheme != "bls0chain" { - return nil, errors.New("", "signature key doesn't support split key") - } - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := sigScheme.SetPrivateKey(privateKey) - if err != nil { - return nil, errors.Wrap(err, "set private key failed") - } - w, err := sigScheme.SplitKeys(numSplits) - if err != nil { - return nil, errors.Wrap(err, "split key failed.") - } - - w.IsSplit = true - - return w, nil -} - -type GetClientResponse struct { - ID string `json:"id"` - Version string `json:"version"` - CreationDate int `json:"creation_date"` - PublicKey string `json:"public_key"` -} - -func GetClientDetails(clientID string) (*GetClientResponse, error) { - minerurl := util.GetRandom(_config.chain.Miners, 1)[0] - url := minerurl + GET_CLIENT - url = fmt.Sprintf("%v?id=%v", url, clientID) - req, err := util.NewHTTPGetRequest(url) - if err != nil { - logging.Error(minerurl, "new get request failed. ", err.Error()) - return nil, err - } - res, err := req.Get() - if err != nil { - logging.Error(minerurl, "send error. ", err.Error()) - return nil, err - } - - var clientDetails GetClientResponse - err = json.Unmarshal([]byte(res.Body), &clientDetails) - if err != nil { - return nil, err - } - - return &clientDetails, nil -} - -// IsMnemonicValid is a utility function to check the mnemonic valid -// - mnemonic: mnemonics to check -func IsMnemonicValid(mnemonic string) bool { - return zcncrypto.IsMnemonicValid(mnemonic) -} - -// SetWallet should be set before any transaction or client specific APIs -// splitKeyWallet parameter is valid only if SignatureScheme is "BLS0Chain" -func SetWallet(w zcncrypto.Wallet, splitKeyWallet bool) error { - _config.wallet = w - - if _config.chain.SignatureScheme == "bls0chain" { - _config.isSplitWallet = splitKeyWallet - } - _config.isValidWallet = true - - return nil -} - -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" -// - 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 { - return err - } - - if _config.chain.SignatureScheme == "bls0chain" { - _config.isSplitWallet = splitKeyWallet - } - _config.isValidWallet = true - - return nil -} - -// SetAuthUrl will be called by app to set zauth URL to SDK. -// # Inputs -// - url: the url of zAuth server -func SetAuthUrl(url string) error { - if !_config.isSplitWallet { - return errors.New("", "wallet type is not split key") - } - if url == "" { - return errors.New("", "invalid auth url") - } - _config.authUrl = strings.TrimRight(url, "/") - return nil -} - -func getWalletBalance(clientId string) (common.Balance, int64, error) { - err := checkSdkInit() - if err != nil { - return 0, 0, err - } - - cb := &walletCallback{} - cb.Add(1) - - go func() { - value, info, err := getBalanceFromSharders(clientId) - if err != nil && strings.TrimSpace(info) != `{"error":"value not present"}` { - cb.OnBalanceAvailable(StatusError, value, info) - cb.err = err - return - } - cb.OnBalanceAvailable(StatusSuccess, value, info) - }() - - cb.Wait() - - var clientState struct { - Nonce int64 `json:"nonce"` - } - err = json.Unmarshal([]byte(cb.info), &clientState) - if err != nil { - return 0, 0, err - } - - return cb.balance, clientState.Nonce, cb.err -} - -// GetBalance retrieve wallet balance from sharders -// - cb: info callback instance, carries the response of the GET request to the sharders -func GetBalance(cb GetBalanceCallback) error { - err := CheckConfig() - if err != nil { - return err - } - go func() { - value, info, err := getBalanceFromSharders(_config.wallet.ClientID) - if err != nil { - logging.Error(err) - cb.OnBalanceAvailable(StatusError, 0, info) - return - } - cb.OnBalanceAvailable(StatusSuccess, value, info) - }() - return nil -} - -// 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 { - return err - } - - go GetInfoFromSharders(withParams(GET_MINT_NONCE, Params{ - "client_id": _config.wallet.ClientID, - }), OpGetMintNonce, cb) - return nil -} - -// 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 { - return err - } - - go GetInfoFromSharders(withParams(GET_NOT_PROCESSED_BURN_TICKETS, Params{ - "ethereum_address": ethereumAddress, - "nonce": startNonce, - }), OpGetNotProcessedBurnTickets, cb) - - return nil -} - -// 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{} - } - - err := CheckConfig() - if err != nil { - return err - } - - go func() { - value, info, err := getNonceFromSharders(_config.wallet.ClientID) - if err != nil { - logging.Error(err) - cb.OnNonceAvailable(StatusError, 0, info) - return - } - - cb.OnNonceAvailable(StatusSuccess, value, info) - }() - - return nil -} - -// GetWalletBalance retrieve wallet nonce from sharders -// - clientID: client id -func GetWalletNonce(clientID string) (int64, error) { - cb := &GetNonceCallbackStub{} - - err := CheckConfig() - if err != nil { - return 0, err - } - wait := &sync.WaitGroup{} - wait.Add(1) - go func() { - defer wait.Done() - value, info, err := getNonceFromSharders(clientID) - if err != nil { - logging.Error(err) - cb.OnNonceAvailable(StatusError, 0, info) - return - } - cb.OnNonceAvailable(StatusSuccess, value, info) - }() - - wait.Wait() - - if cb.status == StatusSuccess { - return cb.nonce, nil - } - - return 0, stdErrors.New(cb.info) -} - -// 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 { - fmt.Printf("Error while parsing the wallet. %v\n", err) - return err - } - - go func() { - value, info, err := getBalanceFromSharders(w.ClientID) - if err != nil { - logging.Error(err) - cb.OnBalanceAvailable(StatusError, 0, info) - return - } - cb.OnBalanceAvailable(StatusSuccess, value, info) - }() - return nil -} - -func getBalanceFromSharders(clientID string) (int64, string, error) { - return Sharders.GetBalanceFieldFromSharders(clientID, "balance") -} - -func getNonceFromSharders(clientID string) (int64, string, error) { - return Sharders.GetBalanceFieldFromSharders(clientID, "nonce") -} - -// ConvertToToken converts the SAS tokens to ZCN 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 { - return 0, err - } - 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 { - return 0, err - } - return usd * (1 / zcnRate), nil -} - -func getTokenUSDRate() (float64, error) { - return tokenrate.GetUSD(context.TODO(), "zcn") -} - -// getWallet get a wallet object from a wallet string -func getWallet(walletStr string) (*zcncrypto.Wallet, error) { - var w zcncrypto.Wallet - err := json.Unmarshal([]byte(walletStr), &w) - if err != nil { - fmt.Printf("error while parsing wallet string.\n%v\n", err) - return nil, err - } - - return &w, nil -} - -// 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 { - return "", err - } - return w.ClientID, nil -} - -// GetZcnUSDInfo returns USD value for ZCN token by tokenrate -func GetZcnUSDInfo() (float64, error) { - return tokenrate.GetUSD(context.TODO(), "zcn") -} - -// SetupAuth prepare auth app with clientid, key and a set of public, private key and local publickey -// which is running on PC/Mac. -func SetupAuth(authHost, clientID, clientKey, publicKey, privateKey, localPublicKey string, cb AuthCallback) error { - go func() { - authHost = strings.TrimRight(authHost, "/") - data := map[string]string{"client_id": clientID, "client_key": clientKey, "public_key": publicKey, "private_key": privateKey, "peer_public_key": localPublicKey} - req, err := util.NewHTTPPostRequest(authHost+"/setup", data) - if err != nil { - logging.Error("new post request failed. ", err.Error()) - return - } - res, err := req.Post() - if err != nil { - logging.Error(authHost+"send error. ", err.Error()) - } - if res.StatusCode != http.StatusOK { - cb.OnSetupComplete(StatusError, res.Body) - return - } - cb.OnSetupComplete(StatusSuccess, "") - }() - 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) - req, err := util.NewHTTPGetRequest(url) - if err != nil { - logging.Error(url, "new get request failed. ", err.Error()) - return "" - } - res, err := req.Get() - if err != nil { - logging.Error(url, "get error. ", err.Error()) - return "" - } - - s := strings.Split(res.Body, ",") - if len(s) >= 3 { - return s[3] - } - return "" -} - -// -// vesting pool -// - -type Params map[string]string - -func (p Params) Query() string { - if len(p) == 0 { - return "" - } - var params = make(url.Values) - for k, v := range p { - params[k] = []string{v} - } - return "?" + params.Encode() -} - -// -// miner SC -// - -// GetMiners obtains list of all 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) -} - -func getMinersInternal(cb GetInfoCallback, active, stakable bool, limit, offset int) { - if err := CheckConfig(); err != nil { - return - } - - var url = withParams(GET_MINERSC_MINERS, Params{ - "active": strconv.FormatBool(active), - "stakable": strconv.FormatBool(stakable), - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), - }) - - go GetInfoFromSharders(url, 0, cb) -} - -// 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: 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) -} - -func getShardersInternal(cb GetInfoCallback, active, stakable bool, limit, offset int) { - if err := CheckConfig(); err != nil { - return - } - - var url = withParams(GET_MINERSC_SHARDERS, Params{ - "active": strconv.FormatBool(active), - "stakable": strconv.FormatBool(stakable), - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), - }) - - go GetInfoFromSharders(url, 0, cb) -} - -func withParams(uri string, params Params) string { - return uri + params.Query() -} - -// GetMinerSCNodeInfo get miner information from sharders -// - id: the id of miner -// - 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 { - return - } - - go GetInfoFromSharders(withParams(GET_MINERSC_NODE, Params{ - "id": id, - }), 0, cb) - 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 - } - go GetInfoFromSharders(withParams(GET_MINERSC_POOL, Params{ - "id": id, - "pool_id": _config.wallet.ClientID, - }), 0, cb) - - return -} - -// 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 - } - if clientID == "" { - clientID = _config.wallet.ClientID - } - go GetInfoFromSharders(withParams(GET_MINERSC_USER, Params{ - "client_id": clientID, - }), 0, cb) - - 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 - } - go GetInfoFromSharders(GET_MINERSC_CONFIG, 0, cb) - 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 - } - go GetInfoFromSharders(GET_MINERSC_GLOBALS, 0, cb) - return -} - -// -// Storage SC -// - -// 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 - } - go GetInfoFromSharders(STORAGESC_GET_SC_CONFIG, OpStorageSCGetConfig, cb) - return -} - -// GetChallengePoolInfo obtains challenge pool information for an allocation. -func GetChallengePoolInfo(allocID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - var url = withParams(STORAGESC_GET_CHALLENGE_POOL_INFO, Params{ - "allocation_id": allocID, - }) - go GetInfoFromSharders(url, OpStorageSCGetChallengePoolInfo, cb) - return -} - -// GetAllocation obtains allocation information. -func GetAllocation(allocID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - var url = withParams(STORAGESC_GET_ALLOCATION, Params{ - "allocation": allocID, - }) - go GetInfoFromSharders(url, OpStorageSCGetAllocation, cb) - return -} - -// GetAllocations obtains list of allocations of a user. -func GetAllocations(clientID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - if clientID == "" { - clientID = _config.wallet.ClientID - } - var url = withParams(STORAGESC_GET_ALLOCATIONS, Params{ - "client": clientID, - }) - go GetInfoFromSharders(url, OpStorageSCGetAllocations, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetSnapshots, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_BLOBBER_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - "offset": strconv.FormatInt(offset, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetBlobberSnapshots, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_MINER_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - "offset": strconv.FormatInt(offset, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetMinerSnapshots, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_SHARDER_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - "offset": strconv.FormatInt(offset, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetSharderSnapshots, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_VALIDATOR_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - "offset": strconv.FormatInt(offset, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetValidatorSnapshots, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_AUTHORIZER_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - "offset": strconv.FormatInt(offset, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetAuthorizerSnapshots, cb) - return -} - -// 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 - } - var url = withParams(STORAGE_GET_USER_SNAPSHOT, Params{ - "round": strconv.FormatInt(round, 10), - "limit": strconv.FormatInt(limit, 10), - "offset": strconv.FormatInt(offset, 10), - }) - go GetInfoFromAnySharder(url, OpStorageSCGetUserSnapshots, cb) - return -} - -// GetReadPoolInfo obtains information about read pool of a user. -func GetReadPoolInfo(clientID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - if clientID == "" { - clientID = _config.wallet.ClientID - } - var url = withParams(STORAGESC_GET_READ_POOL_INFO, Params{ - "client_id": clientID, - }) - go GetInfoFromSharders(url, OpStorageSCGetReadPoolInfo, cb) - return -} - -// GetStakePoolInfo obtains information about stake pool of a blobber and -// related validator. -func GetStakePoolInfo(blobberID string, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - var url = withParams(STORAGESC_GET_STAKE_POOL_INFO, Params{ - "blobber_id": blobberID, - }) - go GetInfoFromSharders(url, OpStorageSCGetStakePoolInfo, cb) - return -} - -// GetStakePoolUserInfo for a user. -// # Inputs -// - clientID: the id of wallet -// - 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 - } - if clientID == "" { - clientID = _config.wallet.ClientID - } - - var url = withParams(STORAGESC_GET_STAKE_POOL_USER_INFO, Params{ - "client_id": clientID, - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), - }) - go GetInfoFromSharders(url, OpStorageSCGetStakePoolInfo, cb) - return -} - -// GetStakeableBlobbers obtains list of all active blobbers that can be staked (i.e. still number of delegations < max_delegations) -// # Inputs -// - 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 -func GetStakableBlobbers(cb GetInfoCallback, limit, offset int, active bool) { - getBlobbersInternal(cb, active, limit, offset, true) -} - -// GetBlobbers obtains list of all active blobbers. -// - 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 -func GetBlobbers(cb GetInfoCallback, limit, offset int, active bool) { - getBlobbersInternal(cb, active, limit, offset, false) -} - -func getBlobbersInternal(cb GetInfoCallback, active bool, limit, offset int, stakable bool) { - if err := CheckConfig(); err != nil { - return - } - - var url = withParams(STORAGESC_GET_BLOBBERS, Params{ - "active": strconv.FormatBool(active), - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), - "stakable": strconv.FormatBool(stakable), - }) - - go GetInfoFromSharders(url, OpStorageSCGetBlobbers, cb) -} - -// 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 - } - var url = withParams(STORAGESC_GET_BLOBBER, Params{ - "blobber_id": blobberID, - }) - go GetInfoFromSharders(url, OpStorageSCGetBlobber, cb) - 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 - } - var url = withParams(STORAGESC_GET_VALIDATOR, Params{ - "validator_id": validatorID, - }) - go GetInfoFromSharders(url, OpStorageSCGetBlobber, cb) - 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 - } - var url = withParams(GET_AUTHORIZER, Params{ - "id": authorizerID, - }) - go GetInfoFromSharders(url, OpStorageSCGetBlobber, cb) - 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 - } - var url = withParams(GET_MINERSC_NODE, Params{ - "id": id, - }) - go GetInfoFromSharders(url, OpStorageSCGetBlobber, cb) - return -} - -// GetTransactions query transactions from sharders -// # Inputs -// - toClient: receiver -// - fromClient: sender -// - block_hash: block hash -// - sort: desc or asc -// - limit: how many transactions should be fetched -// - offset: how many transactions should be skipped -// - cb: callback to get result -func GetTransactions(toClient, fromClient, block_hash, sort string, limit, offset int, cb GetInfoCallback) (err error) { - if err = CheckConfig(); err != nil { - return - } - - params := Params{} - if toClient != "" { - params["to_client_id"] = toClient - } - if fromClient != "" { - params["client_id"] = fromClient - } - if block_hash != "" { - params["block_hash"] = block_hash - } - if sort != "" { - params["sort"] = sort - } - if limit != 0 { - l := strconv.Itoa(limit) - params["limit"] = l - } - if offset != 0 { - o := strconv.Itoa(offset) - params["offset"] = o - } - - var u = withParams(STORAGESC_GET_TRANSACTIONS, params) - go GetInfoFromSharders(u, OpStorageSCGetTransactions, cb) - return -} - -func Encrypt(key, text string) (string, error) { - keyBytes := []byte(key) - textBytes := []byte(text) - response, err := zboxutil.Encrypt(keyBytes, textBytes) - if err != nil { - return "", err - } - 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) - response, err := zboxutil.Decrypt(keyBytes, textBytes) - if err != nil { - return "", err - } - return string(response), nil -} - -func CryptoJsEncrypt(passphrase, message string) (string, error) { - o := openssl.New() - - enc, err := o.EncryptBytes(passphrase, []byte(message), openssl.DigestMD5Sum) - if err != nil { - return "", err - } - - return string(enc), nil -} - -func CryptoJsDecrypt(passphrase, encryptedMessage string) (string, error) { - o := openssl.New() - dec, err := o.DecryptBytes(passphrase, []byte(encryptedMessage), openssl.DigestMD5Sum) - if err != nil { - return "", err - } - - 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) - if err != nil { - return "", err - } - return encScheme.GetPublicKey() -} diff --git a/zcncore/wallet_base_test.go b/zcncore/wallet_base_test.go deleted file mode 100644 index e90c01945..000000000 --- a/zcncore/wallet_base_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package zcncore - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestCFBEncryption(t *testing.T) { - key := "passphrase1111111111111111111111" - 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" - - encryptedMnemonics, err := Encrypt(key, mnemonics) - - require.Nil(t, err) - require.NotEmpty(t, encryptedMnemonics) - - decryptedMnemonics, err := Decrypt(key, encryptedMnemonics) - require.Nil(t, err) - require.Equal(t, mnemonics, decryptedMnemonics) -} - -func TestCBCEncryption(t *testing.T) { - passphrase := "12345611111111111111111111111111" - mnemonics := "cube reward february gym summer peanut marble slow puppy picnic cart waste aspect either anchor vacant horse north border wonder stamp mansion steak magic" - - enc, err := CryptoJsEncrypt(passphrase, mnemonics) - require.Nil(t, err) - - dec, err := CryptoJsDecrypt(passphrase, string(enc)) - require.Nil(t, err) - require.Equal(t, mnemonics, string(dec)) - encryptedMnemonics := "U2FsdGVkX1/Dz58HfdXjHGJioPZ8bnEWIfa0dZcz0JuizI/Tu1+1ncVv60f4w53VimvKG0dC5zhVFQC8dt7K7Lydutu/pquTCDfKt3AUK2iJ5mjN1n4rCvp5IMG+5fKuVyY0z+PbH5MgyJdAF1Fbsi3X+ccfd/ZB9jg6deHpneHDMxhRzuGKcKUuWA6+D/peQTGCmHCLbAPYswFUeF0Elcmgi1mx69UYeM1qgfumuFs=" - dec, err = CryptoJsDecrypt(passphrase, encryptedMnemonics) - require.Nil(t, err) - require.Equal(t, mnemonics, string(dec)) -} diff --git a/zcncore/wallet_callback.go b/zcncore/wallet_callback.go deleted file mode 100644 index 7b468f13e..000000000 --- a/zcncore/wallet_callback.go +++ /dev/null @@ -1,28 +0,0 @@ -package zcncore - -import ( - "sync" - - "github.com/0chain/gosdk_common/core/common" -) - -type walletCallback struct { - sync.WaitGroup - success bool - - balance common.Balance - info string - err error -} - -func (cb *walletCallback) OnBalanceAvailable(status int, value int64, info string) { - defer cb.Done() - - if status == StatusSuccess { - cb.success = true - } else { - cb.success = false - } - cb.info = info - cb.balance = common.Balance(value) -} diff --git a/zcncore/wallet_mobile.go b/zcncore/wallet_mobile.go deleted file mode 100644 index 79526e7d3..000000000 --- a/zcncore/wallet_mobile.go +++ /dev/null @@ -1,38 +0,0 @@ -//go:build mobile -// +build mobile - -package zcncore - -import ( - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -// Wallet interface to gather all wallet related functions -type Wallet interface { - // Sign sign the hash - Sign(hash string) (string, error) -} - -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) - if err != nil { - return "", err - } - return sigScheme.Sign(hash) -} - -// GetWalletBalance retrieve wallet balance from sharders -// - id: client id -func GetWalletBalance(id string) (int64, error) { - balance, _, err := getWalletBalance(id) - if err != nil { - return 0, err - } - return int64(balance), nil -} diff --git a/zcncore/zauth.go b/zcncore/zauth.go deleted file mode 100644 index a6e811a27..000000000 --- a/zcncore/zauth.go +++ /dev/null @@ -1,598 +0,0 @@ -package zcncore - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/client" - "github.com/pkg/errors" -) - -// AvailableRestrictions represents supported restrictions mapping. -var AvailableRestrictions = map[string][]string{ - "token_transfers": {"transfer"}, - "allocation_file_operations": { - "read_redeem", - "commit_connection", - }, - "allocation_storage_operations": { - "new_allocation_request", - "update_allocation_request", - "finalize_allocation", - "cancel_allocation", - "add_free_storage_assigner", - "free_allocation_request", - }, - "allocation_token_operations": { - "read_pool_lock", - "read_pool_unlock", - "write_pool_lock", - }, - "storage_rewards": { - "collect_reward", - "stake_pool_lock", - "stake_pool_unlock", - }, - "storage_operations": { - "challenge_response", - "add_validator", - "add_blobber", - "blobber_health_check", - "validator_health_check", - }, - "storage_management": { - "kill_blobber", - "kill_validator", - "shutdown_blobber", - "shutdown_validator", - "update_blobber_settings", - "update_validator_settings", - }, - "miner_operations": { - "add_miner", - "add_sharder", - "miner_health_check", - "sharder_health_check", - "contributeMpk", - "shareSignsOrShares", - "wait", - "sharder_keep", - }, - "miner_management_operations": { - "delete_miner", - "delete_sharder", - "update_miner_settings", - "kill_miner", - "kill_sharder", - }, - "miner_financial_operations": { - "addToDelegatePool", - "deleteFromDelegatePool", - "collect_reward", - }, - "token_bridging": { - "mint", - "burn", - }, - "authorizer_management_operations": { - "delete-authorizer", - }, - "authorizer_operations": { - "add-authorizer", - "authorizer-health-check", - "add-to-delegate-pool", - "delete-from-delegate-pool", - }, -} - -type updateRestrictionsRequest struct { - Restrictions []string `json:"restrictions"` -} - -type AuthMessage struct { - Hash string `json:"hash"` - Signature string `json:"signature"` - ClientID string `json:"client_id"` -} - -type AuthResponse struct { - Sig string `json:"sig"` -} - -func CallZauthRetreiveKey(serverAddr, token, clientID, peerPublicKey string) (string, error) { - endpoint := fmt.Sprintf("%s/key/%s", serverAddr, clientID) - - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", peerPublicKey) - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil -} - -func CallZauthRevoke(serverAddr, token, clientID, peerPublicKey string) error { - endpoint := serverAddr + "/revoke/" + clientID + "?peer_public_key=" + peerPublicKey - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - return nil -} - -func CallZauthDelete(serverAddr, token, clientID string) error { - endpoint := serverAddr + "/delete/" + clientID - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - return nil -} - -func CallZvaultNewWallet(serverAddr, token string) error { - endpoint := serverAddr + "/wallet" - - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - return nil -} - -func CallZvaultNewSplit(serverAddr, token, clientID string) error { - endpoint := serverAddr + "/key/" + clientID - - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - return nil -} - -func CallZvaultRetrieveRestrictions(serverAddr, token, peerPublicKey string) (string, error) { - endpoint := serverAddr + "/restrictions" - - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", peerPublicKey) - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return "", errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return "", errors.Errorf("code: %d", resp.StatusCode) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil -} - -func CallZvaultUpdateRestrictions(serverAddr, token, clientID, peerPublicKey string, restrictions []string) error { - endpoint := serverAddr + "/restrictions/" + clientID - - data, err := json.Marshal(updateRestrictionsRequest{ - Restrictions: restrictions, - }) - if err != nil { - return errors.Wrap(err, "failed to serialize request") - } - - req, err := http.NewRequest("PUT", endpoint, bytes.NewReader(data)) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", peerPublicKey) - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - return nil -} - -func CallZvaultStoreKeyString(serverAddr, token, privateKey string) error { - endpoint := serverAddr + "/store" - - reqData := struct { - PrivateKey string `json:"private_key"` - }{ - PrivateKey: privateKey, - } - - var buff bytes.Buffer - - encoder := json.NewEncoder(&buff) - - err := encoder.Encode(reqData) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - var req *http.Request - - req, err = http.NewRequest("POST", endpoint, &buff) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - if len(errMsg) > 0 { - return errors.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - return errors.Errorf("code: %d", resp.StatusCode) - } - - return nil -} - -func CallZvaultRetrieveKeys(serverAddr, token, clientID string) (string, error) { - endpoint := fmt.Sprintf("%s/keys/%s", serverAddr, clientID) - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil -} - -func CallZvaultDeletePrimaryKey(serverAddr, token, clientID string) error { - endpoint := serverAddr + "/delete/" + clientID - - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - return fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - _, err = io.ReadAll(resp.Body) - if err != nil { - return errors.Wrap(err, "failed to read response body") - } - - return nil -} - -func CallZvaultRevokeKey(serverAddr, token, clientID, publicKey string) error { - // Add your code here - endpoint := fmt.Sprintf("%s/revoke/%s?public_key=%s", serverAddr, clientID, publicKey) - req, err := http.NewRequest("POST", endpoint, nil) - if err != nil { - return errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - return fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - _, err = io.ReadAll(resp.Body) - if err != nil { - return errors.Wrap(err, "failed to read response body") - } - - return nil -} - -func CallZvaultRetrieveWallets(serverAddr, token string) (string, error) { - // Add your code here - endpoint := fmt.Sprintf("%s/wallets", serverAddr) - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil -} - -func CallZvaultRetrieveSharedWallets(serverAddr, token string) (string, error) { - // Add your code here - endpoint := fmt.Sprintf("%s/wallets/shared", serverAddr) - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Jwt-Token", token) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - errMsg, _ := io.ReadAll(resp.Body) - return "", fmt.Errorf("code: %d, err: %s", resp.StatusCode, string(errMsg)) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil -} - -// ZauthSignTxn returns a function that sends a txn signing request to the zauth server -func ZauthSignTxn(serverAddr string) sys.AuthorizeFunc { - return func(msg string) (string, error) { - req, err := http.NewRequest("POST", serverAddr+"/sign/txn", bytes.NewBuffer([]byte(msg))) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - req.Header.Set("Content-Type", "application/json") - c := client.GetClient() - pubkey := c.Keys[0].PublicKey - req.Header.Set("X-Peer-Public-Key", pubkey) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - rsp, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return "", errors.Errorf("unexpected status code: %d, res: %s", resp.StatusCode, string(rsp)) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil - } -} - -func ZauthAuthCommon(serverAddr string) sys.AuthorizeFunc { - return func(msg string) (string, error) { - req, err := http.NewRequest("POST", serverAddr+"/sign/msg", bytes.NewBuffer([]byte(msg))) - if err != nil { - return "", errors.Wrap(err, "failed to create HTTP request") - } - - c := client.GetClient() - pubkey := c.Keys[0].PublicKey - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Peer-Public-Key", pubkey) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", errors.Wrap(err, "failed to send HTTP request") - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - rsp, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return "", errors.Errorf("unexpected status code: %d, res: %s", resp.StatusCode, string(rsp)) - } - - d, err := io.ReadAll(resp.Body) - if err != nil { - return "", errors.Wrap(err, "failed to read response body") - } - - return string(d), nil - } -} diff --git a/zmagmacore/build/info.go b/zmagmacore/build/info.go deleted file mode 100644 index f75decb53..000000000 --- a/zmagmacore/build/info.go +++ /dev/null @@ -1,7 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package build - -var ( - // Tag represents the git commit for the build. - Tag = "is not set" -) diff --git a/zmagmacore/chain/entity.go b/zmagmacore/chain/entity.go deleted file mode 100644 index c57bdb243..000000000 --- a/zmagmacore/chain/entity.go +++ /dev/null @@ -1,45 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package chain - -import ( - "github.com/0chain/gosdk/zmagmacore/time" -) - -// Chain represents data structure that holds the chain data. -type Chain struct { - ID string - Version string - CreationDate time.Timestamp - OwnerID string - BlockWorker string -} - -// serverChain is the chain object of the chain the server is responsible for. -var serverChain = new(Chain) - -// SetServerChain sets the server chain object to package variable serverChain. -func SetServerChain(c *Chain) { - serverChain = c -} - -// GetServerChain returns the chain object for the server chain. -func GetServerChain() *Chain { - return serverChain -} - -// NewChain creates a new Chain. -func NewChain(id, OwnerID, blockWorker string) *Chain { - chain := Provider() - chain.ID = id - chain.OwnerID = OwnerID - chain.BlockWorker = blockWorker - return chain -} - -// Provider returns entity for chain object. -func Provider() *Chain { - c := &Chain{} - c.Version = "1.0" - c.CreationDate = time.Now() - return c -} diff --git a/zmagmacore/config/chain.go b/zmagmacore/config/chain.go deleted file mode 100644 index 872deecd3..000000000 --- a/zmagmacore/config/chain.go +++ /dev/null @@ -1,12 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package config - -type ( - // ServerChain represents config describes blockchain options and signature scheme options. - ServerChain struct { - ID string `yaml:"id"` - OwnerID string `yaml:"owner_id"` - BlockWorker string `yaml:"block_worker"` - SignatureScheme string `yaml:"signature_scheme"` - } -) diff --git a/zmagmacore/config/consumer.go b/zmagmacore/config/consumer.go deleted file mode 100644 index 282024701..000000000 --- a/zmagmacore/config/consumer.go +++ /dev/null @@ -1,29 +0,0 @@ -package config - -import ( - "os" - - "gopkg.in/yaml.v3" -) - -type ( - // Consumer represents config used for registration of node. - Consumer struct { - ID string `yaml:"id"` - ExtID string `yaml:"ext_id"` - Host string `yaml:"host"` - } -) - -// Read reads config yaml file from path. -func (c *Consumer) Read(path string) error { - f, err := os.Open(path) - if err != nil { - return err - } - defer func(f *os.File) { _ = f.Close() }(f) - - decoder := yaml.NewDecoder(f) - - return decoder.Decode(c) -} diff --git a/zmagmacore/config/handler.go b/zmagmacore/config/handler.go deleted file mode 100644 index b0b10aba1..000000000 --- a/zmagmacore/config/handler.go +++ /dev/null @@ -1,14 +0,0 @@ -package config - -type ( - // Handler represents config options for handlers. - Handler struct { - RateLimit float64 `yaml:"rate_limit"` // per second - Log LogHandler `yaml:"log"` - } - - // LogHandler represents config options described in "handler.log" section of the config yaml file. - LogHandler struct { - BufLength int64 `yaml:"buf_length"` // in kilobytes - } -) diff --git a/zmagmacore/config/provider.go b/zmagmacore/config/provider.go deleted file mode 100644 index 54ff6c4cd..000000000 --- a/zmagmacore/config/provider.go +++ /dev/null @@ -1,30 +0,0 @@ -package config - -import ( - "os" - - "gopkg.in/yaml.v3" -) - -type ( - // Provider represents configs of the providers' node. - Provider struct { - ID string `yaml:"id"` - ExtID string `yaml:"ext_id"` - Host string `yaml:"host"` - MinStake int64 `yaml:"min_stake"` - } -) - -// Read reads config yaml file from path. -func (p *Provider) Read(path string) error { - f, err := os.Open(path) - if err != nil { - return err - } - defer func(f *os.File) { _ = f.Close() }(f) - - decoder := yaml.NewDecoder(f) - - return decoder.Decode(p) -} diff --git a/zmagmacore/config/workers.go b/zmagmacore/config/workers.go deleted file mode 100644 index 4c440de4c..000000000 --- a/zmagmacore/config/workers.go +++ /dev/null @@ -1,9 +0,0 @@ -package config - -type ( - // BalanceWorker represents worker options described in "workers.balance" section of the config yaml file. - BalanceWorker struct { - WaitResponseTimeout int64 `yaml:"wait_response_timeout"` // in seconds - ScrapingTime int64 `yaml:"scraping_time"` // in seconds - } -) diff --git a/zmagmacore/crypto/hash.go b/zmagmacore/crypto/hash.go deleted file mode 100644 index cffb0d197..000000000 --- a/zmagmacore/crypto/hash.go +++ /dev/null @@ -1,46 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package crypto - -import ( - "encoding/hex" - - "golang.org/x/crypto/sha3" -) - -const HashLength = 32 - -type HashBytes [HashLength]byte - -// Hash computes hash of the given data using RawHash and returns result as hex decoded string. -func Hash(data interface{}) string { - return hex.EncodeToString(RawHash(data)) -} - -// RawHash computes SHA3-256 hash depending on data type and returns the hash bytes. -// -// RawHash panics if data type is unknown. -// -// Known types: -// -// - []byte -// -// - HashBytes -// -// - string -func RawHash(data interface{}) []byte { - var databuf []byte - switch dataImpl := data.(type) { - case []byte: - databuf = dataImpl - case HashBytes: - databuf = dataImpl[:] - case string: - databuf = []byte(dataImpl) - default: - panic("unknown type") - } - hash := sha3.New256() - hash.Write(databuf) - var buf []byte - return hash.Sum(buf) -} diff --git a/zmagmacore/crypto/keys.go b/zmagmacore/crypto/keys.go deleted file mode 100644 index a7393f88a..000000000 --- a/zmagmacore/crypto/keys.go +++ /dev/null @@ -1,64 +0,0 @@ -package crypto - -import ( - "bufio" - "encoding/hex" - "io" - "os" - - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -// ReadKeysFile reads file existing in keysFile dir and parses public and private keys from file. -func ReadKeysFile(keysFile string) (publicKey, privateKey []byte, err error) { - const errCode = "read_keys" - - reader, err := os.Open(keysFile) - if err != nil { - return nil, nil, errors.Wrap(errCode, "error while open keys file", err) - } - - publicKeyHex, privateKeyHex := readKeys(reader) - err = reader.Close() - if err != nil { - return nil, nil, errors.Wrap(errCode, "error while close keys file", err) - } - publicKey, err = hex.DecodeString(publicKeyHex) - if err != nil { - return nil, nil, errors.Wrap(errCode, "error while decoding public key", err) - } - privateKey, err = hex.DecodeString(privateKeyHex) - if err != nil { - return nil, nil, errors.Wrap(errCode, "error while decoding private key", err) - } - - return publicKey, privateKey, nil -} - -// readKeys reads a publicKey and a privateKey from a io.Reader passed in args. -// They are assumed to be in two separate lines one followed by the other. -func readKeys(reader io.Reader) (publicKey string, privateKey string) { - scanner := bufio.NewScanner(reader) - scanner.Scan() - publicKey = scanner.Text() - scanner.Scan() - privateKey = scanner.Text() - scanner.Scan() - - return publicKey, privateKey -} - -// Verify verifies passed signature of the passed hash with passed public key using the signature scheme. -func Verify(publicKey, signature, hash, scheme string) (bool, error) { - signScheme := zcncrypto.NewSignatureScheme(scheme) - if signScheme != nil { - err := signScheme.SetPublicKey(publicKey) - if err != nil { - return false, err - } - return signScheme.Verify(signature, hash) - } - - return false, errors.New("invalid_signature_scheme", "invalid signature scheme") -} diff --git a/zmagmacore/doc.go b/zmagmacore/doc.go deleted file mode 100644 index 99d371946..000000000 --- a/zmagmacore/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index 28e44b3e7..000000000 --- a/zmagmacore/errors/errors.go +++ /dev/null @@ -1,91 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package errors - -import ( - "errors" - "os" -) - -const ( - delim = ": " -) - -type ( - // Error type for a new application error. - Error struct { - Code string `json:"code,omitempty"` - Msg string `json:"msg"` - } -) - -type ( - // wrapper implements error wrapper interface. - errWrapper struct { - code string - text string - wrap error - } -) - -// Error implements error interface. -func (e *errWrapper) Error() string { - return e.code + delim + e.text -} - -// Unwrap implements error unwrap interface. -func (e *errWrapper) Unwrap() error { - return e.wrap -} - -// Wrap implements error wrapper interface. -func (e *errWrapper) Wrap(err error) *errWrapper { - return Wrap(e.code, e.text, err) -} - -// Any reports whether an error in error's chain -// matches to any error provided in list. -func Any(err error, targets ...error) bool { - for _, target := range targets { - if errors.Is(err, target) { - return true - } - } - - return false -} - -// ExitErr prints error to os.Stderr and call os.Exit with given code. -func ExitErr(text string, err error, code int) { - text = Wrap("exit", text, err).Error() - _, _ = os.Stderr.Write([]byte(text)) - os.Exit(code) -} - -// ExitMsg prints message to os.Stderr and call os.Exit with given code. -func ExitMsg(text string, code int) { - text = New("exit", text).Error() - _, _ = os.Stderr.Write([]byte(text)) - os.Exit(code) -} - -// Is wraps function errors.Is from stdlib to avoid import it -// in other places of the magma smart contract (magmasc) package. -func Is(err, target error) bool { - return errors.Is(err, target) -} - -// New returns constructed error wrapper interface. -func New(code, text string) *errWrapper { - return &errWrapper{code: code, text: text} -} - -// Wrap wraps given error into a new error with format. -func Wrap(code, text string, err error) *errWrapper { - wrapper := &errWrapper{code: code, text: text} - if err != nil && !errors.Is(wrapper, err) { - wrapper.wrap = err - wrapper.text += delim + err.Error() - } - - return wrapper -} diff --git a/zmagmacore/errors/errors_test.go b/zmagmacore/errors/errors_test.go deleted file mode 100644 index 0858773ae..000000000 --- a/zmagmacore/errors/errors_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package errors - -import ( - "reflect" - "testing" -) - -const ( - testCode = "test_code" - testText = "test text" - wrapCode = "wrap_code" - wrapText = "wrap text" -) - -func Test_errWrapper_Error(t *testing.T) { - t.Parallel() - - tests := [1]struct { - name string - err error - want string - }{ - { - name: "OK", - err: Wrap(wrapCode, wrapText, New(testCode, testText)), - want: wrapCode + delim + wrapText + delim + testCode + delim + testText, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.err.Error(); got != test.want { - t.Errorf("Error() got: %v | want: %v", got, test.want) - } - }) - } -} - -func Test_errWrapper_Unwrap(t *testing.T) { - t.Parallel() - - err := New(testCode, testText) - - tests := [1]struct { - name string - wrapper *errWrapper - want error - }{ - { - name: "OK", - wrapper: Wrap(wrapCode, wrapText, err), - want: err, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.wrapper.Unwrap(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Unwrap() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_errWrapper_Wrap(t *testing.T) { - t.Parallel() - - err := New(testCode, testText) - - tests := [1]struct { - name string - error error - wrapper *errWrapper - want *errWrapper - }{ - { - name: "OK", - error: New(testCode, testText), - wrapper: New(wrapCode, wrapText), - want: &errWrapper{code: wrapCode, text: wrapText + delim + err.Error(), wrap: err}, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.wrapper.Wrap(test.error); !reflect.DeepEqual(got, test.want) { - t.Errorf("Wrap() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_errAny(t *testing.T) { - t.Parallel() - - testErr := New(testCode, testText) - wrapErr := Wrap(wrapCode, wrapText, testErr) - - tests := [2]struct { - name string - list []error - wrapErr error - want bool - }{ - { - name: "TRUE", - list: []error{testErr}, - wrapErr: wrapErr, - want: true, - }, - { - name: "FALSE", - list: []error{testErr}, - wrapErr: Wrap(wrapCode, wrapText, New(testCode, testText)), - want: false, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := Any(test.wrapErr, test.list...); got != test.want { - t.Errorf("errIs() got: %v | want: %v", got, test.want) - } - }) - } -} - -func Test_errIs(t *testing.T) { - t.Parallel() - - testErr := New(testCode, testText) - wrapErr := Wrap(wrapCode, wrapText, testErr) - - tests := [2]struct { - name string - testErr error - wrapErr error - want bool - }{ - { - name: "TRUE", - testErr: testErr, - wrapErr: wrapErr, - want: true, - }, - { - name: "FALSE", - testErr: testErr, - wrapErr: Wrap(wrapCode, wrapText, New(testCode, testText)), - want: false, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := Is(test.wrapErr, test.testErr); got != test.want { - t.Errorf("errIs() got: %v | want: %v", got, test.want) - } - }) - } -} - -func Test_errNew(t *testing.T) { - t.Parallel() - - tests := [1]struct { - name string - code string - text string - want *errWrapper - }{ - { - name: "Equal", - code: testCode, - text: testText, - want: &errWrapper{code: testCode, text: testText}, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := New(test.code, test.text); !reflect.DeepEqual(got, test.want) { - t.Errorf("errNew() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_errWrap(t *testing.T) { - t.Parallel() - - tests := [2]struct { - name string - code string - text string - wrap error - want string - }{ - { - name: "OK", - code: wrapCode, - text: wrapText, - wrap: New(testCode, testText), - want: wrapCode + delim + wrapText + delim + testCode + delim + testText, - }, - { - name: "nil_Wrap_OK", - code: wrapCode, - text: wrapText, - wrap: nil, - want: wrapCode + delim + wrapText, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := Wrap(test.code, test.text, test.wrap).Error(); got != test.want { - t.Errorf("errWrap() got: %#v | want: %#v", got, test.want) - } - }) - } -} diff --git a/zmagmacore/http/client.go b/zmagmacore/http/client.go deleted file mode 100644 index 318d6c14c..000000000 --- a/zmagmacore/http/client.go +++ /dev/null @@ -1,45 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package http - -import ( - "net" - "net/http" - "time" - - "github.com/hashicorp/go-retryablehttp" -) - -const ( - // clientTimeout represents default http.Client timeout. - clientTimeout = 10 * time.Second - - // tlsHandshakeTimeout represents default http.Transport TLS handshake timeout. - tlsHandshakeTimeout = 5 * time.Second - - // dialTimeout represents default net.Dialer timeout. - dialTimeout = 5 * time.Second -) - -// NewClient creates default http.Client with timeouts. -func NewClient() *http.Client { - return &http.Client{ - Timeout: clientTimeout, - Transport: &http.Transport{ - TLSHandshakeTimeout: tlsHandshakeTimeout, - DialContext: (&net.Dialer{ - Timeout: dialTimeout, - }).DialContext, - }, - } -} - -// NewRetryableClient creates default retryablehttp.Client with timeouts and embedded NewClient result. -func NewRetryableClient(retryMax int) *retryablehttp.Client { - client := retryablehttp.NewClient() - client.HTTPClient = NewClient() - client.RetryWaitMax = clientTimeout - client.RetryMax = retryMax - client.Logger = nil - - return client -} diff --git a/zmagmacore/http/sc-api.go b/zmagmacore/http/sc-api.go deleted file mode 100644 index df8e1833d..000000000 --- a/zmagmacore/http/sc-api.go +++ /dev/null @@ -1,102 +0,0 @@ -package http - -import ( - "crypto/sha1" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk_common/core/util" -) - -// MakeSCRestAPICall calls smart contract with provided address -// and makes retryable request to smart contract resource with provided relative path using params. -func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string) ([]byte, error) { - var ( - resMaxCounterBody []byte - - hashMaxCounter int - hashCounters = make(map[string]int) - - sharders = extractSharders() - - lastErrMsg string - ) - - for _, sharder := range sharders { - var ( - client = NewRetryableClient(5) - u = makeScURL(params, sharder, scAddress, relativePath) - ) - - resp, err := client.Get(u.String()) - if err != nil { - lastErrMsg = fmt.Sprintf("error while requesting sharders: %v", err) - continue - } - hash, resBody, err := hashAndBytesOfReader(resp.Body) - _ = resp.Body.Close() - if err != nil { - lastErrMsg = fmt.Sprintf("error while reading response body: %v", err) - continue - } - if resp.StatusCode != http.StatusOK { - lastErrMsg = fmt.Sprintf("response status is not OK; response body: %s", string(resBody)) - continue - } - - hashCounters[hash]++ - if hashCounters[hash] > hashMaxCounter { - hashMaxCounter = hashCounters[hash] - resMaxCounterBody = resBody - } - } - - if hashMaxCounter == 0 { - return nil, errors.New("request_sharders", "no valid responses, last err: "+lastErrMsg) - } - - return resMaxCounterBody, nil -} - -// hashAndBytesOfReader computes hash of readers data and returns hash encoded to hex and bytes of reader data. -// If error occurs while reading data from reader, it returns non nil error. -func hashAndBytesOfReader(r io.Reader) (hash string, reader []byte, err error) { - h := sha1.New() - teeReader := io.TeeReader(r, h) - readerBytes, err := ioutil.ReadAll(teeReader) - if err != nil { - return "", nil, err - } - - return hex.EncodeToString(h.Sum(nil)), readerBytes, nil -} - -// extractSharders returns string slice of randomly ordered sharders existing in the current network. -func extractSharders() []string { - network := zcncore.GetNetwork() - return util.GetRandom(network.Sharders, len(network.Sharders)) -} - -const ( - // ScRestApiUrl represents base URL path to execute smart contract rest points. - ScRestApiUrl = "v1/screst/" -) - -// makeScURL creates url.URL to make smart contract request to sharder. -func makeScURL(params map[string]string, sharder, scAddress, relativePath string) *url.URL { - uString := fmt.Sprintf("%v/%v%v%v", sharder, ScRestApiUrl, scAddress, relativePath) - u, _ := url.Parse(uString) - q := u.Query() - for k, v := range params { - q.Add(k, v) - } - u.RawQuery = q.Encode() - - return u -} diff --git a/zmagmacore/http/server.go b/zmagmacore/http/server.go deleted file mode 100644 index 2ae5de73c..000000000 --- a/zmagmacore/http/server.go +++ /dev/null @@ -1,81 +0,0 @@ -package http - -import ( - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/gorilla/handlers" - "github.com/gorilla/mux" - - "github.com/0chain/gosdk/zmagmacore/config" - "github.com/0chain/gosdk/zmagmacore/log" -) - -type setupHandlers func(r *mux.Router, cfg config.Handler) - -// CreateServer creates http.Server and setups handlers. -func CreateServer(setupHandlers setupHandlers, cfg config.Handler, port int, development bool) *http.Server { - // setup CORS - router := mux.NewRouter() - setupHandlers(router, cfg) - - address := ":" + strconv.Itoa(port) - originsOk := handlers.AllowedOriginValidator(isValidOrigin) - headersOk := handlers.AllowedHeaders([]string{ - "X-Requested-With", "X-App-cmd-ID", - "X-App-cmd-Key", "Content-Type", - }) - methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"}) - - server := &http.Server{ - Addr: address, - ReadHeaderTimeout: 30 * time.Second, - WriteTimeout: 30 * time.Second, - IdleTimeout: 30 * time.Second, - MaxHeaderBytes: 1 << 20, - Handler: handlers.CORS(originsOk, headersOk, methodsOk)(router), - } - if development { // non idle & write timeouts setup to enable pprof - server.IdleTimeout = 0 - server.WriteTimeout = 0 - } - - log.Logger.Info("Ready to listen to the requests") - - return server -} - -// StartServer calls http.Server.ListenAndServe and calls app context cancel if error occurs. -func StartServer(server *http.Server, appCtxCancel func()) { - err := server.ListenAndServe() - if err != nil { - log.Logger.Warn(err.Error()) - appCtxCancel() - } -} - -func isValidOrigin(origin string) bool { - uri, err := url.Parse(origin) - if err != nil { - return false - } - - host := uri.Hostname() - switch { // allowed origins - case host == "localhost": - case host == "0chain.net": - case strings.HasSuffix(host, ".0chain.net"): - case strings.HasSuffix(host, ".alphanet-0chain.net"): - case strings.HasSuffix(host, ".devnet-0chain.net"): - case strings.HasSuffix(host, ".testnet-0chain.net"): - case strings.HasSuffix(host, ".mainnet-0chain.net"): - - default: // not allowed - return false - } - - return true -} diff --git a/zmagmacore/limiter/limiter.go b/zmagmacore/limiter/limiter.go deleted file mode 100644 index c324facc4..000000000 --- a/zmagmacore/limiter/limiter.go +++ /dev/null @@ -1,49 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package limiter - -import ( - "net/http" - "time" - - "github.com/didip/tollbooth" - "github.com/didip/tollbooth/limiter" -) - -// rateLimiter represents custom wrapper above limiter.Limiter. -type rateLimit struct { - Limiter *limiter.Limiter - RateLimit bool - RequestsPerSecond float64 -} - -// userRateLimit represents application level limiter. -var userRateLimit *rateLimit - -func (rl *rateLimit) init() { - if rl.RequestsPerSecond == 0 { - rl.RateLimit = false - return - } - rl.RateLimit = true - rl.Limiter = tollbooth.NewLimiter(rl.RequestsPerSecond, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour}). - SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}). - SetMethods([]string{"GET", "POST", "PUT", "DELETE"}) -} - -// ConfigRateLimits configures rate limits used in app. -// -// Should be called only once while application starting process. -func ConfigRateLimits(limit float64) { - userRateLimit = &rateLimit{RequestsPerSecond: limit} - userRateLimit.init() -} - -// UserRateLimit is a middleware that performs rate-limiting given request handler function. -func UserRateLimit(handler http.HandlerFunc) http.HandlerFunc { - if !userRateLimit.RateLimit { - return handler - } - return func(writer http.ResponseWriter, request *http.Request) { - tollbooth.LimitFuncHandler(userRateLimit.Limiter, handler).ServeHTTP(writer, request) - } -} diff --git a/zmagmacore/log/handler.go b/zmagmacore/log/handler.go deleted file mode 100644 index 6b4775446..000000000 --- a/zmagmacore/log/handler.go +++ /dev/null @@ -1,58 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package log - -import ( - "net/http" - "os" - "strings" - - "github.com/0chain/gosdk_common/core/sys" -) - -// HandleFunc returns handle function that writes logs to http.ResponseWriter with provided buffer size. -// Buffered length represented in kilobytes. -func HandleFunc(buffLen int64) func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, _ *http.Request) { - file, err := os.Open(logName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - defer func() { - _ = file.Close() - }() - - stat, err := sys.Files.Stat(logName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - var ( - writeLen = buffLen * 1024 - brokenLines = true // flag that describes existence of broken lines - ) - if writeLen > stat.Size() { - writeLen = stat.Size() - brokenLines = false - } - - buf := make([]byte, writeLen) - _, err = file.ReadAt(buf, stat.Size()-writeLen) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - // cut broken lines if it exist - if brokenLines { - lbInd := strings.Index(string(buf), "\n") - buf = buf[lbInd+1:] - } - - if _, err := w.Write(buf); err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - } -} diff --git a/zmagmacore/log/logging.go b/zmagmacore/log/logging.go deleted file mode 100644 index 7348bcb08..000000000 --- a/zmagmacore/log/logging.go +++ /dev/null @@ -1,93 +0,0 @@ -package log - -import ( - "os" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - "gopkg.in/natefinch/lumberjack.v2" - - "github.com/0chain/gosdk/zmagmacore/errors" -) - -var ( - // Logger represents main logger implementation used in app. - Logger = zap.NewNop() - - // logName - logName string -) - -// InitLogging initializes the main Logger consistent with passed log directory and level. -// -// If an error occurs during execution, the program terminates with code 2 and the error will be written in os.Stderr. -// -// InitLogging should be used only once while application is starting. -func InitLogging(development bool, logDir, level string) { - logName = logDir + "/" + "logs.log" - var ( - logWriter = getWriteSyncer(logName) - logCfg zap.Config - ) - - if development { - logCfg = zap.NewProductionConfig() - logCfg.DisableCaller = true - } else { - logCfg = zap.NewDevelopmentConfig() - logCfg.EncoderConfig.LevelKey = "level" - logCfg.EncoderConfig.NameKey = "name" - logCfg.EncoderConfig.MessageKey = "msg" - logCfg.EncoderConfig.CallerKey = "caller" - logCfg.EncoderConfig.StacktraceKey = "stacktrace" - - logWriter = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), logWriter) - } - _ = logCfg.Level.UnmarshalText([]byte(level)) - logCfg.Encoding = consoleEncoderType - logCfg.EncoderConfig.TimeKey = "timestamp" - logCfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder - - l, err := logCfg.Build(setOutput(logWriter, logCfg)) - if err != nil { - errors.ExitErr("error while build logger config", err, 2) - } - - Logger = l -} - -const ( - jsonEncoderType = "json" - consoleEncoderType = "console" -) - -// setOutput replaces existing Core with new, that writes to passed zapcore.WriteSyncer. -func setOutput(ws zapcore.WriteSyncer, conf zap.Config) zap.Option { - var enc zapcore.Encoder - switch conf.Encoding { - case jsonEncoderType: - enc = zapcore.NewJSONEncoder(conf.EncoderConfig) - case consoleEncoderType: - enc = zapcore.NewConsoleEncoder(conf.EncoderConfig) - default: - errors.ExitMsg("error while build logger config", 2) - } - - return zap.WrapCore(func(core zapcore.Core) zapcore.Core { - return zapcore.NewCore(enc, ws, conf.Level) - }) -} - -// getWriteSyncer creates zapcore.WriteSyncer using provided log file. -func getWriteSyncer(logName string) zapcore.WriteSyncer { - var ioWriter = &lumberjack.Logger{ - Filename: logName, - MaxSize: 10, // MB - MaxBackups: 3, // number of backups - MaxAge: 28, // days - LocalTime: true, - Compress: false, // disabled by default - } - _ = ioWriter.Rotate() - return zapcore.AddSync(ioWriter) -} diff --git a/zmagmacore/magmasc/acknowledgment.go b/zmagmacore/magmasc/acknowledgment.go deleted file mode 100644 index 89431e34c..000000000 --- a/zmagmacore/magmasc/acknowledgment.go +++ /dev/null @@ -1,123 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/storage" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // Acknowledgment contains the necessary data obtained when the consumer - // accepts the provider terms and stores in the state of the blockchain - // as a result of performing the consumerAcceptTerms MagmaSmartContract function. - Acknowledgment struct { - SessionID string `json:"session_id"` - AccessPointID string `json:"access_point_id"` - Billing Billing `json:"billing"` - Consumer *Consumer `json:"consumer,omitempty"` - Provider *Provider `json:"provider,omitempty"` - Terms ProviderTerms `json:"terms"` - TokenPool *TokenPool `json:"token_pool,omitempty"` - } -) - -var ( - // Make sure Acknowledgment implements PoolConfigurator interface. - _ PoolConfigurator = (*Acknowledgment)(nil) - - // Make sure Acknowledgment implements Value interface. - _ storage.Value = (*Acknowledgment)(nil) - - // Make sure Acknowledgment implements Serializable interface. - _ util.Serializable = (*Acknowledgment)(nil) -) - -// ActiveKey returns key used for operations with storage.Storage -// AcknowledgmentPrefix + AcknowledgmentActivePrefixPart + Acknowledgment.SessionID. -func (m *Acknowledgment) ActiveKey() []byte { - return []byte(AcknowledgmentPrefix + AcknowledgmentActivePrefixPart + m.SessionID) -} - -// Decode implements util.Serializable interface. -func (m *Acknowledgment) Decode(blob []byte) error { - var ackn Acknowledgment - if err := json.Unmarshal(blob, &ackn); err != nil { - return errDecodeData.Wrap(err) - } - if err := ackn.Validate(); err != nil { - return err - } - - m.SessionID = ackn.SessionID - m.AccessPointID = ackn.AccessPointID - m.Billing = ackn.Billing - m.Consumer = ackn.Consumer - m.Provider = ackn.Provider - m.Terms = ackn.Terms - m.TokenPool = ackn.TokenPool - - return nil -} - -// Encode implements util.Serializable interface. -func (m *Acknowledgment) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} - -// Key returns key with AcknowledgmentPrefix. -// Used for operations with storage.Storage. -func (m *Acknowledgment) Key() []byte { - return []byte(AcknowledgmentPrefix + m.SessionID) -} - -// PoolBalance implements PoolConfigurator interface. -func (m *Acknowledgment) PoolBalance() uint64 { - return m.Terms.GetAmount() -} - -// PoolID implements PoolConfigurator interface. -func (m *Acknowledgment) PoolID() string { - return m.SessionID -} - -// PoolHolderID implements PoolConfigurator interface. -func (m *Acknowledgment) PoolHolderID() string { - return Address -} - -// PoolPayerID implements PoolConfigurator interface. -func (m *Acknowledgment) PoolPayerID() string { - return m.Consumer.ID -} - -// PoolPayeeID implements PoolConfigurator interface. -func (m *Acknowledgment) PoolPayeeID() string { - return m.Provider.ID -} - -// Validate checks Acknowledgment for correctness. -// If it is not return errInvalidAcknowledgment. -func (m *Acknowledgment) Validate() (err error) { - switch { // is invalid - case m.SessionID == "": - err = errors.New(errCodeBadRequest, "session id is required") - - case m.AccessPointID == "": - err = errors.New(errCodeBadRequest, "access point id is required") - - case m.Consumer == nil || m.Consumer.ExtID == "": - err = errors.New(errCodeBadRequest, "consumer external id is required") - - case m.Provider == nil || m.Provider.ExtID == "": - err = errors.New(errCodeBadRequest, "provider external id is required") - - default: - return nil // is valid - } - - return errInvalidAcknowledgment.Wrap(err) -} diff --git a/zmagmacore/magmasc/acknowledgment_test.go b/zmagmacore/magmasc/acknowledgment_test.go deleted file mode 100644 index 1e0a821f1..000000000 --- a/zmagmacore/magmasc/acknowledgment_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" -) - -func Test_Acknowledgment_Decode(t *testing.T) { - t.Parallel() - - ackn := mockAcknowledgment() - blob, err := json.Marshal(ackn) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - acknInvalid := mockAcknowledgment() - acknInvalid.SessionID = "" - blobInvalid, err := json.Marshal(acknInvalid) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [3]struct { - name string - blob []byte - want *Acknowledgment - error bool - }{ - { - name: "OK", - blob: blob, - want: ackn, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: &Acknowledgment{}, - error: true, - }, - { - name: "Invalid_ERR", - blob: blobInvalid, - want: &Acknowledgment{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := &Acknowledgment{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, test.error) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Acknowledgment_Encode(t *testing.T) { - t.Parallel() - - ackn := mockAcknowledgment() - blob, err := json.Marshal(ackn) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - ackn *Acknowledgment - want []byte - }{ - { - name: "OK", - ackn: ackn, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.ackn.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Acknowledgment_Key(t *testing.T) { - t.Parallel() - - t.Run("OK", func(t *testing.T) { - t.Parallel() - - ackn := mockAcknowledgment() - want := []byte(AcknowledgmentPrefix + ackn.SessionID) - - if got := ackn.Key(); !reflect.DeepEqual(got, want) { - t.Errorf("Key() got: %v | want: %v", string(got), string(want)) - } - }) -} - -func Test_Acknowledgment_Validate(t *testing.T) { - t.Parallel() - - acknEmptySessionID := mockAcknowledgment() - acknEmptySessionID.SessionID = "" - - acknEmptyAccessPointID := mockAcknowledgment() - acknEmptyAccessPointID.AccessPointID = "" - - acknEmptyConsumerExtID := mockAcknowledgment() - acknEmptyConsumerExtID.Consumer.ExtID = "" - - acknEmptyProviderExtID := mockAcknowledgment() - acknEmptyProviderExtID.Provider.ExtID = "" - - tests := [5]struct { - name string - ackn *Acknowledgment - error bool - }{ - { - name: "OK", - ackn: mockAcknowledgment(), - error: false, - }, - { - name: "Empty_Session_ID", - ackn: acknEmptySessionID, - error: true, - }, - { - name: "Empty_Access_Point_ID", - ackn: acknEmptyAccessPointID, - error: true, - }, - { - name: "Empty_Consumer_Ext_ID", - ackn: acknEmptyConsumerExtID, - error: true, - }, - { - name: "Empty_Provider_Txt_ID", - ackn: acknEmptyProviderExtID, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if err := test.ackn.Validate(); (err != nil) != test.error { - t.Errorf("validate() error: %v | want: %v", err, test.error) - } - }) - } -} diff --git a/zmagmacore/magmasc/actions.go b/zmagmacore/magmasc/actions.go deleted file mode 100644 index d164866e9..000000000 --- a/zmagmacore/magmasc/actions.go +++ /dev/null @@ -1,284 +0,0 @@ -package magmasc - -import ( - "context" - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/transaction" -) - -// ExecuteSessionStart starts session for provided IDs by executing ConsumerSessionStartFuncName. -func ExecuteSessionStart(ctx context.Context, sessID string) (*Acknowledgment, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - ackn, err := RequestAcknowledgment(sessID) - if err != nil { - return nil, err - } - input, err := json.Marshal(&ackn) - if err != nil { - return nil, err - } - txnHash, err := txn.ExecuteSmartContract( - ctx, - Address, - ConsumerSessionStartFuncName, - string(input), - ackn.Terms.GetAmount(), - ) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, txnHash) - if err != nil { - return nil, err - } - - ackn = new(Acknowledgment) - if err := json.Unmarshal([]byte(txn.TransactionOutput), &ackn); err != nil { - return nil, err - } - - return ackn, err -} - -// ExecuteDataUsage executes ProviderDataUsageFuncName and returns current Acknowledgment. -func ExecuteDataUsage( - ctx context.Context, downloadBytes, uploadBytes uint64, sessID string, sessTime uint32) (*Acknowledgment, error) { - - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - dataUsage := DataUsage{ - DownloadBytes: downloadBytes, - UploadBytes: uploadBytes, - SessionID: sessID, - SessionTime: sessTime, - } - input, err := json.Marshal(&dataUsage) - if err != nil { - return nil, err - } - txnHash, err := txn.ExecuteSmartContract(ctx, Address, ProviderDataUsageFuncName, string(input), 0) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, txnHash) - if err != nil { - return nil, err - } - - ackn := Acknowledgment{} - if err = json.Unmarshal([]byte(txn.TransactionOutput), &ackn); err != nil { - return nil, err - } - - return &ackn, err -} - -// ExecuteSessionStop requests Acknowledgment from the blockchain and executes ConsumerSessionStopFuncName -// and verifies including the transaction in the blockchain. -// -// Returns Acknowledgment for session with provided ID. -func ExecuteSessionStop(ctx context.Context, sessionID string) (*Acknowledgment, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - // need to respond billing to compute value of txn - ackn, err := RequestAcknowledgment(sessionID) - if err != nil { - return nil, err - } - - input, err := json.Marshal(&ackn) - if err != nil { - return nil, err - } - txnHash, err := txn.ExecuteSmartContract( - ctx, - Address, - ConsumerSessionStopFuncName, - string(input), - ackn.Billing.Amount, - ) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, txnHash) - if err != nil { - return nil, err - } - - ackn = new(Acknowledgment) - if err := json.Unmarshal([]byte(txn.TransactionOutput), ackn); err != nil { - return nil, err - } - - return ackn, err -} - -// ExecuteProviderRegister executes provider registration magma sc function and returns current Provider. -func ExecuteProviderRegister(ctx context.Context, provider *Provider) (*Provider, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - input, err := json.Marshal(provider) - if err != nil { - return nil, err - } - txnHash, err := txn.ExecuteSmartContract(ctx, Address, ProviderRegisterFuncName, string(input), 0) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, txnHash) - if err != nil { - return nil, err - } - - provider = &Provider{} - if err = json.Unmarshal([]byte(txn.TransactionOutput), provider); err != nil { - return nil, err - } - - return provider, nil -} - -// ExecuteProviderUpdate executes update provider magma sc function and returns updated Provider. -func ExecuteProviderUpdate(ctx context.Context, provider *Provider) (*Provider, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - input := provider.Encode() - hash, err := txn.ExecuteSmartContract(ctx, Address, ProviderUpdateFuncName, string(input), 0) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, hash) - if err != nil { - return nil, err - } - - provider = new(Provider) - if err := json.Unmarshal([]byte(txn.TransactionOutput), provider); err != nil { - return nil, err - } - - return provider, nil -} - -// ExecuteConsumerRegister executes consumer registration magma sc function and returns current Consumer. -func ExecuteConsumerRegister(ctx context.Context, consumer *Consumer) (*Consumer, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - input, err := json.Marshal(consumer) - if err != nil { - return nil, err - } - txnHash, err := txn.ExecuteSmartContract(ctx, Address, ConsumerRegisterFuncName, string(input), 0) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, txnHash) - if err != nil { - return nil, err - } - - consumer = &Consumer{} - if err = json.Unmarshal([]byte(txn.TransactionOutput), consumer); err != nil { - return nil, err - } - - return consumer, nil -} - -// ExecuteConsumerUpdate executes update consumer magma sc function and returns updated Consumer. -func ExecuteConsumerUpdate(ctx context.Context, consumer *Consumer) (*Consumer, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - input := consumer.Encode() - hash, err := txn.ExecuteSmartContract(ctx, Address, ConsumerUpdateFuncName, string(input), 0) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, hash) - if err != nil { - return nil, err - } - - consumer = new(Consumer) - if err := json.Unmarshal([]byte(txn.TransactionOutput), consumer); err != nil { - return nil, err - } - - return consumer, nil -} - -// ExecuteSessionInit executes session init magma sc function and returns Acknowledgment. -func ExecuteSessionInit(ctx context.Context, consExtID, provExtID, apID, sessID string, terms ProviderTerms) (*Acknowledgment, error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return nil, err - } - - ackn := Acknowledgment{ - Consumer: &Consumer{ - ExtID: consExtID, - }, - Provider: &Provider{ - ExtID: provExtID, - }, - AccessPointID: apID, - SessionID: sessID, - Terms: terms, - } - input, err := json.Marshal(&ackn) - if err != nil { - return nil, err - } - txnHash, err := txn.ExecuteSmartContract( - ctx, - Address, - ProviderSessionInitFuncName, - string(input), - 0, - ) - if err != nil { - return nil, err - } - - txn, err = transaction.VerifyTransaction(ctx, txnHash) - if err != nil { - return nil, err - } - - ackn = Acknowledgment{} - if err := json.Unmarshal([]byte(txn.TransactionOutput), &ackn); err != nil { - return nil, err - } - - return &ackn, err -} diff --git a/zmagmacore/magmasc/api.go b/zmagmacore/magmasc/api.go deleted file mode 100644 index eda97d70b..000000000 --- a/zmagmacore/magmasc/api.go +++ /dev/null @@ -1,180 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/http" -) - -// GetAllConsumers makes smart contract rest api call to magma smart contract -// GetAllConsumersRP rest point to retrieve all registered consumer.Consumer. -func GetAllConsumers() ([]Consumer, error) { - resp, err := http.MakeSCRestAPICall(Address, GetAllConsumersRP, nil) - if err != nil { - return nil, err - } - - consumers := make([]Consumer, 0) - if err = json.Unmarshal(resp, &consumers); err != nil { - return nil, err - } - - return consumers, err -} - -// GetAllProviders makes smart contract rest api call to magma smart contract -// GetAllProvidersRP rest point to retrieve all registered provider.Provider. -func GetAllProviders() ([]Provider, error) { - resp, err := http.MakeSCRestAPICall(Address, GetAllProvidersRP, nil) - if err != nil { - return nil, err - } - - providers := make([]Provider, 0) - if err = json.Unmarshal(resp, &providers); err != nil { - return nil, err - } - - return providers, err -} - -// RequestAcknowledgment makes smart contract rest api call to magma smart contract -// AcknowledgmentRP rest point to retrieve Acknowledgment. -func RequestAcknowledgment(sessionID string) (*Acknowledgment, error) { - params := map[string]string{ - "id": sessionID, - } - - blob, err := http.MakeSCRestAPICall(Address, AcknowledgmentRP, params) - if err != nil { - return nil, err - } - - ackn := Acknowledgment{} - if err = json.Unmarshal(blob, &ackn); err != nil { - return nil, err - } - - return &ackn, nil -} - -// IsAcknowledgmentExist makes smart contract rest api call to magma smart contract -// IsAcknowledgmentExistRP rest point to ensure that Acknowledgment with provided session ID exist in the blockchain. -func IsAcknowledgmentExist(sessionID string) (bool, error) { - params := map[string]string{ - "id": sessionID, - } - - blob, err := http.MakeSCRestAPICall(Address, IsAcknowledgmentExistRP, params) - if err != nil { - return false, err - } - - var exist bool - if err = json.Unmarshal(blob, &exist); err != nil { - return false, err - } - - return exist, nil -} - -// VerifyAcknowledgmentAccepted makes smart contract rest api call to magma smart contract -// VerifyAcknowledgmentAcceptedRP rest point to ensure that Acknowledgment with provided IDs was accepted. -func VerifyAcknowledgmentAccepted(sessionID, accessPointID, consumerExtID, providerExtID string) (*Acknowledgment, error) { - params := map[string]string{ - "session_id": sessionID, - "access_point_id": accessPointID, - "provider_ext_id": providerExtID, - "consumer_ext_id": consumerExtID, - } - - blob, err := http.MakeSCRestAPICall(Address, VerifyAcknowledgmentAcceptedRP, params) - if err != nil { - return nil, err - } - - ackn := Acknowledgment{} - if err = json.Unmarshal(blob, &ackn); err != nil { - return nil, err - } - - return &ackn, nil -} - -// ConsumerFetch makes smart contract rest api call to magma smart contract -// ConsumerFetchRP rest point to fetch Consumer info. -func ConsumerFetch(id string) (*Consumer, error) { - params := map[string]string{ - "ext_id": id, - } - - blob, err := http.MakeSCRestAPICall(Address, ConsumerFetchRP, params) - if err != nil { - return nil, err - } - - cons := Consumer{} - if err = json.Unmarshal(blob, &cons); err != nil { - return nil, err - } - - return &cons, nil -} - -// ProviderFetch makes smart contract rest api call to magma smart contract -// ProviderFetchRP rest point to fetch Provider info. -func ProviderFetch(id string) (*Provider, error) { - params := map[string]string{ - "ext_id": id, - } - - blob, err := http.MakeSCRestAPICall(Address, ProviderFetchRP, params) - if err != nil { - return nil, err - } - - prov := Provider{} - if err = json.Unmarshal(blob, &prov); err != nil { - return nil, err - } - - return &prov, nil -} - -// IsConsumerRegisteredRP makes smart contract rest api call to magma smart contract -// ConsumerRegisteredRP rest point to check registration of the consumer with provided external ID. -func IsConsumerRegisteredRP(extID string) (bool, error) { - params := map[string]string{ - "ext_id": extID, - } - registeredByt, err := http.MakeSCRestAPICall(Address, ConsumerRegisteredRP, params) - if err != nil { - return false, err - } - - var registered bool - if err := json.Unmarshal(registeredByt, ®istered); err != nil { - return false, err - } - - return registered, nil -} - -// IsProviderRegisteredRP makes smart contract rest api call to magma smart contract -// ProviderRegisteredRP rest point to check registration of the provider with provided external ID. -func IsProviderRegisteredRP(extID string) (bool, error) { - params := map[string]string{ - "ext_id": extID, - } - registeredByt, err := http.MakeSCRestAPICall(Address, ProviderRegisteredRP, params) - if err != nil { - return false, err - } - - var registered bool - if err := json.Unmarshal(registeredByt, ®istered); err != nil { - return false, err - } - - return registered, nil -} diff --git a/zmagmacore/magmasc/billing.go b/zmagmacore/magmasc/billing.go deleted file mode 100644 index 49b0b2bc1..000000000 --- a/zmagmacore/magmasc/billing.go +++ /dev/null @@ -1,79 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/time" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // Billing represents all info about data usage. - Billing struct { - Amount uint64 `json:"amount"` - DataUsage DataUsage `json:"data_usage"` - CompletedAt time.Timestamp `json:"completed_at,omitempty"` - } -) - -var ( - // Make sure Billing implements Serializable interface. - _ util.Serializable = (*Billing)(nil) -) - -// CalcAmount calculates and sets the billing Amount value by given price. -// NOTE: the cost value must be represented in token units per megabyte. -func (m *Billing) CalcAmount(terms ProviderTerms) { - price := float64(terms.GetPrice()) - if price > 0 { - // data usage summary in megabytes - mbps := float64(m.DataUsage.UploadBytes+m.DataUsage.DownloadBytes) / million - m.Amount = uint64(mbps * price) // rounded amount of megabytes multiplied by price - } - if minCost := terms.GetMinCost(); m.Amount < minCost { - m.Amount = minCost - } -} - -// Decode implements util.Serializable interface. -func (m *Billing) Decode(blob []byte) error { - var bill Billing - if err := json.Unmarshal(blob, &bill); err != nil { - return errDecodeData.Wrap(err) - } - - m.Amount = bill.Amount - m.DataUsage = bill.DataUsage - m.CompletedAt = bill.CompletedAt - - return nil -} - -// Encode implements util.Serializable interface. -func (m *Billing) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} - -// Validate checks given data usage is correctness for the billing. -func (m *Billing) Validate(dataUsage *DataUsage) (err error) { - switch { - case dataUsage == nil: - err = errors.New(errCodeBadRequest, "data usage required") - - case m.DataUsage.SessionTime > dataUsage.SessionTime: - err = errors.New(errCodeBadRequest, "invalid session time") - - case m.DataUsage.UploadBytes > dataUsage.UploadBytes: - err = errors.New(errCodeBadRequest, "invalid upload bytes") - - case m.DataUsage.DownloadBytes > dataUsage.DownloadBytes: - err = errors.New(errCodeBadRequest, "invalid download bytes") - - default: - return nil // is valid - everything is ok - } - - return errInvalidDataUsage.Wrap(err) -} diff --git a/zmagmacore/magmasc/billing_test.go b/zmagmacore/magmasc/billing_test.go deleted file mode 100644 index fdce86e09..000000000 --- a/zmagmacore/magmasc/billing_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/0chain/gosdk/zmagmacore/time" -) - -func Test_Billing_CalcAmount(t *testing.T) { - t.Parallel() - - bill, terms := mockBilling(), mockProviderTerms() - - termsMinCost := mockProviderTerms() - termsMinCost.MinCost = 1000 - - // data usage summary in megabytes - mbps := float64(bill.DataUsage.UploadBytes+bill.DataUsage.DownloadBytes) / million - want := uint64(mbps * float64(terms.GetPrice())) - - tests := [3]struct { - name string - bill Billing - terms ProviderTerms - want uint64 - }{ - { - name: "OK", - bill: bill, - terms: terms, - want: want, - }, - { - name: "Zero_Amount_OK", - bill: mockBilling(), - terms: ProviderTerms{}, - want: 0, - }, - { - name: "Min_Cost_Amount_OK", - bill: mockBilling(), - terms: termsMinCost, - want: termsMinCost.GetMinCost(), - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if test.bill.Amount != 0 { // must be zero before first call CalcAmount() - t.Errorf("Billing.Amount is: %v | want: %v", test.bill.Amount, 0) - } - - test.bill.CalcAmount(test.terms) - if test.bill.Amount != test.want { // must be the same value with test.want after called CalcAmount() - t.Errorf("GetVolume() got: %v | want: %v", test.bill.Amount, test.want) - } - }) - } -} - -func Test_Billing_Decode(t *testing.T) { - t.Parallel() - - bill := mockBilling() - blob, err := json.Marshal(bill) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - billCompleted := mockBilling() - billCompleted.CalcAmount(mockProviderTerms()) - billCompleted.CompletedAt = time.Now() - blobCompleted, err := json.Marshal(billCompleted) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [3]struct { - name string - blob []byte - want Billing - error bool - }{ - { - name: "OK", - blob: blob, - want: bill, - error: false, - }, - { - name: "Completed_OK", - blob: blobCompleted, - want: billCompleted, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: Billing{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := Billing{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, test.error) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Billing_Encode(t *testing.T) { - t.Parallel() - - bill := mockBilling() - blob, err := json.Marshal(bill) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - bill Billing - want []byte - }{ - { - name: "OK", - bill: bill, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.bill.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Billing_Validate(t *testing.T) { - t.Parallel() - - bill, dataUsage := mockBilling(), mockDataUsage() - - duInvalidSessionTime := mockDataUsage() - duInvalidSessionTime.SessionTime = bill.DataUsage.SessionTime - 1 - - duInvalidUploadBytes := mockDataUsage() - duInvalidUploadBytes.UploadBytes = bill.DataUsage.UploadBytes - 1 - - duInvalidDownloadBytes := mockDataUsage() - duInvalidDownloadBytes.DownloadBytes = bill.DataUsage.DownloadBytes - 1 - - tests := [5]struct { - name string - du *DataUsage - bill Billing - error bool - }{ - { - name: "OK", - du: &dataUsage, - bill: bill, - error: false, - }, - { - name: "nil_Data_Usage_ERR", - du: nil, - bill: bill, - error: true, - }, - { - name: "Invalid_Session_Time_ERR", - du: &duInvalidSessionTime, - bill: bill, - error: true, - }, - { - name: "Invalid_Upload_Bytes_ERR", - du: &duInvalidUploadBytes, - bill: bill, - error: true, - }, - { - name: "Invalid_Download_Bytes_ERR", - du: &duInvalidDownloadBytes, - bill: bill, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if err := test.bill.Validate(test.du); (err != nil) != test.error { - t.Errorf("validate() error: %v | want: %v", err, test.error) - } - }) - } -} diff --git a/zmagmacore/magmasc/const.go b/zmagmacore/magmasc/const.go deleted file mode 100644 index 3c2d46afc..000000000 --- a/zmagmacore/magmasc/const.go +++ /dev/null @@ -1,111 +0,0 @@ -package magmasc - -const ( - // Address represents the address of the Magma smart contract. - // Used while making requests to smart contract's rest points and executing smart contracts functions. - Address = "11f8411db41e34cea7c100f19faff32da8f3cd5a80635731cec06f32d08089be" - - // GetAllConsumersRP represents MagmaSC relative path. - // Used to list all registered in the blockchain consumers. - GetAllConsumersRP = "/allConsumers" - - // GetAllProvidersRP represents MagmaSC relative path. - // Used to list all registered in the blockchain providers. - GetAllProvidersRP = "/allProviders" -) - -const ( - // AcknowledgmentPrefix represents prefix to save into storage. - AcknowledgmentPrefix = "ackn" - - // AcknowledgmentActivePrefixPart represents prefix part to save into storage. - AcknowledgmentActivePrefixPart = "act" - - // AcknowledgmentRP represents MagmaSC relative path. - // Used to retrieve accepted acknowledgment. - AcknowledgmentRP = "/acknowledgmentAccepted" - - // IsAcknowledgmentExistRP represents MagmaSC relative path. - // Used to check existing of acknowledgment. - IsAcknowledgmentExistRP = "/acknowledgmentExist" - - // VerifyAcknowledgmentAcceptedRP represents MagmaSC relative path. - // Used to verify accepting Provider's terms by Consumer. - VerifyAcknowledgmentAcceptedRP = "/acknowledgmentAcceptedVerify" -) - -const ( - // ConsumerRegisterFuncName represents MagmaSC function. - // Used to register bandwidth-marketplace's node. - ConsumerRegisterFuncName = "consumer_register" - - // ConsumerSessionStartFuncName represents MagmaSC function. - // Used to start session. - ConsumerSessionStartFuncName = "consumer_session_start" - - // ConsumerSessionStopFuncName represents MagmaSC function. - // Used to stop session. - ConsumerSessionStopFuncName = "consumer_session_stop" - - // ConsumerUpdateFuncName represents MagmaSC function. - // Used to update consumer node info. - ConsumerUpdateFuncName = "consumer_update" - - // ConsumerFetchRP represents MagmaSC relative path. - // Used to fetch consumer info. - ConsumerFetchRP = "/consumerFetch" - - // ConsumerRegisteredRP represents MagmaSC relative path. - // Used to fetch consumer registered info. - ConsumerRegisteredRP = "/consumerExist" - - // consumerType contents a value of consumer node type. - consumerType = "consumer" -) - -const ( - // TermsExpiredDuration represents value for - // minimal duration of provider terms that will pass check it's expired. - TermsExpiredDuration = 1 * 60 // 1 minute - - // ProviderDataUsageFuncName represents MagmaSC function. - // Used to update session info about data usages and collecting payments data - // from consumer to provider. - ProviderDataUsageFuncName = "provider_data_usage" - - // ProviderRegisterFuncName represents MagmaSC function. - // Used to register bandwidth-marketplace's node. - ProviderRegisterFuncName = "provider_register" - - // ProviderUpdateFuncName represents MagmaSC function. - // Used for updating provider terms. - ProviderUpdateFuncName = "provider_update" - - // ProviderSessionInitFuncName represents MagmaSC function. - // Used for initializing session by a provider. - ProviderSessionInitFuncName = "provider_session_init" - - // ProviderFetchRP represents MagmaSC relative path. - // Used to fetch provider info. - ProviderFetchRP = "/providerFetch" - - // ProviderRegisteredRP represents MagmaSC relative path. - // Used to fetch provider registered info. - ProviderRegisteredRP = "/providerExist" - - // providerType contents a value of provider node type. - providerType = "provider" -) - -const ( - // one billion (Giga) is a unit prefix in metric systems - // of units denoting a factor of one billion (1e9 or 1_000_000_000). - billion = 1e9 - - // one million (Mega) is a unit prefix in metric systems - // of units denoting a factor of one million (1e6 or 1_000_000). - million = 1e6 - - // octet represents number of bits in an octet. - octet = 8 -) diff --git a/zmagmacore/magmasc/consumer.go b/zmagmacore/magmasc/consumer.go deleted file mode 100644 index 7433a9b13..000000000 --- a/zmagmacore/magmasc/consumer.go +++ /dev/null @@ -1,75 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/config" - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/node" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // Consumer represents consumers node stored in blockchain. - Consumer struct { - ID string `json:"id"` - ExtID string `json:"ext_id"` - Host string `json:"host,omitempty"` - } -) - -var ( - // Make sure Consumer implements Serializable interface. - _ util.Serializable = (*Consumer)(nil) -) - -// NewConsumerFromCfg creates Consumer from config.Consumer. -func NewConsumerFromCfg(cfg *config.Consumer) *Consumer { - return &Consumer{ - ID: node.ID(), - ExtID: cfg.ExtID, - Host: cfg.Host, - } -} - -// Decode implements util.Serializable interface. -func (m *Consumer) Decode(blob []byte) error { - var consumer Consumer - if err := json.Unmarshal(blob, &consumer); err != nil { - return errDecodeData.Wrap(err) - } - if err := consumer.Validate(); err != nil { - return err - } - - m.ID = consumer.ID - m.ExtID = consumer.ExtID - m.Host = consumer.Host - - return nil -} - -// Encode implements util.Serializable interface. -func (m *Consumer) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} - -// GetType returns node type. -func (m *Consumer) GetType() string { - return consumerType -} - -// Validate checks the Consumer for correctness. -// If it is not return errInvalidConsumer. -func (m *Consumer) Validate() (err error) { - switch { // is invalid - case m.ExtID == "": - err = errors.New(errCodeBadRequest, "consumer external id is required") - - default: - return nil // is valid - } - - return errInvalidConsumer.Wrap(err) -} diff --git a/zmagmacore/magmasc/consumer_test.go b/zmagmacore/magmasc/consumer_test.go deleted file mode 100644 index 424e7cc0e..000000000 --- a/zmagmacore/magmasc/consumer_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" -) - -func Test_Consumer_Decode(t *testing.T) { - t.Parallel() - - cons := mockConsumer() - blob, err := json.Marshal(cons) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - consInvalid := mockConsumer() - consInvalid.ExtID = "" - extIDBlobInvalid, err := json.Marshal(consInvalid) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [3]struct { - name string - blob []byte - want *Consumer - error bool - }{ - { - name: "OK", - blob: blob, - want: cons, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: &Consumer{}, - error: true, - }, - { - name: "Ext_ID_Invalid_ERR", - blob: extIDBlobInvalid, - want: &Consumer{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := &Consumer{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, nil) - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Consumer_Encode(t *testing.T) { - t.Parallel() - - cons := mockConsumer() - blob, err := json.Marshal(cons) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - cons *Consumer - want []byte - }{ - { - name: "OK", - cons: cons, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.cons.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Consumer_GetType(t *testing.T) { - t.Parallel() - - t.Run("OK", func(t *testing.T) { - t.Parallel() - - cons := Consumer{} - if got := cons.GetType(); got != consumerType { - t.Errorf("GetType() got: %v | want: %v", got, consumerType) - } - }) -} - -func Test_Consumer_Validate(t *testing.T) { - t.Parallel() - - consEmptyExtID := mockConsumer() - consEmptyExtID.ExtID = "" - - tests := [2]struct { - name string - cons *Consumer - error bool - }{ - { - name: "OK", - cons: mockConsumer(), - error: false, - }, - { - name: "Empty_Ext_ID_ERR", - cons: consEmptyExtID, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if err := test.cons.Validate(); (err != nil) != test.error { - t.Errorf("validate() error: %v | want: %v", err, test.error) - } - }) - } -} diff --git a/zmagmacore/magmasc/datausage.go b/zmagmacore/magmasc/datausage.go deleted file mode 100644 index 66d5a995d..000000000 --- a/zmagmacore/magmasc/datausage.go +++ /dev/null @@ -1,60 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // DataUsage represents session data sage implementation. - DataUsage struct { - DownloadBytes uint64 `json:"download_bytes"` - UploadBytes uint64 `json:"upload_bytes"` - SessionID string `json:"session_id"` - SessionTime uint32 `json:"session_time"` - } -) - -var ( - // Make sure DataUsage implements Serializable interface. - _ util.Serializable = (*DataUsage)(nil) -) - -// Decode implements util.Serializable interface. -func (m *DataUsage) Decode(blob []byte) error { - var dataUsage DataUsage - if err := json.Unmarshal(blob, &dataUsage); err != nil { - return errDecodeData.Wrap(err) - } - if err := dataUsage.Validate(); err != nil { - return err - } - - m.DownloadBytes = dataUsage.DownloadBytes - m.UploadBytes = dataUsage.UploadBytes - m.SessionID = dataUsage.SessionID - m.SessionTime = dataUsage.SessionTime - - return nil -} - -// Encode implements util.Serializable interface. -func (m *DataUsage) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} - -// Validate checks DataUsage for correctness. -func (m *DataUsage) Validate() (err error) { - switch { // is invalid - case m.SessionID == "": - err = errors.New(errCodeBadRequest, "session id is required") - - default: // is valid - return nil - } - - return errInvalidDataUsage.Wrap(err) -} diff --git a/zmagmacore/magmasc/datausage_test.go b/zmagmacore/magmasc/datausage_test.go deleted file mode 100644 index 01012868e..000000000 --- a/zmagmacore/magmasc/datausage_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" -) - -func Test_DataUsage_Decode(t *testing.T) { - t.Parallel() - - dataUsage := mockDataUsage() - blob, err := json.Marshal(dataUsage) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - dataUsageInvalid := mockDataUsage() - dataUsageInvalid.SessionID = "" - blobInvalid, err := json.Marshal(dataUsageInvalid) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [3]struct { - name string - blob []byte - want *DataUsage - error bool - }{ - { - name: "OK", - blob: blob, - want: &dataUsage, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: &DataUsage{}, - error: true, - }, - { - name: "Invalid_ERR", - blob: blobInvalid, - want: &DataUsage{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := &DataUsage{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, test.error) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_DataUsage_Encode(t *testing.T) { - t.Parallel() - - dataUsage := mockDataUsage() - blob, err := json.Marshal(dataUsage) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - dataUsage *DataUsage - want []byte - }{ - { - name: "OK", - dataUsage: &dataUsage, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.dataUsage.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_DataUsage_Validate(t *testing.T) { - t.Parallel() - - duEmptySessionID := mockDataUsage() - duEmptySessionID.SessionID = "" - - tests := [2]struct { - name string - usage DataUsage - error bool - }{ - { - name: "OK", - usage: mockDataUsage(), - error: false, - }, - { - name: "EmptySessionID", - usage: duEmptySessionID, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if err := test.usage.Validate(); (err != nil) != test.error { - t.Errorf("validate() error: %v | want: %v", err, test.error) - } - }) - } -} diff --git a/zmagmacore/magmasc/errors.go b/zmagmacore/magmasc/errors.go deleted file mode 100644 index f67599bf2..000000000 --- a/zmagmacore/magmasc/errors.go +++ /dev/null @@ -1,36 +0,0 @@ -package magmasc - -import ( - "github.com/0chain/gosdk/zmagmacore/errors" -) - -const ( - errCodeBadRequest = "bad_request" - errCodeInvalid = "invalid_error" -) - -var ( - // errDecodeData represents an error - // that decode data was failed. - errDecodeData = errors.New("decode_error", "decode error") - - // errInvalidAcknowledgment represents an error - // that an acknowledgment was invalidated. - errInvalidAcknowledgment = errors.New(errCodeInvalid, "invalid acknowledgment") - - // errInvalidConsumer represents an error - // that consumer was invalidated. - errInvalidConsumer = errors.New(errCodeInvalid, "invalid consumer") - - // errInvalidDataUsage represents an error - // that a data usage was invalidated. - errInvalidDataUsage = errors.New(errCodeInvalid, "invalid data usage") - - // errInvalidProvider represents an error - // that provider was invalidated. - errInvalidProvider = errors.New(errCodeInvalid, "invalid provider") - - // errInvalidProviderTerms represents an error - // that provider terms was invalidated. - errInvalidProviderTerms = errors.New(errCodeInvalid, "invalid provider terms") -) diff --git a/zmagmacore/magmasc/interfaces.go b/zmagmacore/magmasc/interfaces.go deleted file mode 100644 index 092130274..000000000 --- a/zmagmacore/magmasc/interfaces.go +++ /dev/null @@ -1,51 +0,0 @@ -package magmasc - -// ExternalID represents simple getter for ExtID. -func (m *Consumer) ExternalID() string { - return m.ExtID -} - -// FetchNodeRP returns name of magma sc rest point used for fetching consumer's node info. -func (m *Consumer) FetchNodeRP() string { - return ConsumerFetchRP -} - -// IsNodeRegisteredRP returns name of magma sc rest point used for checking consumer's node registration. -func (m *Consumer) IsNodeRegisteredRP() string { - return ConsumerRegisteredRP -} - -// RegistrationFuncName returns name of magma sc function used for consumer's node registration. -func (m *Consumer) RegistrationFuncName() string { - return ConsumerRegisterFuncName -} - -// UpdateNodeFuncName returns name of magma sc function used for consumer's node updating. -func (m *Consumer) UpdateNodeFuncName() string { - return ConsumerUpdateFuncName -} - -// ExternalID represents simple getter for ExtID. -func (m *Provider) ExternalID() string { - return m.ExtID -} - -// FetchNodeRP returns name of magma sc rest point used for fetching provider's node info. -func (m *Provider) FetchNodeRP() string { - return ProviderFetchRP -} - -// IsNodeRegisteredRP returns name of magma sc rest point used for checking provider's node registration. -func (m *Provider) IsNodeRegisteredRP() string { - return ProviderRegisteredRP -} - -// RegistrationFuncName returns name of magma sc function used for provider's node registration. -func (m *Provider) RegistrationFuncName() string { - return ProviderRegisterFuncName -} - -// UpdateNodeFuncName returns name of magma sc function used for provider's node updating. -func (m *Provider) UpdateNodeFuncName() string { - return ProviderUpdateFuncName -} diff --git a/zmagmacore/magmasc/mocks_test.go b/zmagmacore/magmasc/mocks_test.go deleted file mode 100644 index b9939beb0..000000000 --- a/zmagmacore/magmasc/mocks_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package magmasc - -import ( - "encoding/hex" - "time" - - magma "github.com/magma/augmented-networks/accounting/protos" - "golang.org/x/crypto/sha3" - - ts "github.com/0chain/gosdk/zmagmacore/time" -) - -func mockAcknowledgment() *Acknowledgment { - now := time.Now().Format(time.RFC3339Nano) - billing := mockBilling() - - return &Acknowledgment{ - SessionID: billing.DataUsage.SessionID, - AccessPointID: "id:access:point:" + now, - Billing: billing, - Consumer: mockConsumer(), - Provider: mockProvider(), - } -} - -func mockBilling() Billing { - return Billing{ - DataUsage: mockDataUsage(), - } -} - -func mockConsumer() *Consumer { - now := time.Now().Format(time.RFC3339Nano) - return &Consumer{ - ID: "id:consumer:" + now, - ExtID: "id:consumer:external:" + now, - Host: "localhost:8010", - } -} - -func mockDataUsage() DataUsage { - now := time.Now().Format(time.RFC3339Nano) - return DataUsage{ - DownloadBytes: 3 * million, - UploadBytes: 2 * million, - SessionID: "id:session:" + now, - SessionTime: 1 * 60, // 1 minute - } -} - -func mockProvider() *Provider { - now := time.Now().Format(time.RFC3339Nano) - return &Provider{ - ID: "id:provider:" + now, - ExtID: "id:provider:external:" + now, - Host: "localhost:8020", - MinStake: billion, - } -} - -func mockProviderTerms() ProviderTerms { - return ProviderTerms{ - AccessPointID: "id:access:point" + time.Now().Format(time.RFC3339Nano), - Price: 0.1, - PriceAutoUpdate: 0.001, - MinCost: 0.5, - Volume: 0, - QoS: mockQoS(), - QoSAutoUpdate: &QoSAutoUpdate{ - DownloadMbps: 0.001, - UploadMbps: 0.001, - }, - ProlongDuration: 1 * 60 * 60, // 1 hour - ExpiredAt: ts.Now() + (1 * 60 * 60), // 1 hour from now - } -} - -func mockTokenPool() *TokenPool { - now := time.Now().Format(time.RFC3339Nano) - return &TokenPool{ - ID: "id:session:" + now, - Balance: 1000, - HolderID: "id:holder:" + now, - PayerID: "id:payer:" + now, - PayeeID: "id:payee:" + now, - Transfers: []TokenPoolTransfer{ - mockTokenPoolTransfer(), - mockTokenPoolTransfer(), - mockTokenPoolTransfer(), - }, - } -} - -func mockTokenPoolTransfer() TokenPoolTransfer { - now := time.Now() - bin, _ := time.Now().MarshalBinary() - hash := sha3.Sum256(bin) - fix := now.Format(time.RFC3339Nano) - - return TokenPoolTransfer{ - TxnHash: hex.EncodeToString(hash[:]), - FromPool: "id:from:pool:" + fix, - ToPool: "id:to:pool:" + fix, - Value: 1111, - FromClient: "id:from:client:" + fix, - ToClient: "id:to:client:" + fix, - } -} - -func mockQoS() *magma.QoS { - return &magma.QoS{ - DownloadMbps: 5.4321, - UploadMbps: 1.2345, - } -} diff --git a/zmagmacore/magmasc/provider.go b/zmagmacore/magmasc/provider.go deleted file mode 100644 index 16adc1066..000000000 --- a/zmagmacore/magmasc/provider.go +++ /dev/null @@ -1,81 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/config" - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/node" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // Provider represents providers node stored in blockchain. - Provider struct { - ID string `json:"id"` - ExtID string `json:"ext_id"` - Host string `json:"host,omitempty"` - MinStake int64 `json:"min_stake,omitempty"` - } -) - -var ( - // Make sure Provider implements Serializable interface. - _ util.Serializable = (*Provider)(nil) -) - -// NewProviderFromCfg creates Provider from config.Provider. -func NewProviderFromCfg(cfg *config.Provider) *Provider { - return &Provider{ - ID: node.ID(), - ExtID: cfg.ExtID, - Host: cfg.Host, - MinStake: cfg.MinStake, - } -} - -// Decode implements util.Serializable interface. -func (m *Provider) Decode(blob []byte) error { - var provider Provider - if err := json.Unmarshal(blob, &provider); err != nil { - return errDecodeData.Wrap(err) - } - if err := provider.Validate(); err != nil { - return err - } - - m.ID = provider.ID - m.ExtID = provider.ExtID - m.Host = provider.Host - m.MinStake = provider.MinStake - - return nil -} - -// Encode implements util.Serializable interface. -func (m *Provider) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} - -// GetType returns Provider's type. -func (m *Provider) GetType() string { - return providerType -} - -// Validate checks Provider for correctness. -// If it is not return errInvalidProvider. -func (m *Provider) Validate() (err error) { - switch { // is invalid - case m.ExtID == "": - err = errors.New(errCodeBadRequest, "provider external id is required") - - case m.Host == "": - err = errors.New(errCodeBadRequest, "provider host is required") - - default: - return nil // is valid - } - - return errInvalidProvider.Wrap(err) -} diff --git a/zmagmacore/magmasc/provider_terms.go b/zmagmacore/magmasc/provider_terms.go deleted file mode 100644 index edf647092..000000000 --- a/zmagmacore/magmasc/provider_terms.go +++ /dev/null @@ -1,200 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - magma "github.com/magma/augmented-networks/accounting/protos" - - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/time" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // ProviderTerms represents a provider and service terms. - ProviderTerms struct { - AccessPointID string `json:"apid"` // access point id - Price float32 `json:"price"` // tokens per Megabyte - PriceAutoUpdate float32 `json:"price_auto_update,omitempty"` // price change on auto update - MinCost float32 `json:"min_cost"` // minimal cost for a session - Volume int64 `json:"volume"` // bytes per a session - QoS *magma.QoS `json:"qos"` // quality of service guarantee - QoSAutoUpdate *QoSAutoUpdate `json:"qos_auto_update,omitempty"` // qos change on auto update - ProlongDuration time.Duration `json:"prolong_duration,omitempty"` // duration in seconds to prolong the terms - ExpiredAt time.Timestamp `json:"expired_at,omitempty"` // timestamp till a session valid - } - - // QoSAutoUpdate represents data of qos terms on auto update. - QoSAutoUpdate struct { - DownloadMbps float32 `json:"download_mbps"` - UploadMbps float32 `json:"upload_mbps"` - } -) - -var ( - // Make sure ProviderTerms implements Serializable interface. - _ util.Serializable = (*ProviderTerms)(nil) -) - -// NewProviderTerms returns a new constructed provider terms. -func NewProviderTerms() *ProviderTerms { - return &ProviderTerms{QoS: &magma.QoS{}} -} - -// Decode implements util.Serializable interface. -func (m *ProviderTerms) Decode(blob []byte) error { - var terms ProviderTerms - if err := json.Unmarshal(blob, &terms); err != nil { - return errDecodeData.Wrap(err) - } - if err := terms.Validate(); err != nil { - return err - } - - m.AccessPointID = terms.AccessPointID - m.Price = terms.Price - m.PriceAutoUpdate = terms.PriceAutoUpdate - m.MinCost = terms.MinCost - m.Volume = terms.Volume - m.QoS.UploadMbps = terms.QoS.UploadMbps - m.QoS.DownloadMbps = terms.QoS.DownloadMbps - m.QoSAutoUpdate = terms.QoSAutoUpdate - m.ProlongDuration = terms.ProlongDuration - m.ExpiredAt = terms.ExpiredAt - - return nil -} - -// Decrease makes automatically Decrease provider terms by config. -func (m *ProviderTerms) Decrease() *ProviderTerms { - m.Volume = 0 // the volume of terms must be zeroed - - if m.ProlongDuration != 0 { - m.ExpiredAt += time.Timestamp(m.ProlongDuration) // prolong expire of terms - } - - if m.PriceAutoUpdate != 0 && m.Price > m.PriceAutoUpdate { - m.Price -= m.PriceAutoUpdate // down the price - } - - if m.QoSAutoUpdate != nil { - if m.QoSAutoUpdate.UploadMbps != 0 { - m.QoS.UploadMbps += m.QoSAutoUpdate.UploadMbps // up the qos of upload mbps - } - - if m.QoSAutoUpdate.DownloadMbps != 0 { - m.QoS.DownloadMbps += m.QoSAutoUpdate.DownloadMbps // up the qos of download mbps - } - } - - return m -} - -// Encode implements util.Serializable interface. -func (m *ProviderTerms) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} - -// Expired returns if terms already expired. -func (m *ProviderTerms) Expired() bool { - return m.ExpiredAt < time.Now()+TermsExpiredDuration -} - -// GetAmount returns calculated amount value of provider terms. -func (m *ProviderTerms) GetAmount() (amount uint64) { - price := m.GetPrice() - vol := m.GetVolume() - if vol > 0 { - amount = price * uint64(vol) - if minCost := m.GetMinCost(); amount < minCost { - amount = minCost - } - } - - return amount -} - -// GetMinCost returns calculated min cost value of provider terms. -func (m *ProviderTerms) GetMinCost() (cost uint64) { - if m.MinCost > 0 { - cost = uint64(m.MinCost * billion) - } - - return cost -} - -// GetPrice returns calculated price value of provider terms. -// NOTE: the price value will be represented in token units per megabyte. -func (m *ProviderTerms) GetPrice() (price uint64) { - if m.Price > 0 { - price = uint64(m.Price * billion) - } - - return price -} - -// GetVolume returns value of the provider terms volume. -// If the Volume is empty it will be calculated by the provider terms. -func (m *ProviderTerms) GetVolume() int64 { - if m.Volume == 0 { - mbps := (m.QoS.UploadMbps + m.QoS.DownloadMbps) / octet // megabytes per second - duration := float32(m.ExpiredAt - time.Now()) // duration in seconds - // rounded of bytes per second multiplied by duration in seconds - m.Volume = int64(mbps * duration) - } - - return m.Volume -} - -// Increase makes automatically Increase provider terms by config. -func (m *ProviderTerms) Increase() *ProviderTerms { - m.Volume = 0 // the volume of terms must be zeroed - - if m.ProlongDuration != 0 { - m.ExpiredAt += time.Timestamp(m.ProlongDuration) // prolong expire of terms - } - - if m.PriceAutoUpdate != 0 { - m.Price += m.PriceAutoUpdate // up the price - } - - if m.QoSAutoUpdate != nil { - if m.QoSAutoUpdate.UploadMbps != 0 && m.QoS.UploadMbps > m.QoSAutoUpdate.UploadMbps { - m.QoS.UploadMbps -= m.QoSAutoUpdate.UploadMbps // down the qos of upload mbps - } - - if m.QoSAutoUpdate.DownloadMbps != 0 && m.QoS.DownloadMbps > m.QoSAutoUpdate.DownloadMbps { - m.QoS.DownloadMbps -= m.QoSAutoUpdate.DownloadMbps // down the qos of download mbps - } - } - - return m -} - -// Validate checks ProviderTerms for correctness. -// If it is not return errInvalidProviderTerms. -func (m *ProviderTerms) Validate() (err error) { - switch { // is invalid - case m.AccessPointID == "": - err = errors.New(errCodeBadRequest, "invalid access point id") - - case m.QoS == nil: - err = errors.New(errCodeBadRequest, "invalid terms qos") - - case m.QoS.UploadMbps <= 0: - err = errors.New(errCodeBadRequest, "invalid terms qos upload mbps") - - case m.QoS.DownloadMbps <= 0: - err = errors.New(errCodeBadRequest, "invalid terms qos download mbps") - - case m.Expired(): - now := time.NowTime().Add(TermsExpiredDuration).Format(time.RFC3339) - err = errors.New(errCodeBadRequest, "expired at must be after "+now) - - default: - return nil // is valid - } - - return errInvalidProviderTerms.Wrap(err) -} diff --git a/zmagmacore/magmasc/provider_test.go b/zmagmacore/magmasc/provider_test.go deleted file mode 100644 index c5c6ba7e3..000000000 --- a/zmagmacore/magmasc/provider_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" -) - -func Test_Provider_Decode(t *testing.T) { - t.Parallel() - - prov := mockProvider() - blob, err := json.Marshal(prov) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - provInvalid := mockProvider() - provInvalid.ExtID = "" - extIDBlobInvalid, err := json.Marshal(provInvalid) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [3]struct { - name string - blob []byte - want *Provider - error bool - }{ - { - name: "OK", - blob: blob, - want: prov, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: &Provider{}, - error: true, - }, - { - name: "Ext_ID_Invalid_ERR", - blob: extIDBlobInvalid, - want: &Provider{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := &Provider{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, test.error) - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Provider_Encode(t *testing.T) { - t.Parallel() - - prov := mockProvider() - blob, err := json.Marshal(prov) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - prov *Provider - want []byte - }{ - { - name: "OK", - prov: prov, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.prov.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_Provider_GetType(t *testing.T) { - t.Parallel() - - t.Run("OK", func(t *testing.T) { - t.Parallel() - - prov := Provider{} - if got := prov.GetType(); got != providerType { - t.Errorf("GetType() got: %v | want: %v", got, providerType) - } - }) -} - -func Test_Provider_Validate(t *testing.T) { - t.Parallel() - - provEmptyExtID := mockProvider() - provEmptyExtID.ExtID = "" - - provEmptyHost := mockProvider() - provEmptyHost.Host = "" - - tests := [3]struct { - name string - prov *Provider - error bool - }{ - { - name: "OK", - prov: mockProvider(), - error: false, - }, - { - name: "Empty_Ext_ID_ERR", - prov: provEmptyExtID, - error: true, - }, - { - name: "Empty_Host_ERR", - prov: provEmptyHost, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if err := test.prov.Validate(); (err != nil) != test.error { - t.Errorf("validate() error: %v | want: %v", err, test.error) - } - }) - } -} diff --git a/zmagmacore/magmasc/tokenpool.go b/zmagmacore/magmasc/tokenpool.go deleted file mode 100644 index 5f64ab0b6..000000000 --- a/zmagmacore/magmasc/tokenpool.go +++ /dev/null @@ -1,47 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // TokenPool represents token pool implementation. - TokenPool struct { - ID string `json:"id"` - Balance int64 `json:"balance"` - HolderID string `json:"holder_id"` - PayerID string `json:"payer_id"` - PayeeID string `json:"payee_id"` - Transfers []TokenPoolTransfer `json:"transfers,omitempty"` - } -) - -var ( - // Make sure tokenPool implements Serializable interface. - _ util.Serializable = (*TokenPool)(nil) -) - -// Decode implements util.Serializable interface. -func (m *TokenPool) Decode(blob []byte) error { - var pool TokenPool - if err := json.Unmarshal(blob, &pool); err != nil { - return errDecodeData.Wrap(err) - } - - m.ID = pool.ID - m.Balance = pool.Balance - m.HolderID = pool.HolderID - m.PayerID = pool.PayerID - m.PayeeID = pool.PayeeID - m.Transfers = pool.Transfers - - return nil -} - -// Encode implements util.Serializable interface. -func (m *TokenPool) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} diff --git a/zmagmacore/magmasc/tokenpool_configurator.go b/zmagmacore/magmasc/tokenpool_configurator.go deleted file mode 100644 index e793327ac..000000000 --- a/zmagmacore/magmasc/tokenpool_configurator.go +++ /dev/null @@ -1,21 +0,0 @@ -package magmasc - -type ( - // PoolConfigurator represents a pool config interface. - PoolConfigurator interface { - // PoolBalance returns the amount value of token pool. - PoolBalance() uint64 - - // PoolID returns the token pool ID. - PoolID() string - - // PoolHolderID returns the token pool holder ID. - PoolHolderID() string - - // PoolPayerID returns the token pool payer ID. - PoolPayerID() string - - // PoolPayeeID returns the token pool payee ID. - PoolPayeeID() string - } -) diff --git a/zmagmacore/magmasc/tokenpool_test.go b/zmagmacore/magmasc/tokenpool_test.go deleted file mode 100644 index e525de6ea..000000000 --- a/zmagmacore/magmasc/tokenpool_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" -) - -func Test_tokenPool_Decode(t *testing.T) { - t.Parallel() - - pool := mockTokenPool() - blob, err := json.Marshal(pool) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [2]struct { - name string - blob []byte - want *TokenPool - error bool - }{ - { - name: "OK", - blob: blob, - want: pool, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: &TokenPool{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := &TokenPool{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, test.error) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_tokenPool_Encode(t *testing.T) { - t.Parallel() - - pool := mockTokenPool() - blob, err := json.Marshal(pool) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - pool *TokenPool - want []byte - }{ - { - name: "OK", - pool: pool, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.pool.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} diff --git a/zmagmacore/magmasc/tokenpool_transfer.go b/zmagmacore/magmasc/tokenpool_transfer.go deleted file mode 100644 index e75aeffe8..000000000 --- a/zmagmacore/magmasc/tokenpool_transfer.go +++ /dev/null @@ -1,35 +0,0 @@ -package magmasc - -import ( - "encoding/json" - - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // TokenPoolTransfer stores info about token transfers from pool to pool. - TokenPoolTransfer struct { - TxnHash string `json:"txn_hash,omitempty"` - FromPool string `json:"from_pool,omitempty"` - ToPool string `json:"to_pool,omitempty"` - Value int64 `json:"value,omitempty"` - FromClient string `json:"from_client,omitempty"` - ToClient string `json:"to_client,omitempty"` - } -) - -var ( - // Make sure TokenPoolTransfer implements Serializable interface. - _ util.Serializable = (*TokenPoolTransfer)(nil) -) - -// Decode implements util.Serializable interface. -func (m *TokenPoolTransfer) Decode(blob []byte) error { - return json.Unmarshal(blob, m) -} - -// Encode implements util.Serializable interface. -func (m *TokenPoolTransfer) Encode() []byte { - blob, _ := json.Marshal(m) - return blob -} diff --git a/zmagmacore/magmasc/tokenpool_transfer_test.go b/zmagmacore/magmasc/tokenpool_transfer_test.go deleted file mode 100644 index 2b4d4bcbe..000000000 --- a/zmagmacore/magmasc/tokenpool_transfer_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package magmasc - -import ( - "encoding/json" - "reflect" - "testing" -) - -func Test_TokenPoolTransfer_Decode(t *testing.T) { - t.Parallel() - - resp := mockTokenPoolTransfer() - blob, err := json.Marshal(resp) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [2]struct { - name string - blob []byte - want TokenPoolTransfer - error bool - }{ - { - name: "OK", - blob: blob, - want: resp, - error: false, - }, - { - name: "Decode_ERR", - blob: []byte(":"), // invalid json - want: TokenPoolTransfer{}, - error: true, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - got := TokenPoolTransfer{} - if err := got.Decode(test.blob); (err != nil) != test.error { - t.Errorf("Decode() error: %v | want: %v", err, test.error) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Decode() got: %#v | want: %#v", got, test.want) - } - }) - } -} - -func Test_TokenPoolTransfer_Encode(t *testing.T) { - t.Parallel() - - resp := mockTokenPoolTransfer() - blob, err := json.Marshal(resp) - if err != nil { - t.Fatalf("json.Marshal() error: %v | want: %v", err, nil) - } - - tests := [1]struct { - name string - resp TokenPoolTransfer - want []byte - }{ - { - name: "OK", - resp: resp, - want: blob, - }, - } - - for idx := range tests { - test := tests[idx] - t.Run(test.name, func(t *testing.T) { - t.Parallel() - - if got := test.resp.Encode(); !reflect.DeepEqual(got, test.want) { - t.Errorf("Encode() got: %#v | want: %#v", got, test.want) - } - }) - } -} diff --git a/zmagmacore/node/self.go b/zmagmacore/node/self.go deleted file mode 100644 index 563523484..000000000 --- a/zmagmacore/node/self.go +++ /dev/null @@ -1,80 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package node - -import ( - "net/url" - "strconv" - "time" - - "github.com/0chain/gosdk/zmagmacore/wallet" -) - -// Node represent self node type. -type Node struct { - url string - wallet *wallet.Wallet - extID string - startTime time.Time -} - -var ( - self = &Node{} -) - -// Start writes to self node current time, sets wallet, external id and url -// -// Start should be used only once while application is starting. -func Start(host string, port int, extID string, wallet *wallet.Wallet) { - self = &Node{ - url: makeHostURL(host, port), - wallet: wallet, - extID: extID, - startTime: time.Now(), - } -} - -func makeHostURL(host string, port int) string { - if host == "" { - host = "localhost" - } - - uri := url.URL{ - Scheme: "http", - Host: host + ":" + strconv.Itoa(port), - } - - return uri.String() -} - -// GetWalletString returns marshaled to JSON string nodes wallet. -func GetWalletString() (string, error) { - return self.wallet.StringJSON() -} - -func SetWallet(wall *wallet.Wallet) { - self.wallet = wall -} - -// ID returns id of Node. -func ID() string { - return self.wallet.ID() -} - -func ExtID() string { - return self.extID -} - -// PublicKey returns id of Node. -func PublicKey() string { - return self.wallet.PublicKey() -} - -// PrivateKey returns id of Node. -func PrivateKey() string { - return self.wallet.PrivateKey() -} - -// StartTime returns time when Node is started. -func StartTime() time.Time { - return self.startTime -} diff --git a/zmagmacore/registration/node.go b/zmagmacore/registration/node.go deleted file mode 100644 index 3e239dc8a..000000000 --- a/zmagmacore/registration/node.go +++ /dev/null @@ -1,119 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package registration - -import ( - "context" - "encoding/json" - "time" - - "go.uber.org/zap" - - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/http" - "github.com/0chain/gosdk/zmagmacore/log" - "github.com/0chain/gosdk/zmagmacore/magmasc" - "github.com/0chain/gosdk/zmagmacore/transaction" - "github.com/0chain/gosdk_common/core/sys" -) - -// RegisterOrUpdateWithRetries registers bandwidth-marketplace Node in blockchain -// if node is not registered or updates if is with retries. -// -// If an error occurs during execution, the program terminates with code 2 and the last error will be written in os.Stderr. -// -// RegisterOrUpdateWithRetries should be used only once while application is starting. -func RegisterOrUpdateWithRetries(ctx context.Context, bmNode Node, numTries int) { - var ( - executeSC executeSmartContract - ) - - registered, err := isNodeRegistered(bmNode) - if err != nil { - errors.ExitErr("err while checking nodes registration", err, 2) - } - if registered { - executeSC = update - log.Logger.Debug("Node is already registered in the blockchain, trying to update ...") - } else { - executeSC = register - log.Logger.Debug("Node is not registered in the Blockchain, trying to start registration ...") - } - - var ( - txnOutput string - ) - for ind := 0; ind < numTries; ind++ { - txnOutput, err = executeSC(ctx, bmNode) - if err != nil { - log.Logger.Debug("Executing smart contract failed. Sleep for 1 seconds ...", - zap.String("err", err.Error()), - ) - sys.Sleep(time.Second) - continue - } - - log.Logger.Info("Node is registered in the blockchain", zap.Any("txn_output", txnOutput)) - break - } - - if err != nil { - errors.ExitErr("error while registering", err, 2) - } -} - -func isNodeRegistered(bmNode Node) (bool, error) { - params := map[string]string{ - "ext_id": bmNode.ExternalID(), - } - registeredByt, err := http.MakeSCRestAPICall(magmasc.Address, bmNode.IsNodeRegisteredRP(), params) - if err != nil { - return false, err - } - - var registered bool - if err := json.Unmarshal(registeredByt, ®istered); err != nil { - return false, err - } - - return registered, nil -} - -func register(ctx context.Context, bmNode Node) (txnOutput string, err error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return "", err - } - - input := bmNode.Encode() - hash, err := txn.ExecuteSmartContract(ctx, magmasc.Address, bmNode.RegistrationFuncName(), string(input), 0) - if err != nil { - return "", err - } - - txn, err = transaction.VerifyTransaction(ctx, hash) - if err != nil { - return "", err - } - - return txn.TransactionOutput, nil -} - -func update(ctx context.Context, bmNode Node) (txnOutput string, err error) { - txn, err := transaction.NewTransactionEntity() - if err != nil { - return "", err - } - - input := bmNode.Encode() - hash, err := txn.ExecuteSmartContract(ctx, magmasc.Address, bmNode.UpdateNodeFuncName(), string(input), 0) - if err != nil { - return "", err - } - - txn, err = transaction.VerifyTransaction(ctx, hash) - if err != nil { - return "", err - } - - return txn.TransactionOutput, nil -} diff --git a/zmagmacore/registration/types.go b/zmagmacore/registration/types.go deleted file mode 100644 index af36ea592..000000000 --- a/zmagmacore/registration/types.go +++ /dev/null @@ -1,38 +0,0 @@ -package registration - -import ( - "context" - - "github.com/0chain/gosdk/zmagmacore/magmasc" -) - -type ( - // Node represent bandwidth-marketplace node that can be registered. - Node interface { - // RegistrationFuncName returns name of magma sc function used for registration Node. - RegistrationFuncName() string - - // UpdateNodeFuncName returns name of magma sc function used for updating Node. - UpdateNodeFuncName() string - - // IsNodeRegisteredRP returns name of magma sc relative path for checking registration of Node. - IsNodeRegisteredRP() string - - // ExternalID returns external ID of Node - ExternalID() string - - // Encode encodes Node in json bytes. - Encode() []byte - } - - // executeSmartContract represent types for functions that executes sc functions. - executeSmartContract func(ctx context.Context, node Node) (string, error) -) - -var ( - // Ensure Consumer implements interface. - _ Node = (*magmasc.Consumer)(nil) - - // Ensure Provider implements interface. - _ Node = (*magmasc.Provider)(nil) -) diff --git a/zmagmacore/shutdown/shutdown.go b/zmagmacore/shutdown/shutdown.go deleted file mode 100644 index 34837d8ad..000000000 --- a/zmagmacore/shutdown/shutdown.go +++ /dev/null @@ -1,55 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package shutdown - -import ( - "context" - "net/http" - "os" - "os/signal" - "syscall" - "time" - - "go.uber.org/zap" - "google.golang.org/grpc" - - "github.com/0chain/gosdk/zmagmacore/log" -) - -type ( - // Closable represents interface for types that might be closed. - Closable interface { - Close() error - } -) - -// Handle handles various shutdown signals. -func Handle(ctx context.Context, server *http.Server, grpcServer *grpc.Server, closable ...Closable) { - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM) - - // wait for signals or app context done - select { - case <-ctx.Done(): - case <-c: - } - shutdown(server, grpcServer, closable...) -} - -func shutdown(server *http.Server, grpcServer *grpc.Server, closable ...Closable) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := server.Shutdown(ctx); err != nil { - log.Logger.Warn("Server failed to gracefully shuts down", zap.Error(err)) - } - log.Logger.Debug("Server is shut down.") - - grpcServer.GracefulStop() - log.Logger.Debug("GRPC server is shut down.") - - log.Logger.Debug("Closing rest ...") - for _, cl := range closable { - if err := cl.Close(); err != nil { - log.Logger.Warn("Can not close.", zap.String("err", err.Error())) - } - } -} diff --git a/zmagmacore/storage/interface.go b/zmagmacore/storage/interface.go deleted file mode 100644 index 0a1b86aca..000000000 --- a/zmagmacore/storage/interface.go +++ /dev/null @@ -1,126 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package storage - -import ( - "sync" - - "github.com/dgraph-io/badger/v3" - - "github.com/0chain/gosdk/zmagmacore/errors" -) - -type ( - // Storage represents the main storage based on badger.DB. - Storage struct { - db *badger.DB - - singleton sync.Once // used for opening connection only once - } - - // Value represent value that can be stored as encoded bytes. - Value interface { - Encode() []byte - } -) - -var ( - // storageInst represents singleton storage. - storageInst = &Storage{} -) - -// Open opens singleton connection to storage. -// -// If an error occurs during execution, the program terminates with code 2 and the error will be written in os.Stderr. -// -// Should be used only once while application is starting. -func Open(path string) { - storageInst.singleton.Do(func() { - opts := badger.DefaultOptions(path) - opts.Logger = nil - - db, err := badger.Open(opts) - if err != nil { - errors.ExitErr("error while opening storage: %v", err, 2) - } - - storageInst.db = db - }) -} - -// GetStorage returns current storage implementation. -func GetStorage() *Storage { - return storageInst -} - -// Del deletes entry by the key. -func (s *Storage) Del(key []byte) error { - return s.db.Update(func(txn *badger.Txn) error { - return txn.Delete(key) - }) -} - -// Get retrieves entry by the key. -func (s *Storage) Get(key []byte) (value []byte, err error) { - err = s.db.View(func(txn *badger.Txn) error { - var item *badger.Item - item, err = txn.Get(key) - if err != nil { - return err - } - - return item.Value(func(val []byte) error { - value = val - return nil - }) - }) - - return -} - -// Set sets encoded Value with provided key. -func (s *Storage) Set(key []byte, value Value) error { - return s.db.Update(func(txn *badger.Txn) error { - blob := value.Encode() - return txn.Set(key, blob) - }) -} - -// SetWithRetries sets encoded Value with provided key with retries. -func (s *Storage) SetWithRetries(key []byte, value Value, numRetries int) error { - var err error - for i := 0; i < numRetries; i++ { - if err = s.Set(key, value); err != nil { - continue - } - break - } - - return err -} - -// Iterate iterates all elements with provided prefix and processes it with the handler. -func (s *Storage) Iterate(handler func(item *badger.Item) error, prefix []byte) error { - return s.db.View(func(txn *badger.Txn) error { - it := txn.NewIterator(badger.DefaultIteratorOptions) - defer it.Close() - - for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() { - if err := handler(it.Item()); err != nil { - return err - } - } - return nil - }) -} - -// NewTransaction creates new badger.Txn. -// -// For read-only transactions set update flag to false. -func (s *Storage) NewTransaction(update bool) *badger.Txn { - return s.db.NewTransaction(update) -} - -// Close closes a DB. -func (s *Storage) Close() error { - return s.db.Close() -} diff --git a/zmagmacore/time/time.go b/zmagmacore/time/time.go deleted file mode 100644 index 3478d5314..000000000 --- a/zmagmacore/time/time.go +++ /dev/null @@ -1,35 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package time - -import ( - "time" -) - -const ( - // RFC3339 is useful for formatting time. - RFC3339 = "2006-01-02T15:04:05Z07:00" -) - -type ( - // A Duration represents the elapsed time between two instants - // as an int64 nanosecond count. The representation limits the - // largest representable duration to approximately 290 years. - Duration = time.Duration - - // Time is a copy of time from golang std lib - // to avoid import it from other packages. - Time = time.Time - - // Timestamp represents a wrapper to control the json encoding. - Timestamp int64 -) - -// Now returns current Unix time. -func Now() Timestamp { - return Timestamp(time.Now().Unix()) -} - -// NowTime returns the current local time. -func NowTime() Time { - return time.Now() -} diff --git a/zmagmacore/transaction/callback.go b/zmagmacore/transaction/callback.go deleted file mode 100644 index c8b7356a8..000000000 --- a/zmagmacore/transaction/callback.go +++ /dev/null @@ -1,96 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package transaction - -import ( - "context" - - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk/zmagmacore/errors" -) - -type ( - // callback implements zcncore.TransactionCallback interface. - callback struct { - // waitCh represents channel for making callback.OnTransactionComplete, - // callback.OnVerifyComplete and callBack.OnAuthComplete operations async. - waitCh chan interface{} - - err error - } -) - -var ( - // Ensure callback implements interface. - _ zcncore.TransactionCallback = (*callback)(nil) -) - -func newCallBack() *callback { - return &callback{ - waitCh: make(chan interface{}), - } -} - -// OnTransactionComplete implements zcncore.TransactionCallback interface. -func (cb *callback) OnTransactionComplete(zcnTxn *zcncore.Transaction, status int) { - if status != zcncore.StatusSuccess { - msg := "status is not success: " + TxnStatus(status).String() + "; err: " + zcnTxn.GetTransactionError() - cb.err = errors.New("on_transaction_complete", msg) - } - - cb.sendCall() -} - -func (cb *callback) waitCompleteCall(ctx context.Context) error { - select { - case <-ctx.Done(): - return errors.New("completing_transaction", "completing transaction context deadline exceeded") - - case <-cb.waitCh: - return cb.err - } -} - -// OnVerifyComplete implements zcncore.TransactionCallback interface. -func (cb *callback) OnVerifyComplete(zcnTxn *zcncore.Transaction, status int) { - if status != zcncore.StatusSuccess { - msg := "status is not success: " + TxnStatus(status).String() + "; err: " + zcnTxn.GetVerifyError() - cb.err = errors.New("on_transaction_verify", msg) - } - - cb.sendCall() -} - -func (cb *callback) waitVerifyCall(ctx context.Context) error { - select { - case <-ctx.Done(): - return errors.New("verifying_transaction", "verifying transaction context deadline exceeded") - - case <-cb.waitCh: - return cb.err - } -} - -// OnAuthComplete implements zcncore.TransactionCallback interface. -func (cb *callback) OnAuthComplete(zcnTxn *zcncore.Transaction, status int) { - if status != zcncore.StatusSuccess { - msg := "status is not success: " + TxnStatus(status).String() - cb.err = errors.New("on_transaction_verify", msg) - } - - cb.sendCall() -} - -//nolint:unused -func (cb *callback) waitAuthCall(ctx context.Context) error { - select { - case <-ctx.Done(): - return errors.New("auth_transaction", "authenticating transaction context deadline exceeded") - - case <-cb.waitCh: - return cb.err - } -} - -func (cb *callback) sendCall() { - cb.waitCh <- true -} diff --git a/zmagmacore/transaction/const.go b/zmagmacore/transaction/const.go deleted file mode 100644 index 3ad2971c2..000000000 --- a/zmagmacore/transaction/const.go +++ /dev/null @@ -1,62 +0,0 @@ -package transaction - -type ( - // TxnStatus represented zcncore.TransactionCallback operations statuses. - TxnStatus int -) - -const ( - // StatusSuccess represent zcncore.StatusSuccess. - StatusSuccess TxnStatus = iota - // StatusNetworkError represent zcncore.StatusNetworkError. - StatusNetworkError - // StatusError represent zcncore.StatusError. - StatusError - // StatusRejectedByUser represent zcncore.StatusRejectedByUser. - StatusRejectedByUser - // StatusInvalidSignature represent zcncore.StatusInvalidSignature. - StatusInvalidSignature - // StatusAuthError represent zcncore.StatusAuthError. - StatusAuthError - // StatusAuthVerifyFailed represent zcncore.StatusAuthVerifyFailed. - StatusAuthVerifyFailed - // StatusAuthTimeout represent zcncore.StatusAuthTimeout. - StatusAuthTimeout - // StatusUnknown represent zcncore.StatusUnknown. - StatusUnknown = -1 -) - -// String returns represented in string format TxnStatus. -func (ts TxnStatus) String() string { - switch ts { - case StatusSuccess: - return "success" - - case StatusNetworkError: - return "network error" - - case StatusError: - return "error" - - case StatusRejectedByUser: - return "rejected byt user" - - case StatusInvalidSignature: - return "invalid signature" - - case StatusAuthError: - return "auth error" - - case StatusAuthVerifyFailed: - return "auth verify error" - - case StatusAuthTimeout: - return "auth timeout error" - - case StatusUnknown: - return "unknown" - - default: - return "" - } -} diff --git a/zmagmacore/transaction/http.go b/zmagmacore/transaction/http.go deleted file mode 100644 index afe75d2ba..000000000 --- a/zmagmacore/transaction/http.go +++ /dev/null @@ -1,22 +0,0 @@ -package transaction - -import ( - "context" -) - -// VerifyTransaction verifies including in blockchain transaction with provided hash. -// -// If execution completed with no error, returns Transaction with provided hash. -func VerifyTransaction(ctx context.Context, txnHash string) (*Transaction, error) { - txn, err := NewTransactionEntity() - if err != nil { - return nil, err - } - - txn.Hash = txnHash - err = txn.Verify(ctx) - if err != nil { - return nil, err - } - return txn, nil -} diff --git a/zmagmacore/transaction/txn.go b/zmagmacore/transaction/txn.go deleted file mode 100644 index 9750c4b10..000000000 --- a/zmagmacore/transaction/txn.go +++ /dev/null @@ -1,140 +0,0 @@ -package transaction - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk/zmagmacore/chain" - "github.com/0chain/gosdk/zmagmacore/errors" - "github.com/0chain/gosdk/zmagmacore/node" - ctime "github.com/0chain/gosdk/zmagmacore/time" - "github.com/0chain/gosdk_common/core/util" -) - -type ( - // Transaction entity that encapsulates the transaction related data and metadata. - Transaction struct { - Hash string `json:"hash,omitempty"` - Version string `json:"version,omitempty"` - ClientID string `json:"client_id,omitempty"` - PublicKey string `json:"public_key,omitempty"` - ToClientID string `json:"to_client_id,omitempty"` - ChainID string `json:"chain_id,omitempty"` - TransactionData string `json:"transaction_data,omitempty"` - Value int64 `json:"transaction_value,omitempty"` - Signature string `json:"signature,omitempty"` - CreationDate ctime.Timestamp `json:"creation_date,omitempty"` - TransactionType int `json:"transaction_type,omitempty"` - TransactionOutput string `json:"transaction_output,omitempty"` - OutputHash string `json:"txn_output_hash"` - - scheme zcncore.TransactionScheme - - callBack *callback - } -) - -// NewTransactionEntity creates Transaction with initialized fields. -// Sets version, client ID, creation date, public key and creates internal zcncore.TransactionScheme. -func NewTransactionEntity() (*Transaction, error) { - txn := &Transaction{ - Version: "1.0", - ClientID: node.ID(), - CreationDate: ctime.Now(), - ChainID: chain.GetServerChain().ID, - PublicKey: node.PublicKey(), - callBack: newCallBack(), - } - zcntxn, err := zcncore.NewTransaction(txn.callBack, 0, 0) - if err != nil { - return nil, err - } - txn.scheme = zcntxn - - return txn, nil -} - -// ExecuteSmartContract executes function of smart contract with provided address. -// -// Returns hash of executed transaction. -func (t *Transaction) ExecuteSmartContract(ctx context.Context, address, funcName, input string, - val uint64) (string, error) { - const errCode = "transaction_send" - - _, err := t.scheme.ExecuteSmartContract(address, funcName, input, val) - if err != nil { - msg := fmt.Sprintf("error while sending txn: %v", err) - return "", errors.New(errCode, msg) - } - - if err := t.callBack.waitCompleteCall(ctx); err != nil { - msg := fmt.Sprintf("error while sending txn: %v", err) - return "", errors.New(errCode, msg) - } - - t.Hash = t.scheme.GetTransactionHash() - if len(t.scheme.GetTransactionError()) > 0 { - return "", errors.New(errCode, t.scheme.GetTransactionError()) - } - - return t.Hash, nil -} - -type ( - verifyOutput struct { - Confirmation confirmation `json:"confirmation"` - } - - // confirmation represents the acceptance that a transaction is included into the blockchain. - confirmation struct { - Version string `json:"version"` - Hash string `json:"hash"` - BlockHash string `json:"block_hash"` - PreviousBlockHash string `json:"previous_block_hash"` - Transaction *Transaction `json:"txn,omitempty"` - CreationDate ctime.Timestamp `json:"creation_date"` - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - Status int `json:"transaction_status"` - RoundRandomSeed int64 `json:"round_random_seed"` - MerkleTreeRoot string `json:"merkle_tree_root"` - MerkleTreePath *util.MTPath `json:"merkle_tree_path"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` - } -) - -// Verify checks including of transaction in the blockchain. -func (t *Transaction) Verify(ctx context.Context) error { - const errCode = "transaction_verify" - - if err := t.scheme.SetTransactionHash(t.Hash); err != nil { - return err - } - - err := t.scheme.Verify() - if err != nil { - msg := fmt.Sprintf("error while verifying txn: %v; txn hash: %s", err, t.scheme.GetTransactionHash()) - return errors.New(errCode, msg) - } - - if err := t.callBack.waitVerifyCall(ctx); err != nil { - msg := fmt.Sprintf("error while verifying txn: %v; txn hash: %s", err, t.scheme.GetTransactionHash()) - return errors.New(errCode, msg) - } - - vo := new(verifyOutput) - if err := json.Unmarshal([]byte(t.scheme.GetVerifyOutput()), vo); err != nil { - return errors.New(errCode, "error while unmarshalling confirmation: "+err.Error()+", json: "+t.scheme.GetVerifyOutput()) - } - - if vo.Confirmation.Transaction != nil { - t.TransactionOutput = vo.Confirmation.Transaction.TransactionOutput - } else { - return errors.New(errCode, "got invalid confirmation (missing transaction)") - } - - return nil -} diff --git a/zmagmacore/wallet/balance.go b/zmagmacore/wallet/balance.go deleted file mode 100644 index 1bd1c7165..000000000 --- a/zmagmacore/wallet/balance.go +++ /dev/null @@ -1,52 +0,0 @@ -// DEPRECATED: This package is deprecated and will be removed in a future release. -package wallet - -import ( - "context" - - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk/zmagmacore/errors" -) - -type ( - // getBalanceCallBack implements zcncore.GetBalanceCallback interface. - getBalanceCallBack struct { - balanceCh chan int64 - err error - } -) - -// Balance responds balance of the wallet that used. -// -// NOTE: for using Balance you must set wallet info by running zcncore.SetWalletInfo. -func Balance(ctx context.Context) (int64, error) { - cb := newGetBalanceCallBack() - err := zcncore.GetBalance(cb) - if err != nil { - return 0, err - } - - var b int64 - select { - case <-ctx.Done(): - return 0, errors.New("get_balance", "context done is called") - case b = <-cb.balanceCh: - return b, cb.err - } -} - -// newGetBalanceCallBack creates initialized getBalanceCallBack. -func newGetBalanceCallBack() *getBalanceCallBack { - return &getBalanceCallBack{ - balanceCh: make(chan int64), - } -} - -// OnBalanceAvailable implements zcncore.GetBalanceCallback interface. -func (b *getBalanceCallBack) OnBalanceAvailable(status int, value int64, _ string) { - if status != zcncore.StatusSuccess { - b.err = errors.New("get_balance", "failed respond balance") - } - - b.balanceCh <- value -} diff --git a/zmagmacore/wallet/callback.go b/zmagmacore/wallet/callback.go deleted file mode 100644 index 3f93bda21..000000000 --- a/zmagmacore/wallet/callback.go +++ /dev/null @@ -1,18 +0,0 @@ -package wallet - -import ( - "github.com/0chain/gosdk/zcncore" -) - -type ( - // walletCallback provides callback struct for operations with wallet. - walletCallback struct{} -) - -var ( - // Ensure walletCallback implements interface. - _ zcncore.WalletCallback = (*walletCallback)(nil) -) - -// OnWalletCreateComplete implements zcncore.WalletCallback interface. -func (wb *walletCallback) OnWalletCreateComplete(_ int, _ string, _ string) {} diff --git a/zmagmacore/wallet/setup.go b/zmagmacore/wallet/setup.go deleted file mode 100644 index 4cb105a2e..000000000 --- a/zmagmacore/wallet/setup.go +++ /dev/null @@ -1,37 +0,0 @@ -package wallet - -import ( - "github.com/0chain/gosdk/zcncore" - "github.com/0chain/gosdk_common/core/logger" -) - -// SetupZCNSDK runs zcncore.SetLogFile, zcncore.SetLogLevel and zcncore.InitZCNSDK using provided Config. -// -// If an error occurs during execution, the program terminates with code 2 and the error will be written in os.Stderr. -// -// SetupZCNSDK should be used only once while application is starting. -func SetupZCNSDK(cfg Config) error { - var logName = cfg.LogDir() + "/zsdk.log" - zcncore.SetLogFile(logName, false) - zcncore.SetLogLevel(logLevelFromStr(cfg.LogLvl())) - return zcncore.InitZCNSDK(cfg.BlockWorker(), cfg.SignatureScheme()) -} - -// logLevelFromStr converts string log level to gosdk logger level int value. -func logLevelFromStr(level string) int { - switch level { - case "none": - return logger.NONE - case "fatal": - return logger.FATAL - case "error": - return logger.ERROR - case "info": - return logger.INFO - case "debug": - return logger.DEBUG - - default: - return -1 - } -} diff --git a/zmagmacore/wallet/types.go b/zmagmacore/wallet/types.go deleted file mode 100644 index 3f893ba70..000000000 --- a/zmagmacore/wallet/types.go +++ /dev/null @@ -1,18 +0,0 @@ -package wallet - -type ( - // Config represents config interface used for setup wallet. - Config interface { - // LogDir returns directory to store logs. - LogDir() string - - // LogLvl returns level of logs. - LogLvl() string - - // BlockWorker returns address of dns server. - BlockWorker() string - - // SignatureScheme returns signature scheme. - SignatureScheme() string - } -) diff --git a/zmagmacore/wallet/wallet.go b/zmagmacore/wallet/wallet.go deleted file mode 100644 index 55c501c28..000000000 --- a/zmagmacore/wallet/wallet.go +++ /dev/null @@ -1,63 +0,0 @@ -package wallet - -import ( - "encoding/hex" - "encoding/json" - - "github.com/0chain/gosdk/zmagmacore/crypto" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -type ( - // Wallet represents a wallet that stores keys and additional info. - Wallet struct { - ZCNWallet *zcncrypto.Wallet - } -) - -// New creates initialized Wallet. -func New(publicKey, privateKey []byte) *Wallet { - var ( - publicKeyHex, privateKeyHex = hex.EncodeToString(publicKey), hex.EncodeToString(privateKey) - ) - return &Wallet{ - ZCNWallet: &zcncrypto.Wallet{ - ClientID: crypto.Hash(publicKey), - ClientKey: publicKeyHex, - Keys: []zcncrypto.KeyPair{ - { - PublicKey: publicKeyHex, - PrivateKey: privateKeyHex, - }, - }, - Version: zcncrypto.CryptoVersion, - }, - } -} - -// PublicKey returns the public key. -func (w *Wallet) PublicKey() string { - return w.ZCNWallet.Keys[0].PublicKey -} - -// PrivateKey returns the public key. -func (w *Wallet) PrivateKey() string { - return w.ZCNWallet.Keys[0].PrivateKey -} - -// ID returns the client id. -// -// NOTE: client id represents hex encoded SHA3-256 hash of the raw public key. -func (w *Wallet) ID() string { - return w.ZCNWallet.ClientID -} - -// StringJSON returns marshalled to JSON string Wallet.ZCNWallet. -func (w *Wallet) StringJSON() (string, error) { - byt, err := json.Marshal(w.ZCNWallet) - if err != nil { - return "", err - } - - return string(byt), err -} diff --git a/znft/keystore.go b/znft/keystore.go index 621adcac6..3e14a8984 100644 --- a/znft/keystore.go +++ b/znft/keystore.go @@ -5,7 +5,7 @@ import ( "os" "path" - hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" + hdw "github.com/0chain/gosdk_common/zcncore/ethhdwallet" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" From 8102de5df7d7e89c53f916424112bb9bb776271f Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 16 Jan 2025 18:18:28 +0530 Subject: [PATCH 065/107] refactor 2 --- zboxcore/blockchain/entity.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go index fdfed443f..b21b60845 100644 --- a/zboxcore/blockchain/entity.go +++ b/zboxcore/blockchain/entity.go @@ -7,10 +7,10 @@ import ( "sync" "sync/atomic" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/util" "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/node" ) var miners []string @@ -115,7 +115,7 @@ func PopulateNodes(nodesjson string) ([]string, error) { } var chain *ChainConfig -var Sharders *node.NodeHolder +var Sharders *client.NodeHolder func init() { chain = &ChainConfig{ @@ -198,7 +198,7 @@ func SetSharders(sharderArray []string) { if len(sharderArray) < consensus { consensus = len(sharderArray) } - Sharders = node.NewHolder(sharderArray, consensus) + Sharders = client.NewHolder(sharderArray, consensus) } func SetMiners(minerArray []string) { From d649bba559959a5933f700fcb8de7cccc53a6800 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 16 Jan 2025 21:09:45 +0530 Subject: [PATCH 066/107] wasm refactor --- wasmsdk/README.md | 2 +- wasmsdk/allocation.go | 42 +++++++++++------- wasmsdk/auth_txn.go | 6 +-- wasmsdk/blobber.go | 35 ++++++++++----- wasmsdk/bridge.go | 28 ++++++------ wasmsdk/cache.go | 4 +- wasmsdk/chunked_upload_progress_storer.go | 2 +- wasmsdk/common.go | 10 +---- wasmsdk/demo/index.html | 6 ++- wasmsdk/demo/main.go | 4 +- wasmsdk/demo/zcn.js | 9 ++-- wasmsdk/ethwallet.go | 5 +-- wasmsdk/player_file.go | 2 +- wasmsdk/player_stream.go | 6 +-- wasmsdk/proxy.go | 51 ++++++++++++---------- wasmsdk/sdk.go | 53 +++++++++++++++-------- wasmsdk/statusbar.go | 2 +- wasmsdk/tokenrate.go | 2 +- wasmsdk/wallet.go | 17 +++++--- wasmsdk/wallet_base.go | 2 +- wasmsdk/zbox.go | 2 +- wasmsdk/zcn.go | 8 ++-- 22 files changed, 169 insertions(+), 129 deletions(-) diff --git a/wasmsdk/README.md b/wasmsdk/README.md index 58365f118..c4b52b221 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -3,7 +3,7 @@ # wasmsdk ```go -import "github.com/0chain/gosdk_common/wasmsdk" +import "github.com/0chain/gosdk/wasmsdk" ``` ## Index diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 4093ba667..25aae7861 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -13,9 +13,9 @@ import ( "sync" "syscall/js" + "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) const TOKEN_UNIT int64 = 1e10 @@ -68,7 +68,7 @@ func getAllocationBlobbers(preferredBlobberURLs []string, return sdk.GetBlobberIds(preferredBlobberURLs) } - return sdk.GetAllocationBlobbers(dataShards, parityShards, size, isRestricted, sdk.PriceRange{ + return sdk.GetAllocationBlobbers(sdk.StorageV2, dataShards, parityShards, size, isRestricted, sdk.PriceRange{ Min: uint64(minReadPrice), Max: uint64(maxReadPrice), }, sdk.PriceRange{ @@ -88,7 +88,7 @@ func getAllocationBlobbers(preferredBlobberURLs []string, // - lock is the lock value to add to the allocation. // - blobberIds is the list of blobber ids. // - blobberAuthTickets is the list of blobber auth tickets in case of using restricted blobbers. -func createAllocation(datashards, parityshards int, size int64, +func createAllocation(datashards, parityshards int, size, authRoundExpiry int64, minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, lock int64, blobberIds, blobberAuthTickets []string, setThirdPartyExtendable, IsEnterprise, force bool) ( *transaction.Transaction, error) { @@ -108,8 +108,10 @@ func createAllocation(datashards, parityshards int, size int64, BlobberIds: blobberIds, ThirdPartyExtendable: setThirdPartyExtendable, IsEnterprise: IsEnterprise, + StorageVersion: sdk.StorageV2, BlobberAuthTickets: blobberAuthTickets, Force: force, + AuthRoundExpiry: authRoundExpiry, } sdkLogger.Info(options) @@ -160,14 +162,17 @@ func transferAllocation(allocationID, newOwnerId, newOwnerPublicKey string) erro func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, forbidupdate, forbidmove, forbidcopy, forbidrename bool) (string, error) { hash, _, err := sdk.UpdateAllocation( - 0, //size, + 0, //size, + 0, false, //extend, allocationID, // allocID, 0, //lock, "", //addBlobberId, "", //addBlobberAuthTicket "", //removeBlobberId, - false, //thirdPartyExtendable, + "", //owner, + "", //ownerSigninPublicKey + false, // thirdPartyExtendable &sdk.FileOptionsParameters{ ForbidUpload: sdk.FileOptionParam{Changed: forbidupload, Value: forbidupload}, ForbidDelete: sdk.FileOptionParam{Changed: forbiddelete, Value: forbiddelete}, @@ -176,6 +181,7 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for ForbidCopy: sdk.FileOptionParam{Changed: forbidcopy, Value: forbidcopy}, ForbidRename: sdk.FileOptionParam{Changed: forbidrename, Value: forbidrename}, }, + "", ) return hash, err @@ -188,14 +194,17 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for func freezeAllocation(allocationID string) (string, error) { hash, _, err := sdk.UpdateAllocation( - 0, //size, + 0, //size, + 0, false, //extend, allocationID, // allocID, 0, //lock, "", //addBlobberId, "", //addBlobberAuthTicket "", //removeBlobberId, - false, //thirdPartyExtendable, + "", //owner, + "", //ownerSigninPublicKey + false, // thirdPartyExtendable &sdk.FileOptionsParameters{ ForbidUpload: sdk.FileOptionParam{Changed: true, Value: true}, ForbidDelete: sdk.FileOptionParam{Changed: true, Value: true}, @@ -204,6 +213,7 @@ func freezeAllocation(allocationID string) (string, error) { ForbidCopy: sdk.FileOptionParam{Changed: true, Value: true}, ForbidRename: sdk.FileOptionParam{Changed: true, Value: true}, }, + "", ) if err == nil { @@ -238,10 +248,10 @@ func cancelAllocation(allocationID string) (string, error) { // - addBlobberAuthTicket: blobber auth ticket to add to the allocation, in case of restricted blobbers // - removeBlobberId: blobber ID to remove from the allocation func updateAllocationWithRepair(allocationID string, - size int64, + size, authRoundExpiry int64, extend bool, lock int64, - addBlobberId, addBlobberAuthTicket, removeBlobberId, callbackFuncName string) (string, error) { + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, updateAllocTicket, callbackFuncName string) (string, error) { sdk.SetWasm() allocationObj, err := sdk.GetAllocation(allocationID) if err != nil { @@ -258,7 +268,7 @@ func updateAllocationWithRepair(allocationID string, } } - alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, false, &sdk.FileOptionsParameters{}, statusBar) + alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, authRoundExpiry, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, false, &sdk.FileOptionsParameters{}, updateAllocTicket) if err != nil { return hash, err } @@ -292,10 +302,10 @@ func updateAllocationWithRepair(allocationID string, // - removeBlobberId: blobber ID to remove from the allocation // - setThirdPartyExtendable: third party extendable flag, if true, the allocation can be extended (in terms of size) by a non-owner client func updateAllocation(allocationID string, - size int64, extend bool, + size, authRoundExpiry int64, extend bool, lock int64, - addBlobberId, addBlobberAuthTicket, removeBlobberId string, setThirdPartyExtendable bool) (string, error) { - hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, setThirdPartyExtendable, &sdk.FileOptionsParameters{}) + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, setThirdPartyExtendable bool) (string, error) { + hash, _, err := sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, &sdk.FileOptionsParameters{}, "") if err == nil { clearAllocation(allocationID) @@ -406,8 +416,8 @@ func lockStakePool(providerType, tokens, fee uint64, providerID string) (string, // - providerType: provider type (1: miner, 2:sharder, 3:blobber, 4:validator, 5:authorizer) // - fee: transaction fees (in SAS) // - providerID: provider id -func unlockStakePool(providerType, fee uint64, providerID string) (int64, error) { - unstake, _, err := sdk.StakePoolUnlock(sdk.ProviderType(providerType), providerID, fee) +func unlockStakePool(providerType, fee uint64, providerID, clientID string) (int64, error) { + unstake, _, err := sdk.StakePoolUnlock(sdk.ProviderType(providerType), providerID, clientID, fee) return unstake, err } diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 42bac292a..cd34f925c 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,9 +7,9 @@ import ( "fmt" "syscall/js" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zcncore" ) type AuthCallbackFunc func(msg string) string diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 286313880..487e05457 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -15,19 +15,19 @@ import ( "syscall/js" "time" - "github.com/0chain/gosdk_common/constants" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/pathutil" - "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk/constants" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/pathutil" + "github.com/0chain/gosdk/core/sys" "github.com/hack-pad/safejs" + "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" + "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" ) @@ -479,7 +479,9 @@ func multiDownload(allocationID, jsonMultiDownloadOptions, authTicket, callbackF } var mf sys.File if option.DownloadToDisk { - terminateWorkersWithAllocation(alloc) + if option.SuggestedName != "" { + fileName = option.SuggestedName + } mf, err = jsbridge.NewFileWriter(fileName) if err != nil { PrintError(err.Error()) @@ -590,6 +592,7 @@ type MultiDownloadOption struct { RemoteFileName string `json:"remoteFileName"` //Required only for file download with auth ticket RemoteLookupHash string `json:"remoteLookupHash,omitempty"` //Required only for file download with auth ticket DownloadToDisk bool `json:"downloadToDisk"` + SuggestedName string `json:"suggestedName,omitempty"` //Suggested name for the file when downloading to disk, if empty will use base of remote path } // MultiOperation do copy, move, delete and createdir operation together @@ -1134,7 +1137,7 @@ func checkAllocStatus(allocationID string) (string, error) { if err != nil { return "", err } - if client.GetClientID() != alloc.Owner { + if client.Wallet().ClientID != alloc.Owner { return "", errors.New("client id does not match with the allocation owner") } status, blobberStatus, err := alloc.CheckAllocStatus() @@ -1249,6 +1252,14 @@ func cancelDownloadDirectory(remotePath string) { downloadDirLock.Unlock() } +func cancelDownloadBlocks(allocationID, remotePath string, start, end int64) error { + alloc, err := getAllocation(allocationID) + if err != nil { + return err + } + return alloc.CancelDownloadBlocks(remotePath, start, end) +} + func startListener(respChan chan string) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 45a14ba60..f0f655e12 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -4,18 +4,17 @@ import ( "context" "encoding/base64" "encoding/json" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/zcnbridge" + "github.com/0chain/gosdk/zcnbridge/errors" + "github.com/0chain/gosdk/zcnbridge/log" + "github.com/0chain/gosdk/zcncore" + "github.com/ethereum/go-ethereum/ethclient" "path" "strconv" - - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/zcnbridge" - "github.com/0chain/gosdk_common/zcnbridge/errors" - "github.com/0chain/gosdk_common/zcnbridge/log" - "github.com/0chain/gosdk_common/zcncore" - "github.com/ethereum/go-ethereum/ethclient" ) -var bridge *zcnbridge.BridgeClient +var bridge *zcnbridge.BridgeClient //nolint:unused // initBridge initializes the bridge client // - ethereumAddress: ethereum address of the wallet owner @@ -26,7 +25,7 @@ var bridge *zcnbridge.BridgeClient // - gasLimit: gas limit for the transactions // - value: value to be sent with the transaction (unused) // - consensusThreshold: consensus threshold for the transactions -func initBridge( +func initBridge( //nolint:unused ethereumAddress string, bridgeAddress string, authorizersAddress string, @@ -84,7 +83,9 @@ func burnZCN(amount uint64) string { //nolint // - burnTrxHash: hash of the burn transaction // - timeout: timeout in seconds func mintZCN(burnTrxHash string, timeout int) string { //nolint - mintPayload, err := bridge.QueryZChainMintPayload(burnTrxHash) + mintPayload, + + err := bridge.QueryZChainMintPayload(burnTrxHash) if err != nil { return errors.Wrap("mintZCN", "failed to QueryZChainMintPayload", err).Error() } @@ -114,19 +115,18 @@ func getMintWZCNPayload(burnTrxHash string) string { //nolint:unused } // getNotProcessedWZCNBurnEvents returns all not processed WZCN burn events from the Ethereum network -func getNotProcessedWZCNBurnEvents() string { +func getNotProcessedWZCNBurnEvents() string { //nolint:unused var ( mintNonce int64 res []byte err error ) - if res, err = zcncore.GetMintNonce(); err != nil { return errors.Wrap("getNotProcessedWZCNBurnEvents", "failed to retreive last ZCN processed mint nonce", err).Error() } if err = json.Unmarshal(res, &mintNonce); err != nil { - return errors.New("getNotProcessedWZCNBurnEvents", "failed to unmarshall last ZCN processed mint nonce").Error() + return errors.Wrap("getNotProcessedWZCNBurnEvents", "failed to unmarshal last ZCN processed mint nonce", err).Error() } log.Logger.Debug("MintNonce = " + strconv.Itoa(int(mintNonce))) @@ -162,7 +162,7 @@ func getNotProcessedZCNBurnTickets() string { //nolint:unused } if err = json.Unmarshal(res, &burnTickets); err != nil { - return errors.New("getNotProcessedZCNBurnTickets", "failed to unmarshall ZCN burn tickets").Error() + return errors.Wrap("getNotProcessedZCNBurnTickets", "failed to unmarshal ZCN burn tickets", err).Error() } var result []byte diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 9e0d8c9e1..9089015b3 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -8,9 +8,9 @@ import ( "errors" "time" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/wasmsdk/chunked_upload_progress_storer.go b/wasmsdk/chunked_upload_progress_storer.go index a3435b4ee..d839d5be0 100644 --- a/wasmsdk/chunked_upload_progress_storer.go +++ b/wasmsdk/chunked_upload_progress_storer.go @@ -7,7 +7,7 @@ import ( "sync" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" + "github.com/0chain/gosdk/zboxcore/zboxutil" ) // chunkedUploadProgressStorer load and save upload progress diff --git a/wasmsdk/common.go b/wasmsdk/common.go index a5f22744c..ba2bfe408 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -7,8 +7,8 @@ import ( "errors" "syscall/js" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) // PrintError is to print to stderr @@ -89,11 +89,3 @@ func (h *hasher) WriteToValidationMT(_ []byte) error { func (h *hasher) Finalize() error { return nil } - -func (h *hasher) GetBlockHash() (string, error) { - return "", nil -} - -func (h *hasher) WriteToBlockHasher(buf []byte) error { - return nil -} diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index b73e91cde..e6846532f 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -241,6 +241,8 @@

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

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

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates let stringifiedArray = JSON.stringify(objects); try { - const results = await goWasm.sdk.multiDownload('', stringifiedArray, 'eyJjbGllbnRfaWQiOiIiLCJvd25lcl9pZCI6IjI2ZTIzMjFhZWMxZmEyZDY1NGQ1MDQ5OWY3ZjhmYWJhNjNkYWMxYTExYTQwZDU3NDJkNDAzMWJmMzEzMzAxMTYiLCJhbGxvY2F0aW9uX2lkIjoiMDAwMzAzOTA1MGI3ZDdiM2FlNmI3MGEwZTVjMWU4ZjRhOTkxNzc1YWJiOTQ2NjljMDg4YzczNzJlMzYwMzkyYiIsImZpbGVfcGF0aF9oYXNoIjoiYWEzODE0NTM2ZWI2OWQwNjU4ZWM0OTgyZmE3ZTIwM2I2ZGI2ZWExYmU4ZmMxODRiMWJhOTZhMTk3NmMwM2JlOCIsImFjdHVhbF9maWxlX2hhc2giOiIxMjUwMjJhZGRiZTIwZDNhOWUzYjcxZTA0NjUzZjY3YiIsImZpbGVfbmFtZSI6InVidW50dS0yMi4wNC40LWxpdmUtc2VydmVyLWFtZDY0LmlzbyIsInJlZmVyZW5jZV90eXBlIjoiZiIsImV4cGlyYXRpb24iOjAsInRpbWVzdGFtcCI6MTcxNjM3ODIxNiwiZW5jcnlwdGVkIjpmYWxzZSwic2lnbmF0dXJlIjoiYmEzNzQ1NzlmZTczZDc1MWIwMTNiMjM2NjUzZDRiMGYyYzNjZDJlYTMyNTFkODg0MmRiNWQxNTlhNjBiN2ExMiJ9', '') + const results = await goWasm.sdk.multiDownload('', stringifiedArray, '', '') console.log(JSON.stringify(results)) } catch (e) { alert(e) diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 02c903934..64934403a 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,8 +7,8 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zcncore" "github.com/uptrace/bunrouter" ) diff --git a/wasmsdk/demo/zcn.js b/wasmsdk/demo/zcn.js index d64388d24..63585cfb9 100644 --- a/wasmsdk/demo/zcn.js +++ b/wasmsdk/demo/zcn.js @@ -308,7 +308,7 @@ async function createWasm() { (_, key) => (...args) => // eslint-disable-next-line - new Promise(async (resolve, reject) => { + new Promise(async (resolve, reject) => { if (!go || go.exited) { return reject(new Error('The Go instance is not active.')) } @@ -368,8 +368,11 @@ async function createWasm() { ) const proxy = { - bulkUpload: bulkUpload, - setWallet: setWallet, + bulkUpload, + setWallet, + getWalletId, + getPrivateKey, + getPeerPublicKey, sdk: sdkProxy, //expose sdk methods for js jsProxy, //expose js methods for go } diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index f5ad11610..bc2dbc40b 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -1,4 +1,3 @@ -//go:build js && wasm // +build js,wasm package main @@ -9,7 +8,7 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) // JS does not have int64 so we must take a string instead of int64. @@ -115,7 +114,7 @@ func TransferEthTokens(this js.Value, p []js.Value) interface{} { return promiseConstructor.New(handler) } -// Exports public functions in github.com/0chain/gosdk_common/zcncore/ethwallet.go +// Exports public functions in github.com/0chain/gosdk/zcncore/ethwallet.go func IsValidEthAddress(this js.Value, p []js.Value) interface{} { ethAddr := p[0].String() success, err := zcncore.IsValidEthAddress(ethAddr) diff --git a/wasmsdk/player_file.go b/wasmsdk/player_file.go index 7d847adb5..82de0d4c8 100644 --- a/wasmsdk/player_file.go +++ b/wasmsdk/player_file.go @@ -7,8 +7,8 @@ import ( "context" "fmt" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/zboxcore/marker" ) type FilePlayer struct { diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index fa81be29d..51c844e20 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,10 +11,10 @@ import ( "sync" "time" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zboxcore/marker" ) type StreamPlayer struct { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index ed8db6774..5ad947fd4 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -13,13 +13,13 @@ import ( "sync" "time" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/version" + "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/core/version" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" "github.com/hack-pad/safejs" @@ -59,18 +59,20 @@ func main() { if c == nil || len(c.Keys) == 0 { return "", errors.New("no keys found") } + pk := c.Keys[0].PrivateKey result, err := jsbridge.Await(jsSign.Invoke(hash, pk)) if len(err) > 0 && !err[0].IsNull() { return "", errors.New("sign: " + err[0].String()) } + return result[0].String(), nil } //update sign with js sign zcncrypto.Sign = signFunc - zcncore.SignFn = signFunc + client.SignFn = signFunc sys.Sign = func(hash, signatureScheme string, keys []sys.KeyPair) (string, error) { // js already has signatureScheme and keys return signFunc(hash) @@ -85,7 +87,7 @@ func main() { data, err := json.Marshal(zcncore.AuthMessage{ Hash: hash, Signature: sig, - ClientID: client.GetClient().ClientID, + ClientID: client.Wallet().ClientID, }) if err != nil { return "", err @@ -201,18 +203,20 @@ func main() { if !(sdk.IsNull() || sdk.IsUndefined()) { jsbridge.BindAsyncFuncs(sdk, map[string]interface{}{ //sdk - "init": initSDKs, - "setWallet": setWallet, - "getPublicEncryptionKey": zcncore.GetPublicEncryptionKey, - "hideLogs": hideLogs, - "showLogs": showLogs, - "getUSDRate": getUSDRate, - "isWalletID": isWalletID, - "getVersion": getVersion, - "getLookupHash": getLookupHash, - "createThumbnail": createThumbnail, - "makeSCRestAPICall": makeSCRestAPICall, - "getWasmType": getWasmType, + "init": initSDKs, + "setWallet": setWallet, + "setWalletMode": setWalletMode, + "getPublicEncryptionKey": zcncore.GetPublicEncryptionKey, + "getPublicEncryptionKeyV2": zcncore.GetPublicEncryptionKeyV2, + "hideLogs": hideLogs, + "showLogs": showLogs, + "getUSDRate": getUSDRate, + "isWalletID": isWalletID, + "getVersion": getVersion, + "getLookupHash": getLookupHash, + "createThumbnail": createThumbnail, + "makeSCRestAPICall": makeSCRestAPICall, + "wasmType": getWasmType, //blobber "delete": Delete, @@ -245,6 +249,7 @@ func main() { "getFileMetaByName": getFileMetaByName, "downloadDirectory": downloadDirectory, "cancelDownloadDirectory": cancelDownloadDirectory, + "cancelDownloadBlocks": cancelDownloadBlocks, // player "play": play, @@ -331,7 +336,7 @@ func main() { fmt.Println("__wasm_initialized__ = true;") zcn.Set("__wasm_initialized__", true) - zcn.Set("wasmType", "enterprise") + zcn.Set("wasmType", "normal") } else { PrintError("__zcn_wasm__.sdk is not installed yet") } @@ -342,7 +347,6 @@ func main() { } if mode != "" { - fmt.Println("enterprise wasm sdk") respChan := make(chan string, 1) jsProxy := window.Get("__zcn_worker_wasm__") if !(jsProxy.IsNull() || jsProxy.IsUndefined()) { @@ -353,6 +357,7 @@ func main() { if c == nil || len(c.Keys) == 0 { return "", errors.New("no keys found") } + pk := c.Keys[0].PrivateKey result, err := jsbridge.Await(jsSign.Invoke(hash, pk)) @@ -363,7 +368,7 @@ func main() { } //update sign with js sign zcncrypto.Sign = signFunc - zcncore.SignFn = signFunc + client.SignFn = signFunc sys.Sign = func(hash, signatureScheme string, keys []sys.KeyPair) (string, error) { // js already has signatureScheme and keys return signFunc(hash) diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index e00b46c5e..07f9974ad 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -7,15 +7,17 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io" - "os" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/imageutil" + "github.com/0chain/gosdk/core/logger" + "github.com/0chain/gosdk/core/screstapi" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/core/imageutil" - "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" + + "io" + "os" ) var CreateObjectURL func(buf []byte, mimeType string) string @@ -32,21 +34,34 @@ var CreateObjectURL func(buf []byte, mimeType string) string // - sharderconsensous is the number of sharders to reach consensus func initSDKs(chainID, blockWorker, signatureScheme string, minConfirmation, minSubmit, confirmationChainLength int, - zboxHost, zboxAppType string, sharderconsensous int) error { + zboxHost, zboxAppType string, sharderConsensous int) error { // Print the parameters beautified - fmt.Printf("{ chainID: %s, blockWorker: %s, signatureScheme: %s, minConfirmation: %d, minSubmit: %d, - confirmationChainLength: %d, zboxHost: %s, zboxAppType: %s, sharderConsensous: %d, isSplit: %t }\n", chainID, - blockWorker, signatureScheme, minConfirmation, minSubmit, - confirmationChainLength, zboxHost, zboxAppType, - sharderConsensous, isSplit) + fmt.Printf("{ chainID: %s, blockWorker: %s, signatureScheme: %s, minConfirmation: %d, minSubmit: %d, confirmationChainLength: %d, zboxHost: %s, zboxAppType: %s, sharderConsensous: %d }\n", chainID, blockWorker, signatureScheme, minConfirmation, minSubmit, confirmationChainLength, zboxHost, zboxAppType, sharderConsensous) + zboxApiClient.SetRequest(zboxHost, zboxAppType) - err := client.InitSDK("{}", blockWorker, chainID, signatureScheme, 0, false, false, minConfirmation, minSubmit, confirmationChainLength, sharderConsensous) + params := client.InitSdkOptions{ + WalletJSON: "{}", + BlockWorker: blockWorker, + ChainID: chainID, + SignatureScheme: signatureScheme, + Nonce: int64(0), + AddWallet: false, + MinConfirmation: &minConfirmation, + MinSubmit: &minSubmit, + SharderConsensous: &sharderConsensous, + ConfirmationChainLength: &confirmationChainLength, + ZboxHost: zboxHost, + ZboxAppType: zboxAppType, + } + + err := client.InitSDKWithWebApp(params) if err != nil { fmt.Println("wasm: InitStorageSDK ", err) return err } + sdk.SetWasm() return nil } @@ -57,7 +72,7 @@ func getVersion() string { } func getWasmType() string { - return "enterprise" + return "normal" } var sdkLogger *logger.Logger @@ -118,6 +133,7 @@ func getLookupHash(allocationID string, path string) string { // createThumbnail create thumbnail of an image buffer. It supports // - png + // - jpeg // - gif // - bmp @@ -146,7 +162,7 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro if err != nil { sdkLogger.Error(fmt.Sprintf("Error parsing JSON: %v", err)) } - b, err := client.MakeSCRestAPICall(scAddress, relativePath, params) + b, err := screstapi.MakeSCRestAPICall(scAddress, relativePath, params) return string(b), err } @@ -156,10 +172,9 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro // - fee is the transaction fee // - desc is the description of the transaction func send(toClientID string, tokens uint64, fee uint64, desc string) (string, error) { - hash, _, _, _, err := zcncore.Send(toClientID, tokens, desc) + _, _, _, txn, err := zcncore.Send(toClientID, tokens, desc) if err != nil { return "", err } - - return hash, nil + return txn.TransactionOutput, nil } diff --git a/wasmsdk/statusbar.go b/wasmsdk/statusbar.go index 000cc20fc..526e2e4f7 100644 --- a/wasmsdk/statusbar.go +++ b/wasmsdk/statusbar.go @@ -7,8 +7,8 @@ import ( "path" "sync" + "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/core/sys" "gopkg.in/cheggaaa/pb.v1" ) diff --git a/wasmsdk/tokenrate.go b/wasmsdk/tokenrate.go index 456206331..dd5897657 100644 --- a/wasmsdk/tokenrate.go +++ b/wasmsdk/tokenrate.go @@ -3,7 +3,7 @@ package main import ( "context" - "github.com/0chain/gosdk_common/core/tokenrate" + "github.com/0chain/gosdk/core/tokenrate" ) // getUSDRate gets the USD rate for the given crypto symbol diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index c3f0ef305..278a0913f 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -10,9 +10,9 @@ import ( "os" "strconv" - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk/core/client" + "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk/wasmsdk/jsbridge" ) func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error { @@ -36,11 +36,10 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon Keys: keys, IsSplit: isSplit, } - client.SetWallet(*w) - fmt.Println("set Wallet, is split:", isSplit) + client.SetWallet(*w) - zboxApiClient.SetWallet(clientID, privateKey, publicKey) + zboxApiClient.SetWallet(clientID, privateKey, clientKey) if mode == "" { // main thread, need to notify the web worker to update wallet // notify the web worker to update wallet if err := jsbridge.PostMessageToAllWorkers(jsbridge.MsgTypeUpdateWallet, map[string]string{ @@ -58,3 +57,9 @@ func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemon return nil } + +func setWalletMode(mode bool) { + client.SetWalletMode(mode) + + fmt.Println("gosdk setWalletMode: ", "is split:", mode) +} diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index eb30044d7..3f7e1be44 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -1,7 +1,7 @@ package main import ( - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) // Split keys from the primary master key diff --git a/wasmsdk/zbox.go b/wasmsdk/zbox.go index 880f5811e..1d4497eb7 100644 --- a/wasmsdk/zbox.go +++ b/wasmsdk/zbox.go @@ -7,7 +7,7 @@ import ( "context" "errors" - "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk/zboxapi" ) var ( diff --git a/wasmsdk/zcn.go b/wasmsdk/zcn.go index 17dfe788e..f0272e4b5 100644 --- a/wasmsdk/zcn.go +++ b/wasmsdk/zcn.go @@ -4,8 +4,8 @@ package main import ( - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/screstapi" + "github.com/0chain/gosdk/zcncore" ) type Balance struct { @@ -17,12 +17,10 @@ type Balance struct { // getWalletBalance retrieves the wallet balance of the client from the network. // - clientId is the client id func getWalletBalance(clientId string) (*Balance, error) { - - bal, err := client.GetBalance(clientId) + bal, err := screstapi.GetBalance(clientId) if err != nil { return nil, err } - balance, err := bal.ToToken() if err != nil { return nil, err From b59dcf44b8e80f47f5ab61cce1f5e791178aeb80 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 16 Jan 2025 21:20:02 +0530 Subject: [PATCH 067/107] refactor 2 --- README.md | 4 ++-- wasmsdk/allocation.go | 4 ++-- wasmsdk/auth_txn.go | 4 ++-- wasmsdk/blobber.go | 14 +++++++------- wasmsdk/cache.go | 4 ++-- wasmsdk/common.go | 2 +- wasmsdk/player_stream.go | 4 ++-- wasmsdk/proxy.go | 10 +++++----- wasmsdk/wallet.go | 6 +++--- 9 files changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 8bbe1af8f..b866a3ad6 100644 --- a/README.md +++ b/README.md @@ -177,9 +177,9 @@ To run all the unit tests in `gosdk`: `go test github.com/0chain/gosdk/zboxcore/ $ go test ./... ``` -To run all the unit tests in `bls0chain_test.go`, run this command from $TOP: `go test github.com/0chain/gosdk/core/zcncrypto -v` +To run all the unit tests in `bls0chain_test.go`, run this command from $TOP: `go test github.com/0chain/gosdk_common/core/zcncrypto -v` -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 a specific unit test in `bls0chain_test.go`, such as `TestSignatureScheme`, run: `go test github.com/0chain/gosdk_common/core/zcncrypto -v -run TestSignatureScheme` To run the coverage test in `gosdk`: diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 25aae7861..9787d8a32 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -13,9 +13,9 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) const TOKEN_UNIT int64 = 1e10 diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index cd34f925c..7138d51f3 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,9 +7,9 @@ import ( "fmt" "syscall/js" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) type AuthCallbackFunc func(msg string) string diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 487e05457..bcaa67368 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -16,18 +16,18 @@ import ( "time" "github.com/0chain/gosdk/constants" - "github.com/0chain/gosdk/core/client" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/pathutil" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/sys" "github.com/hack-pad/safejs" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/hack-pad/go-webworkers/worker" ) diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 9089015b3..9e0d8c9e1 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -8,9 +8,9 @@ import ( "errors" "time" - "github.com/0chain/gosdk/core/client" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/wasmsdk/common.go b/wasmsdk/common.go index ba2bfe408..64008c620 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -7,8 +7,8 @@ import ( "errors" "syscall/js" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) // PrintError is to print to stderr diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index 51c844e20..bce670691 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,10 +11,10 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) type StreamPlayer struct { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 5ad947fd4..caef87573 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -13,13 +13,13 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/client" - "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/version" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/version" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/hack-pad/safejs" diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index 278a0913f..edbaaf52f 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -10,9 +10,9 @@ import ( "os" "strconv" - "github.com/0chain/gosdk/core/client" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error { From fcca97e1d86cd137565c1d8753721f8148125062 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 00:18:53 +0530 Subject: [PATCH 068/107] refactor 3 --- go.mod | 2 +- go.sum | 4 + mobilesdk/zbox/models.go | 2 +- mobilesdk/zbox/storage.go | 2 +- mobilesdk/zbox/streaming.go | 2 +- wasmsdk/auth_txn.go | 2 +- wasmsdk/blobber.go | 4 +- wasmsdk/bridge.go | 13 ++- wasmsdk/chunked_upload_progress_storer.go | 2 +- wasmsdk/demo/main.go | 4 +- wasmsdk/ethwallet.go | 3 +- wasmsdk/player_file.go | 2 +- wasmsdk/player_stream.go | 2 +- wasmsdk/proxy.go | 2 +- wasmsdk/sdk.go | 12 +- wasmsdk/statusbar.go | 2 +- wasmsdk/tokenrate.go | 2 +- wasmsdk/wallet_base.go | 2 +- wasmsdk/zbox.go | 2 +- wasmsdk/zcn.go | 4 +- zboxcore/sdk/allocation.go | 27 +++-- zboxcore/sdk/blobber_operations.go | 33 ++---- zboxcore/sdk/chunked_upload.go | 2 +- zboxcore/sdk/chunked_upload_blobber.go | 2 +- zboxcore/sdk/chunked_upload_model.go | 2 +- zboxcore/sdk/commitworker.go | 2 +- zboxcore/sdk/copyworker.go | 2 +- zboxcore/sdk/deleteworker.go | 4 +- zboxcore/sdk/dirworker.go | 2 +- zboxcore/sdk/moveworker.go | 2 +- zboxcore/sdk/multi_operation_worker.go | 3 +- zboxcore/sdk/networkworker.go | 4 +- zboxcore/sdk/renameworker.go | 2 +- zboxcore/sdk/sdk.go | 48 ++++---- zboxcore/sdk/transaction.go | 130 ---------------------- zboxcore/sdk/upload_worker.go | 2 +- zboxcore/zboxutil/util.go | 2 +- 37 files changed, 107 insertions(+), 232 deletions(-) delete mode 100644 zboxcore/sdk/transaction.go diff --git a/go.mod b/go.mod index ebdc38d8c..49206cca3 100644 --- a/go.mod +++ b/go.mod @@ -44,7 +44,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606 + github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe github.com/hack-pad/go-webworkers v0.1.0 github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/minio/sha256-simd v1.0.1 diff --git a/go.sum b/go.sum index 87035ac38..64aea6774 100644 --- a/go.sum +++ b/go.sum @@ -48,6 +48,10 @@ github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd h1:zeLdGO7e5Ov github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd/go.mod h1:A6zAa6S8jWML2razteUYtk9aINjHW4u8MjFKITgIdp4= github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606 h1:/pEJYnH04BoG5UJsQ+k74F/rJOtehXOgMVbB44h1gAY= github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250116160841-eeec3c6a9fcd h1:LbZTG/mIwxmR1mcS5oNsDh0hsnrRLNt0u/6/mqg8V/A= +github.com/0chain/gosdk_common v0.0.0-20250116160841-eeec3c6a9fcd/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe h1:opO2O58fZh2Ca1rdHMNRCkSTys95AOnpCd3WUapgeFU= +github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/mobilesdk/zbox/models.go b/mobilesdk/zbox/models.go index 13f55e39f..d617a09fc 100644 --- a/mobilesdk/zbox/models.go +++ b/mobilesdk/zbox/models.go @@ -1,7 +1,7 @@ package zbox import ( - "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk_common/core/transaction" ) type StatusCallbackMocked interface { diff --git a/mobilesdk/zbox/storage.go b/mobilesdk/zbox/storage.go index bb8ca5028..fd3342342 100644 --- a/mobilesdk/zbox/storage.go +++ b/mobilesdk/zbox/storage.go @@ -6,10 +6,10 @@ import ( "strings" "time" - "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/constants" ) type fileResp struct { diff --git a/mobilesdk/zbox/streaming.go b/mobilesdk/zbox/streaming.go index eab889540..2eff586df 100644 --- a/mobilesdk/zbox/streaming.go +++ b/mobilesdk/zbox/streaming.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/0chain/gosdk/core/transaction" + "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk/zboxcore/sdk" ) diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 7138d51f3..42bac292a 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,9 +7,9 @@ import ( "fmt" "syscall/js" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zcncore" ) type AuthCallbackFunc func(msg string) string diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index bcaa67368..99c3b0280 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -15,7 +15,7 @@ import ( "syscall/js" "time" - "github.com/0chain/gosdk/constants" + "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/encryption" @@ -25,9 +25,9 @@ import ( "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" ) diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index f0f655e12..3e60bfa06 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -4,14 +4,15 @@ import ( "context" "encoding/base64" "encoding/json" - "github.com/0chain/gosdk/core/client" - "github.com/0chain/gosdk/zcnbridge" - "github.com/0chain/gosdk/zcnbridge/errors" - "github.com/0chain/gosdk/zcnbridge/log" - "github.com/0chain/gosdk/zcncore" - "github.com/ethereum/go-ethereum/ethclient" "path" "strconv" + + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/zcnbridge" + "github.com/0chain/gosdk_common/zcnbridge/errors" + "github.com/0chain/gosdk_common/zcnbridge/log" + "github.com/0chain/gosdk_common/zcncore" + "github.com/ethereum/go-ethereum/ethclient" ) var bridge *zcnbridge.BridgeClient //nolint:unused diff --git a/wasmsdk/chunked_upload_progress_storer.go b/wasmsdk/chunked_upload_progress_storer.go index d839d5be0..a3435b4ee 100644 --- a/wasmsdk/chunked_upload_progress_storer.go +++ b/wasmsdk/chunked_upload_progress_storer.go @@ -7,7 +7,7 @@ import ( "sync" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) // chunkedUploadProgressStorer load and save upload progress diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 64934403a..02c903934 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,8 +7,8 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zcncore" "github.com/uptrace/bunrouter" ) diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index bc2dbc40b..6a9b8e696 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -1,3 +1,4 @@ +//go:build js && wasm // +build js,wasm package main @@ -8,7 +9,7 @@ import ( "sync" "syscall/js" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // JS does not have int64 so we must take a string instead of int64. diff --git a/wasmsdk/player_file.go b/wasmsdk/player_file.go index 82de0d4c8..7d847adb5 100644 --- a/wasmsdk/player_file.go +++ b/wasmsdk/player_file.go @@ -7,8 +7,8 @@ import ( "context" "fmt" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type FilePlayer struct { diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index bce670691..fa81be29d 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,10 +11,10 @@ import ( "sync" "time" - "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zboxcore/marker" ) type StreamPlayer struct { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index caef87573..231d80954 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -14,12 +14,12 @@ import ( "time" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/wasmsdk/jsbridge" + "github.com/0chain/gosdk_common/zcncore" "github.com/hack-pad/safejs" diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 07f9974ad..94a760179 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -8,13 +8,13 @@ import ( "encoding/json" "fmt" - "github.com/0chain/gosdk/core/client" - "github.com/0chain/gosdk/core/encryption" - "github.com/0chain/gosdk/core/imageutil" - "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/screstapi" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/encryption" + "github.com/0chain/gosdk_common/core/imageutil" + "github.com/0chain/gosdk_common/core/logger" + "github.com/0chain/gosdk_common/core/screstapi" + "github.com/0chain/gosdk_common/zcncore" "io" "os" diff --git a/wasmsdk/statusbar.go b/wasmsdk/statusbar.go index 526e2e4f7..e42370e3b 100644 --- a/wasmsdk/statusbar.go +++ b/wasmsdk/statusbar.go @@ -7,7 +7,7 @@ import ( "path" "sync" - "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk/zboxcore/sdk" "gopkg.in/cheggaaa/pb.v1" ) diff --git a/wasmsdk/tokenrate.go b/wasmsdk/tokenrate.go index dd5897657..456206331 100644 --- a/wasmsdk/tokenrate.go +++ b/wasmsdk/tokenrate.go @@ -3,7 +3,7 @@ package main import ( "context" - "github.com/0chain/gosdk/core/tokenrate" + "github.com/0chain/gosdk_common/core/tokenrate" ) // getUSDRate gets the USD rate for the given crypto symbol diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index 3f7e1be44..eb30044d7 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -1,7 +1,7 @@ package main import ( - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) // Split keys from the primary master key diff --git a/wasmsdk/zbox.go b/wasmsdk/zbox.go index 1d4497eb7..880f5811e 100644 --- a/wasmsdk/zbox.go +++ b/wasmsdk/zbox.go @@ -7,7 +7,7 @@ import ( "context" "errors" - "github.com/0chain/gosdk/zboxapi" + "github.com/0chain/gosdk_common/zboxapi" ) var ( diff --git a/wasmsdk/zcn.go b/wasmsdk/zcn.go index f0272e4b5..259f1d907 100644 --- a/wasmsdk/zcn.go +++ b/wasmsdk/zcn.go @@ -4,8 +4,8 @@ package main import ( - "github.com/0chain/gosdk/core/screstapi" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/screstapi" + "github.com/0chain/gosdk_common/zcncore" ) type Balance struct { diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index f1fa9d8d0..90de34e8a 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -26,6 +26,7 @@ import ( thrown "github.com/0chain/errors" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/pathutil" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/zboxcore/blockchain" @@ -2421,6 +2422,16 @@ func (a *Allocation) CancelDownload(remotepath string) error { return errors.New("remote_path_not_found", "Invalid path. No download in progress for the path "+remotepath) } +func (a *Allocation) CancelDownloadBlocks(remotepath string, start, end int64) error { + hash := encryption.Hash(fmt.Sprintf("%s:%d:%d", remotepath, start, end)) + if downloadReq, ok := a.downloadProgressMap[hash]; ok { + downloadReq.isDownloadCanceled = true + downloadReq.ctxCncl() + return nil + } + 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( @@ -3102,14 +3113,14 @@ func (a *Allocation) SetConsensusThreshold() { // - fileOptionsParams: The file options parameters which control permissions of the files of the allocations. // - statusCB: A callback function to receive status updates during the update operation. func (a *Allocation) UpdateWithRepair( - size int64, + size, authRoundExpiry int64, extend bool, lock uint64, - addBlobberId, addBlobberAuthTicket, removeBlobberId string, - setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, + setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, updateAllocTicket string, statusCB StatusCallback, ) (string, error) { - updatedAlloc, hash, isRepairRequired, err := a.UpdateWithStatus(size, extend, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, setThirdPartyExtendable, fileOptionsParams, statusCB) + updatedAlloc, hash, isRepairRequired, err := a.UpdateWithStatus(size, authRoundExpiry, extend, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) if err != nil { return hash, err } @@ -3137,12 +3148,12 @@ func (a *Allocation) UpdateWithRepair( // // Returns the updated allocation, hash, and a boolean indicating whether repair is required. func (a *Allocation) UpdateWithStatus( - size int64, + size, authRoundExpiry int64, extend bool, lock uint64, - addBlobberId, addBlobberAuthTicket, removeBlobberId string, + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, - statusCB StatusCallback, + updateAllocTicket string, ) (*Allocation, string, bool, error) { var ( alloc *Allocation @@ -3153,7 +3164,7 @@ func (a *Allocation) UpdateWithStatus( } l.Logger.Info("Updating allocation") - hash, _, err := UpdateAllocation(size, extend, a.ID, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, setThirdPartyExtendable, fileOptionsParams) + hash, _, err := UpdateAllocation(size, authRoundExpiry, extend, a.ID, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) if err != nil { return alloc, "", isRepairRequired, err } diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index e1d158788..06ba48548 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "math" - "strings" "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/transaction" @@ -45,7 +44,7 @@ func CreateAllocationForOwner( return "", 0, nil, errors.New("allocation_validation_failed", "atleast 1 data and 1 parity shards are required") } - allocationRequest, err := getNewAllocationBlobbers( + allocationRequest, err := getNewAllocationBlobbers(StorageV2, datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds, blobberAuthTickets, force) if err != nil { return "", 0, nil, errors.New("failed_get_allocation_blobbers", "failed to get blobbers for allocation: "+err.Error()) @@ -115,12 +114,12 @@ func CreateFreeAllocation(marker string, value uint64) (string, int64, error) { // // returns the hash of the transaction, the nonce of the transaction and an error if any. func UpdateAllocation( - size int64, + size, authRoundExpiry int64, extend bool, allocationID string, lock uint64, - addBlobberId, addBlobberAuthTicket, removeBlobberId string, - setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, + addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerID, ownerSigninPublicKey string, + setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, ticket string, ) (hash string, nonce int64, err error) { if lock > math.MaxInt64 { @@ -225,7 +224,7 @@ func StakePoolLock(providerType ProviderType, providerID string, value, fee uint // - providerType: provider type // - providerID: provider ID // - fee: transaction fee -func StakePoolUnlock(providerType ProviderType, providerID string, fee uint64) (unstake int64, nonce int64, err error) { +func StakePoolUnlock(providerType ProviderType, providerID, clientID string, fee uint64) (unstake int64, nonce int64, err error) { if !sdkInitialized { return 0, 0, sdkNotInitialized } @@ -241,6 +240,7 @@ func StakePoolUnlock(providerType ProviderType, providerID string, fee uint64) ( spr := stakePoolRequest{ ProviderType: providerType, ProviderID: providerID, + ClientID: clientID, } var sn = transaction.SmartContractTxnData{ @@ -390,24 +390,7 @@ func storageSmartContractTxnValue(sn transaction.SmartContractTxnData, value uin func smartContractTxnValueFeeWithRetry(scAddress string, sn transaction.SmartContractTxnData, value, fee uint64) (hash, out string, nonce int64, t *transaction.Transaction, err error) { - hash, out, nonce, t, err = smartContractTxnValueFee(scAddress, sn, value, fee) - if err != nil && strings.Contains(err.Error(), "invalid transaction nonce") { - return smartContractTxnValueFee(scAddress, sn, value, fee) - } - return -} - -func smartContractTxnValueFee(scAddress string, sn transaction.SmartContractTxnData, - value, fee uint64) (hash, out string, nonce int64, t *transaction.Transaction, err error) { - t, err = ExecuteSmartContract(scAddress, sn, value, fee) - if err != nil { - if t != nil { - return "", "", t.TransactionNonce, nil, err - } - - return "", "", 0, nil, err - } - - return t.Hash, t.TransactionOutput, t.TransactionNonce, t, nil + // Fee is set during sdk initialization. + return transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, value, client.TxnFee(), true) } diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index ec3a7a14a..bd52e8b39 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -16,12 +16,12 @@ import ( "errors" thrown "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" coreEncryption "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/encryption" diff --git a/zboxcore/sdk/chunked_upload_blobber.go b/zboxcore/sdk/chunked_upload_blobber.go index 58430ff70..fb6f5e817 100644 --- a/zboxcore/sdk/chunked_upload_blobber.go +++ b/zboxcore/sdk/chunked_upload_blobber.go @@ -14,8 +14,8 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/constants" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index c03a54505..d1cfaa4bf 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -10,8 +10,8 @@ import ( "sync" "time" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/encryption" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index e5aff6a96..a882caca5 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -16,7 +16,7 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index e0dd398ac..3730fc906 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -22,7 +22,7 @@ import ( "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index fa9e07d22..bfe185b3d 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -16,9 +16,9 @@ import ( thrown "github.com/0chain/errors" "github.com/google/uuid" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" @@ -108,7 +108,7 @@ func (req *DeleteRequest) deleteBlobberFile( } if resp.StatusCode == http.StatusBadRequest { body, err := ioutil.ReadAll(resp.Body) - if err!= nil { + if err != nil { logger.Logger.Error("Failed to read response body", err) } diff --git a/zboxcore/sdk/dirworker.go b/zboxcore/sdk/dirworker.go index 3ea0c2dc3..32c4fcf9d 100644 --- a/zboxcore/sdk/dirworker.go +++ b/zboxcore/sdk/dirworker.go @@ -13,9 +13,9 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index efbdad4a9..03bba421c 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -21,7 +21,7 @@ import ( "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 2d2f6c19a..ab77e7e84 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -13,8 +13,8 @@ import ( "github.com/0chain/errors" "github.com/remeh/sizedwaitgroup" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -26,6 +26,7 @@ import ( const ( DefaultCreateConnectionTimeOut = 45 * time.Second + StorageV2 = 1 ) var BatchSize = 6 diff --git a/zboxcore/sdk/networkworker.go b/zboxcore/sdk/networkworker.go index 0cd8359e6..6fec75c52 100644 --- a/zboxcore/sdk/networkworker.go +++ b/zboxcore/sdk/networkworker.go @@ -9,7 +9,7 @@ import ( "strconv" "time" - "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/client" l "github.com/0chain/gosdk_common/zboxcore/logger" "go.uber.org/zap" @@ -73,7 +73,7 @@ func forceUpdateNetworkDetails(networkDetails *Network) { sdkInitialized = false blockchain.SetMiners(networkDetails.Miners) blockchain.SetSharders(networkDetails.Sharders) - node.InitCache(blockchain.Sharders) + client.InitCache(blockchain.Sharders) conf.InitChainNetwork(&conf.Network{ Sharders: networkDetails.Sharders, Miners: networkDetails.Miners, diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index 591a9bc2a..cbff56cd4 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -22,7 +22,7 @@ import ( "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index bba563756..bfcb241b6 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -14,7 +14,7 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/conf" "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/core/node" + "github.com/0chain/gosdk_common/core/screstapi" "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk_common/core/client" @@ -189,7 +189,7 @@ func SetMinConfirmation(num int) { func SetNetwork(miners []string, sharders []string) { blockchain.SetMiners(miners) blockchain.SetSharders(sharders) - node.InitCache(blockchain.Sharders) + client.InitCache(blockchain.Sharders) } // CreateReadPool creates a read pool for the SDK client. @@ -231,7 +231,7 @@ func GetReadPoolInfo(clientID string) (info *ReadPool, err error) { } var b []byte - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getReadPoolStat", + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getReadPoolStat", map[string]string{"client_id": clientID}) if err != nil { return nil, errors.Wrap(err, "error requesting read pool info") @@ -306,7 +306,7 @@ func GetStakePoolInfo(providerType ProviderType, providerID string) (info *Stake } var b []byte - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", map[string]string{"provider_type": strconv.Itoa(int(providerType)), "provider_id": providerID}) if err != nil { return nil, errors.Wrap(err, "error requesting stake pool info:") @@ -347,7 +347,7 @@ func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUs "offset": strconv.FormatInt(int64(offset), 10), "limit": strconv.FormatInt(int64(limit), 10), } - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getUserStakePoolStat", params) if err != nil { return nil, errors.Wrap(err, "error requesting stake pool user info:") @@ -367,6 +367,7 @@ func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUs type stakePoolRequest struct { ProviderType ProviderType `json:"provider_type,omitempty"` ProviderID string `json:"provider_id,omitempty"` + ClientID string `json:"client_id,omitempty"` } // stakePoolLock is stake pool unlock response in case where tokens @@ -399,7 +400,7 @@ func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { } var b []byte - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getChallengePoolStat", map[string]string{"allocation_id": allocID}) if err != nil { return nil, errors.Wrap(err, "error requesting challenge pool info:") @@ -423,7 +424,7 @@ func GetMptData(key string) ([]byte, error) { } var b []byte - b, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, + b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/get_mpt_key", map[string]string{"key": key}) if err != nil { return nil, errors.Wrap(err, "error requesting mpt key data:") @@ -450,7 +451,7 @@ func GetStorageSCConfig() (conf *InputMap, err error) { } var b []byte - b, err = client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/storage-config", nil) + b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/storage-config", nil) if err != nil { return nil, errors.Wrap(err, "error requesting storage SC configs:") } @@ -624,7 +625,7 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe offset, strconv.FormatBool(stakable), ) - b, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, url, nil) + b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, url, nil) var wrap nodes if err != nil { return nil, errors.Wrap(err, "error requesting blobbers:") @@ -682,7 +683,7 @@ func GetBlobber(blobberID string) (blob *Blobber, err error) { return nil, sdkNotInitialized } var b []byte - b, err = client.MakeSCRestAPICall( + b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/getBlobber", map[string]string{"blobber_id": blobberID}) @@ -706,7 +707,7 @@ func GetValidator(validatorID string) (validator *Validator, err error) { return nil, sdkNotInitialized } var b []byte - b, err = client.MakeSCRestAPICall( + b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/get_validator", map[string]string{"validator_id": validatorID}) @@ -730,7 +731,7 @@ func GetValidators(stakable bool) (validators []*Validator, err error) { return nil, sdkNotInitialized } var b []byte - b, err = client.MakeSCRestAPICall( + b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/validators", map[string]string{ @@ -793,7 +794,7 @@ func GetAllocation(allocationID string) (*Allocation, error) { } params := make(map[string]string) params["allocation"] = allocationID - allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) + allocationBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return nil, errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } @@ -825,7 +826,7 @@ func GetAllocationUpdates(allocation *Allocation) error { params := make(map[string]string) params["allocation"] = allocation.ID - allocationBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) + allocationBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) if err != nil { return errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } @@ -878,7 +879,7 @@ func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, params["client"] = clientID params["limit"] = fmt.Sprint(limit) params["offset"] = fmt.Sprint(offset) - allocationsBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocations", params) + allocationsBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocations", params) if err != nil { return nil, errors.New("allocations_fetch_error", "Error fetching the allocations."+err.Error()) } @@ -955,6 +956,8 @@ type CreateAllocationOptions struct { IsEnterprise bool FileOptionsParams *FileOptionsParameters Force bool + StorageVersion int + AuthRoundExpiry int64 } // CreateAllocationWith creates a new allocation with the given options for the current client using the SDK. @@ -982,7 +985,7 @@ func CreateAllocationWith(options CreateAllocationOptions) ( // // returns the list of blobber ids and an error if any. func GetAllocationBlobbers( - datashards, parityshards int, + storageVersion, datashards, parityshards int, size int64, isRestricted int, readPrice, writePrice PriceRange, @@ -995,6 +998,7 @@ func GetAllocationBlobbers( "read_price_range": readPrice, "write_price_range": writePrice, "is_restricted": isRestricted, + "storage_version": storageVersion, } allocationData, _ := json.Marshal(allocationRequest) @@ -1005,7 +1009,7 @@ func GetAllocationBlobbers( params["force"] = strconv.FormatBool(force[0]) } - allocBlobber, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params) + allocBlobber, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params) if err != nil { return nil, err } @@ -1020,7 +1024,7 @@ func GetAllocationBlobbers( } func getNewAllocationBlobbers( - datashards, parityshards int, + storageVersion, datashards, parityshards int, size int64, readPrice, writePrice PriceRange, preferredBlobberIds, blobberAuthTickets []string, force bool, @@ -1040,7 +1044,7 @@ func getNewAllocationBlobbers( } allocBlobberIDs, err := GetAllocationBlobbers( - datashards, parityshards, size, 2, readPrice, writePrice, force, + storageVersion, datashards, parityshards, size, 2, readPrice, writePrice, force, ) if err != nil { return nil, err @@ -1090,7 +1094,7 @@ func GetBlobberIds(blobberUrls []string) ([]string, error) { params := make(map[string]string) params["blobber_urls"] = string(urlsStr) - idsStr, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params) + idsStr, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params) if err != nil { return nil, err } @@ -1115,7 +1119,7 @@ func GetFreeAllocationBlobbers(request map[string]interface{}) ([]string, error) params := make(map[string]string) params["free_allocation_data"] = string(data) - allocBlobber, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params) + allocBlobber, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params) if err != nil { return nil, err } @@ -1512,7 +1516,7 @@ func GetUpdateAllocationMinLock( params := make(map[string]string) params["data"] = string(data) - responseBytes, err := client.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params) + responseBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params) if err != nil { return 0, errors.Wrap(err, "failed to request allocation update min lock") } diff --git a/zboxcore/sdk/transaction.go b/zboxcore/sdk/transaction.go deleted file mode 100644 index 93131c0dc..000000000 --- a/zboxcore/sdk/transaction.go +++ /dev/null @@ -1,130 +0,0 @@ -//go:build !mobile -// +build !mobile - -package sdk - -import ( - "fmt" - "sync" - - "errors" - - "github.com/0chain/gosdk_common/core/transaction" - l "github.com/0chain/gosdk_common/zboxcore/logger" - "github.com/0chain/gosdk_common/zcncore" -) - -type transactionCallback struct { - wg *sync.WaitGroup - success bool - errMsg string - - txn *zcncore.Transaction -} - -func (cb *transactionCallback) OnTransactionComplete(t *zcncore.Transaction, status int) { - defer cb.wg.Done() - cb.txn = t - if status == zcncore.StatusSuccess { - cb.success = true - } else { - cb.errMsg = t.GetTransactionError() - } -} - -func (cb *transactionCallback) OnVerifyComplete(t *zcncore.Transaction, status int) { - defer cb.wg.Done() - cb.txn = t - if status == zcncore.StatusSuccess { - cb.success = true - } else { - cb.errMsg = t.GetVerifyError() - } -} - -func (cb *transactionCallback) OnAuthComplete(t *zcncore.Transaction, status int) { - cb.txn = t - fmt.Println("Authorization complete on zauth.", status) -} - -// ExecuteSmartContract executes the smart contract -func ExecuteSmartContract(address string, sn transaction.SmartContractTxnData, value, fee uint64) (*transaction.Transaction, error) { - wg := &sync.WaitGroup{} - cb := &transactionCallback{wg: wg} - txn, err := zcncore.NewTransaction(cb, fee, 0) - if err != nil { - return nil, err - } - - wg.Add(1) - t, err := txn.ExecuteSmartContract(address, sn.Name, sn.InputArgs, value) - if err != nil { - return nil, err - } - - msg := fmt.Sprintf("Executing transaction '%s' with hash %s ", sn.Name, t.Hash) - l.Logger.Info(msg) - l.Logger.Info("estimated txn fee: ", t.TransactionFee) - - wg.Wait() - - if !cb.success { - return nil, fmt.Errorf("smartcontract: %s", cb.errMsg) - } - - cb.success = false - wg.Add(1) - err = txn.Verify() - if err != nil { - return nil, err - } - - wg.Wait() - - if !cb.success { - return nil, fmt.Errorf("smartcontract: %s", cb.errMsg) - } - - switch txn.GetVerifyConfirmationStatus() { - case zcncore.ChargeableError: - return t, errors.New(txn.GetVerifyOutput()) - case zcncore.Success: - return t, nil - } - - return nil, fmt.Errorf("smartcontract: %v", txn.GetVerifyConfirmationStatus()) -} - -// ExecuteSmartContractSend create send transaction to transfer tokens from the caller to target address -func ExecuteSmartContractSend(to string, tokens, fee uint64, desc string) (string, error) { - wg := &sync.WaitGroup{} - cb := &transactionCallback{wg: wg} - txn, err := zcncore.NewTransaction(cb, fee, 0) - if err != nil { - return "", err - } - - wg.Add(1) - err = txn.Send(to, tokens, desc) - if err == nil { - wg.Wait() - } else { - return "", err - } - - if cb.success { - cb.success = false - wg.Add(1) - err := txn.Verify() - if err == nil { - wg.Wait() - } else { - return "", err - } - if cb.success { - return txn.GetVerifyOutput(), nil - } - } - - return "", errors.New(cb.errMsg) -} diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index e76aa6dd8..947d117a1 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -7,9 +7,9 @@ import ( "io" "strings" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/fileref" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" diff --git a/zboxcore/zboxutil/util.go b/zboxcore/zboxutil/util.go index 966cc35d3..25ea986c9 100644 --- a/zboxcore/zboxutil/util.go +++ b/zboxcore/zboxutil/util.go @@ -19,7 +19,7 @@ import ( "errors" thrown "github.com/0chain/errors" - "github.com/0chain/gosdk_common/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/h2non/filetype" "github.com/hitenjain14/fasthttp" From f01b993290ddfff26d9a5c60d8123c149cd9c2d0 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 16:03:02 +0530 Subject: [PATCH 069/107] fix --- mobilesdk/sdk/sdk.go | 9 +- wasmsdk/proxy.go | 2 +- zboxcore/sdk/blobber_operations.go | 2 +- zboxcore/sdk/sdk.go | 2 +- znft/README.MD | 1308 ------ ...02057996-nft_dstorage_activity_diagram.png | Bin 430030 -> 0 bytes znft/contracts/doc.go | 2 - .../dstorageerc721/binding/dstorageerc721.go | 2660 ----------- .../binding/dstorageerc721fixed.go | 2930 ------------ .../binding/dstorageerc721pack.go | 3731 ---------------- .../binding/dstorageerc721random.go | 3925 ----------------- znft/contracts/factory/binding/factory.go | 862 ---- .../binding/factorymoduleerc721.go | 201 - .../binding/factorymoduleerc721fixed.go | 201 - .../binding/factorymoduleerc721pack.go | 201 - .../binding/factorymoduleerc721random.go | 201 - znft/doc.go | 4 - znft/ethereum_wallet.go | 110 - znft/example/go.mod | 34 - znft/example/go.sum | 184 - znft/example/main.go | 141 - znft/factoryerc721.go | 48 - znft/factoryerc721fixed.go | 47 - znft/factoryerc721pack.go | 47 - znft/factoryerc721random.go | 47 - znft/keystore.go | 156 - znft/storageerc721.go | 347 -- znft/storageerc721fixed.go | 297 -- znft/storageerc721pack.go | 344 -- znft/storageerc721random.go | 154 - znft/transaction.go | 52 - znft/znft.go | 505 --- 32 files changed, 9 insertions(+), 18745 deletions(-) delete mode 100644 znft/README.MD delete mode 100644 znft/assets/1652602057996-nft_dstorage_activity_diagram.png delete mode 100644 znft/contracts/doc.go delete mode 100644 znft/contracts/dstorageerc721/binding/dstorageerc721.go delete mode 100644 znft/contracts/dstorageerc721fixed/binding/dstorageerc721fixed.go delete mode 100644 znft/contracts/dstorageerc721pack/binding/dstorageerc721pack.go delete mode 100644 znft/contracts/dstorageerc721random/binding/dstorageerc721random.go delete mode 100644 znft/contracts/factory/binding/factory.go delete mode 100644 znft/contracts/factorymoduleerc721/binding/factorymoduleerc721.go delete mode 100644 znft/contracts/factorymoduleerc721fixed/binding/factorymoduleerc721fixed.go delete mode 100644 znft/contracts/factorymoduleerc721pack/binding/factorymoduleerc721pack.go delete mode 100644 znft/contracts/factorymoduleerc721random/binding/factorymoduleerc721random.go delete mode 100644 znft/doc.go delete mode 100644 znft/ethereum_wallet.go delete mode 100644 znft/example/go.mod delete mode 100644 znft/example/go.sum delete mode 100644 znft/example/main.go delete mode 100644 znft/factoryerc721.go delete mode 100644 znft/factoryerc721fixed.go delete mode 100644 znft/factoryerc721pack.go delete mode 100644 znft/factoryerc721random.go delete mode 100644 znft/keystore.go delete mode 100644 znft/storageerc721.go delete mode 100644 znft/storageerc721fixed.go delete mode 100644 znft/storageerc721pack.go delete mode 100644 znft/storageerc721random.go delete mode 100644 znft/transaction.go delete mode 100644 znft/znft.go diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 68c956763..a5a56da23 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -4,6 +4,7 @@ package sdk import ( + "context" "encoding/base64" "encoding/json" "fmt" @@ -14,9 +15,10 @@ import ( "github.com/0chain/gosdk_common/core/sys" "github.com/pkg/errors" + "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/conf" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/zboxcore/client" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -49,7 +51,6 @@ type StorageSDK struct { client *client.Client // chainconfig *ChainConfig } -} // SetLogFile setup log level for core libraries // - logFile: the output file of logs @@ -345,10 +346,12 @@ func (s *StorageSDK) WritePoolLock(durInSeconds int64, tokens, fee float64, allo if err != nil { return errors.Errorf("Error parsing fee: %v", err) } - _, _, err := sdk.WritePoolLock( + _, _, err = sdk.WritePoolLock( allocID, wpLockUint, feeUint, + ) + return err } diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 231d80954..49de72ae5 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -13,10 +13,10 @@ import ( "sync" "time" + "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zcncore" diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 06ba48548..032089cb6 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -392,5 +392,5 @@ func smartContractTxnValueFeeWithRetry(scAddress string, sn transaction.SmartCon value, fee uint64) (hash, out string, nonce int64, t *transaction.Transaction, err error) { // Fee is set during sdk initialization. - return transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, value, client.TxnFee(), true) + return transaction.SmartContractTxnValueFeeWithRetry(scAddress, sn, value, fee, true) } diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index bfcb241b6..6f96ed9d3 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -17,11 +17,11 @@ import ( "github.com/0chain/gosdk_common/core/screstapi" "gopkg.in/natefinch/lumberjack.v2" + "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" enc "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/zboxcore/blockchain" zboxclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/encryption" diff --git a/znft/README.MD b/znft/README.MD deleted file mode 100644 index bd2f07db7..000000000 --- a/znft/README.MD +++ /dev/null @@ -1,1308 +0,0 @@ - - -# znft - -```go -import "github.com/0chain/gosdk_common/znft" -``` - -## Index - -- [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>) - - -## Constants - - - -```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" -) -``` - - - -```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/assets/1652602057996-nft_dstorage_activity_diagram.png b/znft/assets/1652602057996-nft_dstorage_activity_diagram.png deleted file mode 100644 index ab3afb29d2336862386d7ed234b2d23ccf9a704d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 430030 zcmeFZby$>LyEd*!cXtdWASf`@&|T6cAw6^mh_rMK4T5y&P!bXX3JB66DIp~d(%sGP zp6Aj1?stFBcK`PA{reprD#~!Lb+2{hd0pofp{^>AgGq^b=gu7*MFknnJ9khmfG^$9 zQGx&A#@t;8{<`a`DKB-WY=9d02k4HXjHI@w@m3bv1e0t{6P89D*=y5IWLWBJqjJGJ zC2+W*WaE7%4lCji6j@0NeS#{al{+6oO5nOd~h2(LekNf_QClRX0yWsxe1rZ+%OvYgCuEw5NVg4WX9~ABS=To?gQLQW?Szy`B&-p*>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$E8&?6VrUjUbK>xY+#k3clW{^Jg2p&Y6F zB!!AtSO517u@`{vhl|0g%3^?G26c&h1Cr5>gPxkMOAPL}m=}pIq}LUL(M$Q#RQV(X z1vjajJB`6($RWIX8!9P^jq1WMrxgOpWdmwZ%Lm3?2zC@&Tb^wrmET1&OsE0(IBOt@ zqGDwnjK+6xq@>&@9sN>qP}nWvZPUshThJZc3_2J{oGAoRW)A?r)}LNK>|tin2_S($ z`VR0jGX?=@{;A}Xj-z~vm&M{y;7jAmC+vcd+uZ1h$dg>;qlZ!d8RtblSnXZi(b3`f z)m{;G=*^UPkZAUTMA;f9x1A-n23YY8n1e)%Up{^uq@Cz5Z5vWoydsuI3Vtlz5CdWh zLJWH~|Bd*3%6;JB&Sg;55An0cn>KG}9mi=!Z^1*Lj23M3)}R48m{9*7MoJ<}VXhj` zzTI$Vf#DFt&?Z6DIcZ6L diff --git a/znft/contracts/doc.go b/znft/contracts/doc.go deleted file mode 100644 index 1c2861cff..000000000 --- a/znft/contracts/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// 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/contracts/dstorageerc721/binding/dstorageerc721.go b/znft/contracts/dstorageerc721/binding/dstorageerc721.go deleted file mode 100644 index bd45f94a0..000000000 --- a/znft/contracts/dstorageerc721/binding/dstorageerc721.go +++ /dev/null @@ -1,2660 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max_\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"}],\"name\":\"MetadataFrozen\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"previous\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"updated\",\"type\":\"bool\"}],\"name\":\"MintableUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previous\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"updated\",\"type\":\"address\"}],\"name\":\"ReceiverUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"RoyaltyUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriFallbackUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriUpdated\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"allocation\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"batch\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"freeze\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"frozen\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"max\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mintOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mintable\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"price\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"receiver\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"royalty\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"salePrice\",\"type\":\"uint256\"}],\"name\":\"royaltyInfo\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"allocation_\",\"type\":\"string\"}],\"name\":\"setAllocation\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status_\",\"type\":\"bool\"}],\"name\":\"setMintable\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver_\",\"type\":\"address\"}],\"name\":\"setReceiver\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"royalty_\",\"type\":\"uint256\"}],\"name\":\"setRoyalty\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURI\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURIFallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURIFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"total\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uri\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uriFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCaller) Allocation(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "allocation") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCallerSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "balanceOf", owner) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCallerSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCaller) Batch(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "batch") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCallerSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCaller) Frozen(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "frozen") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCallerSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) GetApproved(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "getApproved", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCaller) IsApprovedForAll(opts *bind.CallOpts, owner common.Address, operator common.Address) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "isApprovedForAll", owner, operator) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCallerSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCaller) Max(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "max") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCallerSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCaller) Mintable(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "mintable") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCallerSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCallerSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCallerSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) OwnerOf(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "ownerOf", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCaller) Price(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "price") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCallerSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCaller) Receiver(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "receiver") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCallerSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCaller) Royalty(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royalty") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCallerSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCaller) RoyaltyInfo(opts *bind.CallOpts, tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royaltyInfo", tokenId, salePrice) - - if err != nil { - return *new(common.Address), *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) - - return out0, out1, err - -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCallerSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "supportsInterface", interfaceId) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCallerSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURI(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURI", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURIFallback(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURIFallback", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCaller) Total(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "total") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCallerSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCaller) Uri(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uri") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCallerSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCaller) UriFallback(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uriFallback") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCallerSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) Approve(opts *bind.TransactOpts, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "approve", to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactor) Freeze(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "freeze") -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactorSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactor) Mint(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mint", amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactorSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactor) MintOwner(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mintOwner", amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactorSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom", from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactor) SafeTransferFrom0(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom0", from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactor) SetAllocation(opts *bind.TransactOpts, allocation_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setAllocation", allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactorSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactor) SetApprovalForAll(opts *bind.TransactOpts, operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setApprovalForAll", operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactorSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactor) SetMintable(opts *bind.TransactOpts, status_ bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setMintable", status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactorSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactor) SetReceiver(opts *bind.TransactOpts, receiver_ common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setReceiver", receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactorSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactor) SetRoyalty(opts *bind.TransactOpts, royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setRoyalty", royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactorSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactor) SetURI(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURI", uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactor) SetURIFallback(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURIFallback", uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferFrom", from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "withdraw") -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactorSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// BindingApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Binding contract. -type BindingApprovalIterator struct { - Event *BindingApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApproval represents a Approval event raised by the Binding contract. -type BindingApproval struct { - Owner common.Address - Approved common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, approved []common.Address, tokenId []*big.Int) (*BindingApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingApprovalIterator{contract: _Binding.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *BindingApproval, owner []common.Address, approved []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseApproval(log types.Log) (*BindingApproval, error) { - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingApprovalForAllIterator is returned from FilterApprovalForAll and is used to iterate over the raw logs and unpacked data for ApprovalForAll events raised by the Binding contract. -type BindingApprovalForAllIterator struct { - Event *BindingApprovalForAll // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalForAllIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalForAllIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalForAllIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApprovalForAll represents a ApprovalForAll event raised by the Binding contract. -type BindingApprovalForAll struct { - Owner common.Address - Operator common.Address - Approved bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApprovalForAll is a free log retrieval operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) FilterApprovalForAll(opts *bind.FilterOpts, owner []common.Address, operator []common.Address) (*BindingApprovalForAllIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return &BindingApprovalForAllIterator{contract: _Binding.contract, event: "ApprovalForAll", logs: logs, sub: sub}, nil -} - -// WatchApprovalForAll is a free log subscription operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) WatchApprovalForAll(opts *bind.WatchOpts, sink chan<- *BindingApprovalForAll, owner []common.Address, operator []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApprovalForAll is a log parse operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) ParseApprovalForAll(log types.Log) (*BindingApprovalForAll, error) { - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMetadataFrozenIterator is returned from FilterMetadataFrozen and is used to iterate over the raw logs and unpacked data for MetadataFrozen events raised by the Binding contract. -type BindingMetadataFrozenIterator struct { - Event *BindingMetadataFrozen // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMetadataFrozenIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMetadataFrozenIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMetadataFrozenIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMetadataFrozen represents a MetadataFrozen event raised by the Binding contract. -type BindingMetadataFrozen struct { - Uri string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMetadataFrozen is a free log retrieval operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) FilterMetadataFrozen(opts *bind.FilterOpts) (*BindingMetadataFrozenIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return &BindingMetadataFrozenIterator{contract: _Binding.contract, event: "MetadataFrozen", logs: logs, sub: sub}, nil -} - -// WatchMetadataFrozen is a free log subscription operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) WatchMetadataFrozen(opts *bind.WatchOpts, sink chan<- *BindingMetadataFrozen) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMetadataFrozen is a log parse operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) ParseMetadataFrozen(log types.Log) (*BindingMetadataFrozen, error) { - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMintableUpdatedIterator is returned from FilterMintableUpdated and is used to iterate over the raw logs and unpacked data for MintableUpdated events raised by the Binding contract. -type BindingMintableUpdatedIterator struct { - Event *BindingMintableUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMintableUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMintableUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMintableUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMintableUpdated represents a MintableUpdated event raised by the Binding contract. -type BindingMintableUpdated struct { - Previous bool - Updated bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMintableUpdated is a free log retrieval operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) FilterMintableUpdated(opts *bind.FilterOpts) (*BindingMintableUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return &BindingMintableUpdatedIterator{contract: _Binding.contract, event: "MintableUpdated", logs: logs, sub: sub}, nil -} - -// WatchMintableUpdated is a free log subscription operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) WatchMintableUpdated(opts *bind.WatchOpts, sink chan<- *BindingMintableUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMintableUpdated is a log parse operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) ParseMintableUpdated(log types.Log) (*BindingMintableUpdated, error) { - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Binding contract. -type BindingOwnershipTransferredIterator struct { - Event *BindingOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingOwnershipTransferred represents a OwnershipTransferred event raised by the Binding contract. -type BindingOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*BindingOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &BindingOwnershipTransferredIterator{contract: _Binding.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *BindingOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) ParseOwnershipTransferred(log types.Log) (*BindingOwnershipTransferred, error) { - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingReceiverUpdatedIterator is returned from FilterReceiverUpdated and is used to iterate over the raw logs and unpacked data for ReceiverUpdated events raised by the Binding contract. -type BindingReceiverUpdatedIterator struct { - Event *BindingReceiverUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingReceiverUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingReceiverUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingReceiverUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingReceiverUpdated represents a ReceiverUpdated event raised by the Binding contract. -type BindingReceiverUpdated struct { - Previous common.Address - Updated common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterReceiverUpdated is a free log retrieval operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) FilterReceiverUpdated(opts *bind.FilterOpts) (*BindingReceiverUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return &BindingReceiverUpdatedIterator{contract: _Binding.contract, event: "ReceiverUpdated", logs: logs, sub: sub}, nil -} - -// WatchReceiverUpdated is a free log subscription operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) WatchReceiverUpdated(opts *bind.WatchOpts, sink chan<- *BindingReceiverUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceiverUpdated is a log parse operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) ParseReceiverUpdated(log types.Log) (*BindingReceiverUpdated, error) { - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingRoyaltyUpdatedIterator is returned from FilterRoyaltyUpdated and is used to iterate over the raw logs and unpacked data for RoyaltyUpdated events raised by the Binding contract. -type BindingRoyaltyUpdatedIterator struct { - Event *BindingRoyaltyUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingRoyaltyUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingRoyaltyUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingRoyaltyUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingRoyaltyUpdated represents a RoyaltyUpdated event raised by the Binding contract. -type BindingRoyaltyUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterRoyaltyUpdated is a free log retrieval operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterRoyaltyUpdated(opts *bind.FilterOpts) (*BindingRoyaltyUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return &BindingRoyaltyUpdatedIterator{contract: _Binding.contract, event: "RoyaltyUpdated", logs: logs, sub: sub}, nil -} - -// WatchRoyaltyUpdated is a free log subscription operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchRoyaltyUpdated(opts *bind.WatchOpts, sink chan<- *BindingRoyaltyUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseRoyaltyUpdated is a log parse operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseRoyaltyUpdated(log types.Log) (*BindingRoyaltyUpdated, error) { - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Binding contract. -type BindingTransferIterator struct { - Event *BindingTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingTransfer represents a Transfer event raised by the Binding contract. -type BindingTransfer struct { - From common.Address - To common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address, tokenId []*big.Int) (*BindingTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingTransferIterator{contract: _Binding.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *BindingTransfer, from []common.Address, to []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseTransfer(log types.Log) (*BindingTransfer, error) { - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriFallbackUpdatedIterator is returned from FilterUriFallbackUpdated and is used to iterate over the raw logs and unpacked data for UriFallbackUpdated events raised by the Binding contract. -type BindingUriFallbackUpdatedIterator struct { - Event *BindingUriFallbackUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriFallbackUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriFallbackUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriFallbackUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriFallbackUpdated represents a UriFallbackUpdated event raised by the Binding contract. -type BindingUriFallbackUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriFallbackUpdated is a free log retrieval operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriFallbackUpdated(opts *bind.FilterOpts) (*BindingUriFallbackUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return &BindingUriFallbackUpdatedIterator{contract: _Binding.contract, event: "UriFallbackUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriFallbackUpdated is a free log subscription operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriFallbackUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriFallbackUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriFallbackUpdated is a log parse operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriFallbackUpdated(log types.Log) (*BindingUriFallbackUpdated, error) { - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriUpdatedIterator is returned from FilterUriUpdated and is used to iterate over the raw logs and unpacked data for UriUpdated events raised by the Binding contract. -type BindingUriUpdatedIterator struct { - Event *BindingUriUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriUpdated represents a UriUpdated event raised by the Binding contract. -type BindingUriUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriUpdated is a free log retrieval operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriUpdated(opts *bind.FilterOpts) (*BindingUriUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return &BindingUriUpdatedIterator{contract: _Binding.contract, event: "UriUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriUpdated is a free log subscription operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriUpdated is a log parse operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriUpdated(log types.Log) (*BindingUriUpdated, error) { - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/znft/contracts/dstorageerc721fixed/binding/dstorageerc721fixed.go b/znft/contracts/dstorageerc721fixed/binding/dstorageerc721fixed.go deleted file mode 100644 index cc665c565..000000000 --- a/znft/contracts/dstorageerc721fixed/binding/dstorageerc721fixed.go +++ /dev/null @@ -1,2930 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max_\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"price_\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"batch_\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"BatchUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"}],\"name\":\"MetadataFrozen\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"previous\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"updated\",\"type\":\"bool\"}],\"name\":\"MintableUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"PriceUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previous\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"updated\",\"type\":\"address\"}],\"name\":\"ReceiverUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"RoyaltyUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriFallbackUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriUpdated\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"allocation\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"batch\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"freeze\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"frozen\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"max\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mintOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mintable\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"price\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"receiver\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"royalty\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"salePrice\",\"type\":\"uint256\"}],\"name\":\"royaltyInfo\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"allocation_\",\"type\":\"string\"}],\"name\":\"setAllocation\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status_\",\"type\":\"bool\"}],\"name\":\"setMintable\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver_\",\"type\":\"address\"}],\"name\":\"setReceiver\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"royalty_\",\"type\":\"uint256\"}],\"name\":\"setRoyalty\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURI\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURIFallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURIFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"total\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uri\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uriFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCaller) Allocation(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "allocation") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCallerSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "balanceOf", owner) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCallerSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCaller) Batch(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "batch") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCallerSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCaller) Frozen(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "frozen") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCallerSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) GetApproved(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "getApproved", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCaller) IsApprovedForAll(opts *bind.CallOpts, owner common.Address, operator common.Address) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "isApprovedForAll", owner, operator) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCallerSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCaller) Max(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "max") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCallerSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCaller) Mintable(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "mintable") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCallerSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCallerSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCallerSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) OwnerOf(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "ownerOf", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCaller) Price(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "price") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCallerSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCaller) Receiver(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "receiver") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCallerSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCaller) Royalty(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royalty") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCallerSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCaller) RoyaltyInfo(opts *bind.CallOpts, tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royaltyInfo", tokenId, salePrice) - - if err != nil { - return *new(common.Address), *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) - - return out0, out1, err - -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCallerSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "supportsInterface", interfaceId) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCallerSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURI(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURI", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURIFallback(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURIFallback", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCaller) Total(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "total") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCallerSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCaller) Uri(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uri") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCallerSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCaller) UriFallback(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uriFallback") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCallerSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) Approve(opts *bind.TransactOpts, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "approve", to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactor) Freeze(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "freeze") -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactorSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactor) Mint(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mint", amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactorSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactor) MintOwner(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mintOwner", amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactorSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom", from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactor) SafeTransferFrom0(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom0", from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactor) SetAllocation(opts *bind.TransactOpts, allocation_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setAllocation", allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactorSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactor) SetApprovalForAll(opts *bind.TransactOpts, operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setApprovalForAll", operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactorSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactor) SetMintable(opts *bind.TransactOpts, status_ bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setMintable", status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactorSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactor) SetReceiver(opts *bind.TransactOpts, receiver_ common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setReceiver", receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactorSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactor) SetRoyalty(opts *bind.TransactOpts, royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setRoyalty", royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactorSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactor) SetURI(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURI", uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactor) SetURIFallback(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURIFallback", uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferFrom", from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "withdraw") -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactorSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// BindingApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Binding contract. -type BindingApprovalIterator struct { - Event *BindingApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApproval represents a Approval event raised by the Binding contract. -type BindingApproval struct { - Owner common.Address - Approved common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, approved []common.Address, tokenId []*big.Int) (*BindingApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingApprovalIterator{contract: _Binding.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *BindingApproval, owner []common.Address, approved []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseApproval(log types.Log) (*BindingApproval, error) { - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingApprovalForAllIterator is returned from FilterApprovalForAll and is used to iterate over the raw logs and unpacked data for ApprovalForAll events raised by the Binding contract. -type BindingApprovalForAllIterator struct { - Event *BindingApprovalForAll // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalForAllIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalForAllIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalForAllIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApprovalForAll represents a ApprovalForAll event raised by the Binding contract. -type BindingApprovalForAll struct { - Owner common.Address - Operator common.Address - Approved bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApprovalForAll is a free log retrieval operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) FilterApprovalForAll(opts *bind.FilterOpts, owner []common.Address, operator []common.Address) (*BindingApprovalForAllIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return &BindingApprovalForAllIterator{contract: _Binding.contract, event: "ApprovalForAll", logs: logs, sub: sub}, nil -} - -// WatchApprovalForAll is a free log subscription operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) WatchApprovalForAll(opts *bind.WatchOpts, sink chan<- *BindingApprovalForAll, owner []common.Address, operator []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApprovalForAll is a log parse operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) ParseApprovalForAll(log types.Log) (*BindingApprovalForAll, error) { - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingBatchUpdatedIterator is returned from FilterBatchUpdated and is used to iterate over the raw logs and unpacked data for BatchUpdated events raised by the Binding contract. -type BindingBatchUpdatedIterator struct { - Event *BindingBatchUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingBatchUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingBatchUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingBatchUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingBatchUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingBatchUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingBatchUpdated represents a BatchUpdated event raised by the Binding contract. -type BindingBatchUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterBatchUpdated is a free log retrieval operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterBatchUpdated(opts *bind.FilterOpts) (*BindingBatchUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "BatchUpdated") - if err != nil { - return nil, err - } - return &BindingBatchUpdatedIterator{contract: _Binding.contract, event: "BatchUpdated", logs: logs, sub: sub}, nil -} - -// WatchBatchUpdated is a free log subscription operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchBatchUpdated(opts *bind.WatchOpts, sink chan<- *BindingBatchUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "BatchUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingBatchUpdated) - if err := _Binding.contract.UnpackLog(event, "BatchUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseBatchUpdated is a log parse operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseBatchUpdated(log types.Log) (*BindingBatchUpdated, error) { - event := new(BindingBatchUpdated) - if err := _Binding.contract.UnpackLog(event, "BatchUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMetadataFrozenIterator is returned from FilterMetadataFrozen and is used to iterate over the raw logs and unpacked data for MetadataFrozen events raised by the Binding contract. -type BindingMetadataFrozenIterator struct { - Event *BindingMetadataFrozen // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMetadataFrozenIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMetadataFrozenIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMetadataFrozenIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMetadataFrozen represents a MetadataFrozen event raised by the Binding contract. -type BindingMetadataFrozen struct { - Uri string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMetadataFrozen is a free log retrieval operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) FilterMetadataFrozen(opts *bind.FilterOpts) (*BindingMetadataFrozenIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return &BindingMetadataFrozenIterator{contract: _Binding.contract, event: "MetadataFrozen", logs: logs, sub: sub}, nil -} - -// WatchMetadataFrozen is a free log subscription operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) WatchMetadataFrozen(opts *bind.WatchOpts, sink chan<- *BindingMetadataFrozen) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMetadataFrozen is a log parse operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) ParseMetadataFrozen(log types.Log) (*BindingMetadataFrozen, error) { - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMintableUpdatedIterator is returned from FilterMintableUpdated and is used to iterate over the raw logs and unpacked data for MintableUpdated events raised by the Binding contract. -type BindingMintableUpdatedIterator struct { - Event *BindingMintableUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMintableUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMintableUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMintableUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMintableUpdated represents a MintableUpdated event raised by the Binding contract. -type BindingMintableUpdated struct { - Previous bool - Updated bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMintableUpdated is a free log retrieval operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) FilterMintableUpdated(opts *bind.FilterOpts) (*BindingMintableUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return &BindingMintableUpdatedIterator{contract: _Binding.contract, event: "MintableUpdated", logs: logs, sub: sub}, nil -} - -// WatchMintableUpdated is a free log subscription operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) WatchMintableUpdated(opts *bind.WatchOpts, sink chan<- *BindingMintableUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMintableUpdated is a log parse operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) ParseMintableUpdated(log types.Log) (*BindingMintableUpdated, error) { - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Binding contract. -type BindingOwnershipTransferredIterator struct { - Event *BindingOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingOwnershipTransferred represents a OwnershipTransferred event raised by the Binding contract. -type BindingOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*BindingOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &BindingOwnershipTransferredIterator{contract: _Binding.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *BindingOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) ParseOwnershipTransferred(log types.Log) (*BindingOwnershipTransferred, error) { - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingPriceUpdatedIterator is returned from FilterPriceUpdated and is used to iterate over the raw logs and unpacked data for PriceUpdated events raised by the Binding contract. -type BindingPriceUpdatedIterator struct { - Event *BindingPriceUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingPriceUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingPriceUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingPriceUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingPriceUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingPriceUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingPriceUpdated represents a PriceUpdated event raised by the Binding contract. -type BindingPriceUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterPriceUpdated is a free log retrieval operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterPriceUpdated(opts *bind.FilterOpts) (*BindingPriceUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "PriceUpdated") - if err != nil { - return nil, err - } - return &BindingPriceUpdatedIterator{contract: _Binding.contract, event: "PriceUpdated", logs: logs, sub: sub}, nil -} - -// WatchPriceUpdated is a free log subscription operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchPriceUpdated(opts *bind.WatchOpts, sink chan<- *BindingPriceUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "PriceUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingPriceUpdated) - if err := _Binding.contract.UnpackLog(event, "PriceUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParsePriceUpdated is a log parse operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParsePriceUpdated(log types.Log) (*BindingPriceUpdated, error) { - event := new(BindingPriceUpdated) - if err := _Binding.contract.UnpackLog(event, "PriceUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingReceiverUpdatedIterator is returned from FilterReceiverUpdated and is used to iterate over the raw logs and unpacked data for ReceiverUpdated events raised by the Binding contract. -type BindingReceiverUpdatedIterator struct { - Event *BindingReceiverUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingReceiverUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingReceiverUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingReceiverUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingReceiverUpdated represents a ReceiverUpdated event raised by the Binding contract. -type BindingReceiverUpdated struct { - Previous common.Address - Updated common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterReceiverUpdated is a free log retrieval operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) FilterReceiverUpdated(opts *bind.FilterOpts) (*BindingReceiverUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return &BindingReceiverUpdatedIterator{contract: _Binding.contract, event: "ReceiverUpdated", logs: logs, sub: sub}, nil -} - -// WatchReceiverUpdated is a free log subscription operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) WatchReceiverUpdated(opts *bind.WatchOpts, sink chan<- *BindingReceiverUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceiverUpdated is a log parse operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) ParseReceiverUpdated(log types.Log) (*BindingReceiverUpdated, error) { - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingRoyaltyUpdatedIterator is returned from FilterRoyaltyUpdated and is used to iterate over the raw logs and unpacked data for RoyaltyUpdated events raised by the Binding contract. -type BindingRoyaltyUpdatedIterator struct { - Event *BindingRoyaltyUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingRoyaltyUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingRoyaltyUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingRoyaltyUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingRoyaltyUpdated represents a RoyaltyUpdated event raised by the Binding contract. -type BindingRoyaltyUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterRoyaltyUpdated is a free log retrieval operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterRoyaltyUpdated(opts *bind.FilterOpts) (*BindingRoyaltyUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return &BindingRoyaltyUpdatedIterator{contract: _Binding.contract, event: "RoyaltyUpdated", logs: logs, sub: sub}, nil -} - -// WatchRoyaltyUpdated is a free log subscription operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchRoyaltyUpdated(opts *bind.WatchOpts, sink chan<- *BindingRoyaltyUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseRoyaltyUpdated is a log parse operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseRoyaltyUpdated(log types.Log) (*BindingRoyaltyUpdated, error) { - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Binding contract. -type BindingTransferIterator struct { - Event *BindingTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingTransfer represents a Transfer event raised by the Binding contract. -type BindingTransfer struct { - From common.Address - To common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address, tokenId []*big.Int) (*BindingTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingTransferIterator{contract: _Binding.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *BindingTransfer, from []common.Address, to []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseTransfer(log types.Log) (*BindingTransfer, error) { - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriFallbackUpdatedIterator is returned from FilterUriFallbackUpdated and is used to iterate over the raw logs and unpacked data for UriFallbackUpdated events raised by the Binding contract. -type BindingUriFallbackUpdatedIterator struct { - Event *BindingUriFallbackUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriFallbackUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriFallbackUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriFallbackUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriFallbackUpdated represents a UriFallbackUpdated event raised by the Binding contract. -type BindingUriFallbackUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriFallbackUpdated is a free log retrieval operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriFallbackUpdated(opts *bind.FilterOpts) (*BindingUriFallbackUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return &BindingUriFallbackUpdatedIterator{contract: _Binding.contract, event: "UriFallbackUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriFallbackUpdated is a free log subscription operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriFallbackUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriFallbackUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriFallbackUpdated is a log parse operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriFallbackUpdated(log types.Log) (*BindingUriFallbackUpdated, error) { - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriUpdatedIterator is returned from FilterUriUpdated and is used to iterate over the raw logs and unpacked data for UriUpdated events raised by the Binding contract. -type BindingUriUpdatedIterator struct { - Event *BindingUriUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriUpdated represents a UriUpdated event raised by the Binding contract. -type BindingUriUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriUpdated is a free log retrieval operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriUpdated(opts *bind.FilterOpts) (*BindingUriUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return &BindingUriUpdatedIterator{contract: _Binding.contract, event: "UriUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriUpdated is a free log subscription operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriUpdated is a log parse operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriUpdated(log types.Log) (*BindingUriUpdated, error) { - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/znft/contracts/dstorageerc721pack/binding/dstorageerc721pack.go b/znft/contracts/dstorageerc721pack/binding/dstorageerc721pack.go deleted file mode 100644 index 6fd81685c..000000000 --- a/znft/contracts/dstorageerc721pack/binding/dstorageerc721pack.go +++ /dev/null @@ -1,3731 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"price_\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"batch_\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"size_\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"token_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"BatchUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"ClosedUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"}],\"name\":\"MetadataFrozen\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"previous\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"updated\",\"type\":\"bool\"}],\"name\":\"MintableUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"OpenedUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"user\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"requestId\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"PackOpened\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"user\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"content\",\"type\":\"uint256\"}],\"name\":\"PackRedeemed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"PriceUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previous\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"updated\",\"type\":\"address\"}],\"name\":\"ReceiverUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"RoyaltyUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriFallbackUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriUpdated\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"allocation\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"batch\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"closed\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"contents\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"freeze\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"frozen\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"max\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mintOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mintable\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"opened\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"price\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"receiver\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"redeem\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"reveal\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"royalty\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"salePrice\",\"type\":\"uint256\"}],\"name\":\"royaltyInfo\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"allocation_\",\"type\":\"string\"}],\"name\":\"setAllocation\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"closed_\",\"type\":\"string\"}],\"name\":\"setClosed\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status_\",\"type\":\"bool\"}],\"name\":\"setMintable\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"opened_\",\"type\":\"string\"}],\"name\":\"setOpened\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver_\",\"type\":\"address\"}],\"name\":\"setReceiver\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"royalty_\",\"type\":\"uint256\"}],\"name\":\"setRoyalty\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURI\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURIFallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"size\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"token\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURIFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"total\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uri\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uriFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCaller) Allocation(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "allocation") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCallerSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "balanceOf", owner) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCallerSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCaller) Batch(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "batch") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCallerSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Closed is a free data retrieval call binding the contract method 0x597e1fb5. -// -// Solidity: function closed() view returns(string) -func (_Binding *BindingCaller) Closed(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "closed") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Closed is a free data retrieval call binding the contract method 0x597e1fb5. -// -// Solidity: function closed() view returns(string) -func (_Binding *BindingSession) Closed() (string, error) { - return _Binding.Contract.Closed(&_Binding.CallOpts) -} - -// Closed is a free data retrieval call binding the contract method 0x597e1fb5. -// -// Solidity: function closed() view returns(string) -func (_Binding *BindingCallerSession) Closed() (string, error) { - return _Binding.Contract.Closed(&_Binding.CallOpts) -} - -// Contents is a free data retrieval call binding the contract method 0xb5ecf912. -// -// Solidity: function contents(uint256 ) view returns(uint256) -func (_Binding *BindingCaller) Contents(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "contents", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Contents is a free data retrieval call binding the contract method 0xb5ecf912. -// -// Solidity: function contents(uint256 ) view returns(uint256) -func (_Binding *BindingSession) Contents(arg0 *big.Int) (*big.Int, error) { - return _Binding.Contract.Contents(&_Binding.CallOpts, arg0) -} - -// Contents is a free data retrieval call binding the contract method 0xb5ecf912. -// -// Solidity: function contents(uint256 ) view returns(uint256) -func (_Binding *BindingCallerSession) Contents(arg0 *big.Int) (*big.Int, error) { - return _Binding.Contract.Contents(&_Binding.CallOpts, arg0) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCaller) Frozen(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "frozen") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCallerSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) GetApproved(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "getApproved", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCaller) IsApprovedForAll(opts *bind.CallOpts, owner common.Address, operator common.Address) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "isApprovedForAll", owner, operator) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCallerSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCaller) Max(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "max") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCallerSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCaller) Mintable(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "mintable") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCallerSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCallerSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Opened is a free data retrieval call binding the contract method 0x5f88eade. -// -// Solidity: function opened() view returns(string) -func (_Binding *BindingCaller) Opened(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "opened") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Opened is a free data retrieval call binding the contract method 0x5f88eade. -// -// Solidity: function opened() view returns(string) -func (_Binding *BindingSession) Opened() (string, error) { - return _Binding.Contract.Opened(&_Binding.CallOpts) -} - -// Opened is a free data retrieval call binding the contract method 0x5f88eade. -// -// Solidity: function opened() view returns(string) -func (_Binding *BindingCallerSession) Opened() (string, error) { - return _Binding.Contract.Opened(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCallerSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) OwnerOf(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "ownerOf", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCaller) Price(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "price") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCallerSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCaller) Receiver(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "receiver") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCallerSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCaller) Royalty(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royalty") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCallerSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCaller) RoyaltyInfo(opts *bind.CallOpts, tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royaltyInfo", tokenId, salePrice) - - if err != nil { - return *new(common.Address), *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) - - return out0, out1, err - -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCallerSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// Size is a free data retrieval call binding the contract method 0x949d225d. -// -// Solidity: function size() view returns(uint256) -func (_Binding *BindingCaller) Size(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "size") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Size is a free data retrieval call binding the contract method 0x949d225d. -// -// Solidity: function size() view returns(uint256) -func (_Binding *BindingSession) Size() (*big.Int, error) { - return _Binding.Contract.Size(&_Binding.CallOpts) -} - -// Size is a free data retrieval call binding the contract method 0x949d225d. -// -// Solidity: function size() view returns(uint256) -func (_Binding *BindingCallerSession) Size() (*big.Int, error) { - return _Binding.Contract.Size(&_Binding.CallOpts) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "supportsInterface", interfaceId) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCallerSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// Token is a free data retrieval call binding the contract method 0xfc0c546a. -// -// Solidity: function token() view returns(address) -func (_Binding *BindingCaller) Token(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "token") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Token is a free data retrieval call binding the contract method 0xfc0c546a. -// -// Solidity: function token() view returns(address) -func (_Binding *BindingSession) Token() (common.Address, error) { - return _Binding.Contract.Token(&_Binding.CallOpts) -} - -// Token is a free data retrieval call binding the contract method 0xfc0c546a. -// -// Solidity: function token() view returns(address) -func (_Binding *BindingCallerSession) Token() (common.Address, error) { - return _Binding.Contract.Token(&_Binding.CallOpts) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURI(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURI", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURIFallback(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURIFallback", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCaller) Total(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "total") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCallerSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCaller) Uri(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uri") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCallerSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCaller) UriFallback(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uriFallback") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCallerSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) Approve(opts *bind.TransactOpts, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "approve", to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactor) Freeze(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "freeze") -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactorSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactor) Mint(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mint", amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactorSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactor) MintOwner(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mintOwner", amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactorSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// Redeem is a paid mutator transaction binding the contract method 0xdb006a75. -// -// Solidity: function redeem(uint256 tokenId) returns() -func (_Binding *BindingTransactor) Redeem(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "redeem", tokenId) -} - -// Redeem is a paid mutator transaction binding the contract method 0xdb006a75. -// -// Solidity: function redeem(uint256 tokenId) returns() -func (_Binding *BindingSession) Redeem(tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Redeem(&_Binding.TransactOpts, tokenId) -} - -// Redeem is a paid mutator transaction binding the contract method 0xdb006a75. -// -// Solidity: function redeem(uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) Redeem(tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Redeem(&_Binding.TransactOpts, tokenId) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// Reveal is a paid mutator transaction binding the contract method 0xc2ca0ac5. -// -// Solidity: function reveal(uint256 tokenId) returns(bytes32) -func (_Binding *BindingTransactor) Reveal(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "reveal", tokenId) -} - -// Reveal is a paid mutator transaction binding the contract method 0xc2ca0ac5. -// -// Solidity: function reveal(uint256 tokenId) returns(bytes32) -func (_Binding *BindingSession) Reveal(tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Reveal(&_Binding.TransactOpts, tokenId) -} - -// Reveal is a paid mutator transaction binding the contract method 0xc2ca0ac5. -// -// Solidity: function reveal(uint256 tokenId) returns(bytes32) -func (_Binding *BindingTransactorSession) Reveal(tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Reveal(&_Binding.TransactOpts, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom", from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactor) SafeTransferFrom0(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom0", from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactor) SetAllocation(opts *bind.TransactOpts, allocation_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setAllocation", allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactorSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactor) SetApprovalForAll(opts *bind.TransactOpts, operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setApprovalForAll", operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactorSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetClosed is a paid mutator transaction binding the contract method 0x2b079e9c. -// -// Solidity: function setClosed(string closed_) returns() -func (_Binding *BindingTransactor) SetClosed(opts *bind.TransactOpts, closed_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setClosed", closed_) -} - -// SetClosed is a paid mutator transaction binding the contract method 0x2b079e9c. -// -// Solidity: function setClosed(string closed_) returns() -func (_Binding *BindingSession) SetClosed(closed_ string) (*types.Transaction, error) { - return _Binding.Contract.SetClosed(&_Binding.TransactOpts, closed_) -} - -// SetClosed is a paid mutator transaction binding the contract method 0x2b079e9c. -// -// Solidity: function setClosed(string closed_) returns() -func (_Binding *BindingTransactorSession) SetClosed(closed_ string) (*types.Transaction, error) { - return _Binding.Contract.SetClosed(&_Binding.TransactOpts, closed_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactor) SetMintable(opts *bind.TransactOpts, status_ bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setMintable", status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactorSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetOpened is a paid mutator transaction binding the contract method 0x8967032b. -// -// Solidity: function setOpened(string opened_) returns() -func (_Binding *BindingTransactor) SetOpened(opts *bind.TransactOpts, opened_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setOpened", opened_) -} - -// SetOpened is a paid mutator transaction binding the contract method 0x8967032b. -// -// Solidity: function setOpened(string opened_) returns() -func (_Binding *BindingSession) SetOpened(opened_ string) (*types.Transaction, error) { - return _Binding.Contract.SetOpened(&_Binding.TransactOpts, opened_) -} - -// SetOpened is a paid mutator transaction binding the contract method 0x8967032b. -// -// Solidity: function setOpened(string opened_) returns() -func (_Binding *BindingTransactorSession) SetOpened(opened_ string) (*types.Transaction, error) { - return _Binding.Contract.SetOpened(&_Binding.TransactOpts, opened_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactor) SetReceiver(opts *bind.TransactOpts, receiver_ common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setReceiver", receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactorSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactor) SetRoyalty(opts *bind.TransactOpts, royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setRoyalty", royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactorSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactor) SetURI(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURI", uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactor) SetURIFallback(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURIFallback", uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferFrom", from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "withdraw") -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactorSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// BindingApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Binding contract. -type BindingApprovalIterator struct { - Event *BindingApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApproval represents a Approval event raised by the Binding contract. -type BindingApproval struct { - Owner common.Address - Approved common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, approved []common.Address, tokenId []*big.Int) (*BindingApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingApprovalIterator{contract: _Binding.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *BindingApproval, owner []common.Address, approved []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseApproval(log types.Log) (*BindingApproval, error) { - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingApprovalForAllIterator is returned from FilterApprovalForAll and is used to iterate over the raw logs and unpacked data for ApprovalForAll events raised by the Binding contract. -type BindingApprovalForAllIterator struct { - Event *BindingApprovalForAll // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalForAllIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalForAllIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalForAllIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApprovalForAll represents a ApprovalForAll event raised by the Binding contract. -type BindingApprovalForAll struct { - Owner common.Address - Operator common.Address - Approved bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApprovalForAll is a free log retrieval operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) FilterApprovalForAll(opts *bind.FilterOpts, owner []common.Address, operator []common.Address) (*BindingApprovalForAllIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return &BindingApprovalForAllIterator{contract: _Binding.contract, event: "ApprovalForAll", logs: logs, sub: sub}, nil -} - -// WatchApprovalForAll is a free log subscription operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) WatchApprovalForAll(opts *bind.WatchOpts, sink chan<- *BindingApprovalForAll, owner []common.Address, operator []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApprovalForAll is a log parse operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) ParseApprovalForAll(log types.Log) (*BindingApprovalForAll, error) { - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingBatchUpdatedIterator is returned from FilterBatchUpdated and is used to iterate over the raw logs and unpacked data for BatchUpdated events raised by the Binding contract. -type BindingBatchUpdatedIterator struct { - Event *BindingBatchUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingBatchUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingBatchUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingBatchUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingBatchUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingBatchUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingBatchUpdated represents a BatchUpdated event raised by the Binding contract. -type BindingBatchUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterBatchUpdated is a free log retrieval operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterBatchUpdated(opts *bind.FilterOpts) (*BindingBatchUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "BatchUpdated") - if err != nil { - return nil, err - } - return &BindingBatchUpdatedIterator{contract: _Binding.contract, event: "BatchUpdated", logs: logs, sub: sub}, nil -} - -// WatchBatchUpdated is a free log subscription operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchBatchUpdated(opts *bind.WatchOpts, sink chan<- *BindingBatchUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "BatchUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingBatchUpdated) - if err := _Binding.contract.UnpackLog(event, "BatchUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseBatchUpdated is a log parse operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseBatchUpdated(log types.Log) (*BindingBatchUpdated, error) { - event := new(BindingBatchUpdated) - if err := _Binding.contract.UnpackLog(event, "BatchUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingClosedUpdatedIterator is returned from FilterClosedUpdated and is used to iterate over the raw logs and unpacked data for ClosedUpdated events raised by the Binding contract. -type BindingClosedUpdatedIterator struct { - Event *BindingClosedUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingClosedUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingClosedUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingClosedUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingClosedUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingClosedUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingClosedUpdated represents a ClosedUpdated event raised by the Binding contract. -type BindingClosedUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterClosedUpdated is a free log retrieval operation binding the contract event 0xe522ca01e98dcc00c0c8fbb3f248b612670c83507d33b0e30f7cb683ee21a3eb. -// -// Solidity: event ClosedUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterClosedUpdated(opts *bind.FilterOpts) (*BindingClosedUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ClosedUpdated") - if err != nil { - return nil, err - } - return &BindingClosedUpdatedIterator{contract: _Binding.contract, event: "ClosedUpdated", logs: logs, sub: sub}, nil -} - -// WatchClosedUpdated is a free log subscription operation binding the contract event 0xe522ca01e98dcc00c0c8fbb3f248b612670c83507d33b0e30f7cb683ee21a3eb. -// -// Solidity: event ClosedUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchClosedUpdated(opts *bind.WatchOpts, sink chan<- *BindingClosedUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ClosedUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingClosedUpdated) - if err := _Binding.contract.UnpackLog(event, "ClosedUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseClosedUpdated is a log parse operation binding the contract event 0xe522ca01e98dcc00c0c8fbb3f248b612670c83507d33b0e30f7cb683ee21a3eb. -// -// Solidity: event ClosedUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseClosedUpdated(log types.Log) (*BindingClosedUpdated, error) { - event := new(BindingClosedUpdated) - if err := _Binding.contract.UnpackLog(event, "ClosedUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMetadataFrozenIterator is returned from FilterMetadataFrozen and is used to iterate over the raw logs and unpacked data for MetadataFrozen events raised by the Binding contract. -type BindingMetadataFrozenIterator struct { - Event *BindingMetadataFrozen // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMetadataFrozenIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMetadataFrozenIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMetadataFrozenIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMetadataFrozen represents a MetadataFrozen event raised by the Binding contract. -type BindingMetadataFrozen struct { - Uri string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMetadataFrozen is a free log retrieval operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) FilterMetadataFrozen(opts *bind.FilterOpts) (*BindingMetadataFrozenIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return &BindingMetadataFrozenIterator{contract: _Binding.contract, event: "MetadataFrozen", logs: logs, sub: sub}, nil -} - -// WatchMetadataFrozen is a free log subscription operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) WatchMetadataFrozen(opts *bind.WatchOpts, sink chan<- *BindingMetadataFrozen) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMetadataFrozen is a log parse operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) ParseMetadataFrozen(log types.Log) (*BindingMetadataFrozen, error) { - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMintableUpdatedIterator is returned from FilterMintableUpdated and is used to iterate over the raw logs and unpacked data for MintableUpdated events raised by the Binding contract. -type BindingMintableUpdatedIterator struct { - Event *BindingMintableUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMintableUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMintableUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMintableUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMintableUpdated represents a MintableUpdated event raised by the Binding contract. -type BindingMintableUpdated struct { - Previous bool - Updated bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMintableUpdated is a free log retrieval operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) FilterMintableUpdated(opts *bind.FilterOpts) (*BindingMintableUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return &BindingMintableUpdatedIterator{contract: _Binding.contract, event: "MintableUpdated", logs: logs, sub: sub}, nil -} - -// WatchMintableUpdated is a free log subscription operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) WatchMintableUpdated(opts *bind.WatchOpts, sink chan<- *BindingMintableUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMintableUpdated is a log parse operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) ParseMintableUpdated(log types.Log) (*BindingMintableUpdated, error) { - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingOpenedUpdatedIterator is returned from FilterOpenedUpdated and is used to iterate over the raw logs and unpacked data for OpenedUpdated events raised by the Binding contract. -type BindingOpenedUpdatedIterator struct { - Event *BindingOpenedUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingOpenedUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingOpenedUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingOpenedUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingOpenedUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingOpenedUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingOpenedUpdated represents a OpenedUpdated event raised by the Binding contract. -type BindingOpenedUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOpenedUpdated is a free log retrieval operation binding the contract event 0x26d3ff72bc1fe742dadc405289d851bbaf16c9efcaabfd1e911dd66022097308. -// -// Solidity: event OpenedUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterOpenedUpdated(opts *bind.FilterOpts) (*BindingOpenedUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "OpenedUpdated") - if err != nil { - return nil, err - } - return &BindingOpenedUpdatedIterator{contract: _Binding.contract, event: "OpenedUpdated", logs: logs, sub: sub}, nil -} - -// WatchOpenedUpdated is a free log subscription operation binding the contract event 0x26d3ff72bc1fe742dadc405289d851bbaf16c9efcaabfd1e911dd66022097308. -// -// Solidity: event OpenedUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchOpenedUpdated(opts *bind.WatchOpts, sink chan<- *BindingOpenedUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "OpenedUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingOpenedUpdated) - if err := _Binding.contract.UnpackLog(event, "OpenedUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOpenedUpdated is a log parse operation binding the contract event 0x26d3ff72bc1fe742dadc405289d851bbaf16c9efcaabfd1e911dd66022097308. -// -// Solidity: event OpenedUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseOpenedUpdated(log types.Log) (*BindingOpenedUpdated, error) { - event := new(BindingOpenedUpdated) - if err := _Binding.contract.UnpackLog(event, "OpenedUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Binding contract. -type BindingOwnershipTransferredIterator struct { - Event *BindingOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingOwnershipTransferred represents a OwnershipTransferred event raised by the Binding contract. -type BindingOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*BindingOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &BindingOwnershipTransferredIterator{contract: _Binding.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *BindingOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) ParseOwnershipTransferred(log types.Log) (*BindingOwnershipTransferred, error) { - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingPackOpenedIterator is returned from FilterPackOpened and is used to iterate over the raw logs and unpacked data for PackOpened events raised by the Binding contract. -type BindingPackOpenedIterator struct { - Event *BindingPackOpened // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingPackOpenedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingPackOpened) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingPackOpened) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingPackOpenedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingPackOpenedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingPackOpened represents a PackOpened event raised by the Binding contract. -type BindingPackOpened struct { - User common.Address - RequestId [32]byte - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterPackOpened is a free log retrieval operation binding the contract event 0x5b8ff795b38bcf217c82aab5e970dbee75f066d71d5279afe50e56e0352be74f. -// -// Solidity: event PackOpened(address indexed user, bytes32 requestId, uint256 tokenId) -func (_Binding *BindingFilterer) FilterPackOpened(opts *bind.FilterOpts, user []common.Address) (*BindingPackOpenedIterator, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "PackOpened", userRule) - if err != nil { - return nil, err - } - return &BindingPackOpenedIterator{contract: _Binding.contract, event: "PackOpened", logs: logs, sub: sub}, nil -} - -// WatchPackOpened is a free log subscription operation binding the contract event 0x5b8ff795b38bcf217c82aab5e970dbee75f066d71d5279afe50e56e0352be74f. -// -// Solidity: event PackOpened(address indexed user, bytes32 requestId, uint256 tokenId) -func (_Binding *BindingFilterer) WatchPackOpened(opts *bind.WatchOpts, sink chan<- *BindingPackOpened, user []common.Address) (event.Subscription, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "PackOpened", userRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingPackOpened) - if err := _Binding.contract.UnpackLog(event, "PackOpened", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParsePackOpened is a log parse operation binding the contract event 0x5b8ff795b38bcf217c82aab5e970dbee75f066d71d5279afe50e56e0352be74f. -// -// Solidity: event PackOpened(address indexed user, bytes32 requestId, uint256 tokenId) -func (_Binding *BindingFilterer) ParsePackOpened(log types.Log) (*BindingPackOpened, error) { - event := new(BindingPackOpened) - if err := _Binding.contract.UnpackLog(event, "PackOpened", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingPackRedeemedIterator is returned from FilterPackRedeemed and is used to iterate over the raw logs and unpacked data for PackRedeemed events raised by the Binding contract. -type BindingPackRedeemedIterator struct { - Event *BindingPackRedeemed // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingPackRedeemedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingPackRedeemed) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingPackRedeemed) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingPackRedeemedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingPackRedeemedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingPackRedeemed represents a PackRedeemed event raised by the Binding contract. -type BindingPackRedeemed struct { - User common.Address - TokenId *big.Int - Content *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterPackRedeemed is a free log retrieval operation binding the contract event 0x3bfe8a64824b40e960c91dcea2b5ec9b8eca227bf9406456b954ef3aeb3506c1. -// -// Solidity: event PackRedeemed(address indexed user, uint256 tokenId, uint256 content) -func (_Binding *BindingFilterer) FilterPackRedeemed(opts *bind.FilterOpts, user []common.Address) (*BindingPackRedeemedIterator, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "PackRedeemed", userRule) - if err != nil { - return nil, err - } - return &BindingPackRedeemedIterator{contract: _Binding.contract, event: "PackRedeemed", logs: logs, sub: sub}, nil -} - -// WatchPackRedeemed is a free log subscription operation binding the contract event 0x3bfe8a64824b40e960c91dcea2b5ec9b8eca227bf9406456b954ef3aeb3506c1. -// -// Solidity: event PackRedeemed(address indexed user, uint256 tokenId, uint256 content) -func (_Binding *BindingFilterer) WatchPackRedeemed(opts *bind.WatchOpts, sink chan<- *BindingPackRedeemed, user []common.Address) (event.Subscription, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "PackRedeemed", userRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingPackRedeemed) - if err := _Binding.contract.UnpackLog(event, "PackRedeemed", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParsePackRedeemed is a log parse operation binding the contract event 0x3bfe8a64824b40e960c91dcea2b5ec9b8eca227bf9406456b954ef3aeb3506c1. -// -// Solidity: event PackRedeemed(address indexed user, uint256 tokenId, uint256 content) -func (_Binding *BindingFilterer) ParsePackRedeemed(log types.Log) (*BindingPackRedeemed, error) { - event := new(BindingPackRedeemed) - if err := _Binding.contract.UnpackLog(event, "PackRedeemed", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingPriceUpdatedIterator is returned from FilterPriceUpdated and is used to iterate over the raw logs and unpacked data for PriceUpdated events raised by the Binding contract. -type BindingPriceUpdatedIterator struct { - Event *BindingPriceUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingPriceUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingPriceUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingPriceUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingPriceUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingPriceUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingPriceUpdated represents a PriceUpdated event raised by the Binding contract. -type BindingPriceUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterPriceUpdated is a free log retrieval operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterPriceUpdated(opts *bind.FilterOpts) (*BindingPriceUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "PriceUpdated") - if err != nil { - return nil, err - } - return &BindingPriceUpdatedIterator{contract: _Binding.contract, event: "PriceUpdated", logs: logs, sub: sub}, nil -} - -// WatchPriceUpdated is a free log subscription operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchPriceUpdated(opts *bind.WatchOpts, sink chan<- *BindingPriceUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "PriceUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingPriceUpdated) - if err := _Binding.contract.UnpackLog(event, "PriceUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParsePriceUpdated is a log parse operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParsePriceUpdated(log types.Log) (*BindingPriceUpdated, error) { - event := new(BindingPriceUpdated) - if err := _Binding.contract.UnpackLog(event, "PriceUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingReceiverUpdatedIterator is returned from FilterReceiverUpdated and is used to iterate over the raw logs and unpacked data for ReceiverUpdated events raised by the Binding contract. -type BindingReceiverUpdatedIterator struct { - Event *BindingReceiverUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingReceiverUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingReceiverUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingReceiverUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingReceiverUpdated represents a ReceiverUpdated event raised by the Binding contract. -type BindingReceiverUpdated struct { - Previous common.Address - Updated common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterReceiverUpdated is a free log retrieval operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) FilterReceiverUpdated(opts *bind.FilterOpts) (*BindingReceiverUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return &BindingReceiverUpdatedIterator{contract: _Binding.contract, event: "ReceiverUpdated", logs: logs, sub: sub}, nil -} - -// WatchReceiverUpdated is a free log subscription operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) WatchReceiverUpdated(opts *bind.WatchOpts, sink chan<- *BindingReceiverUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceiverUpdated is a log parse operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) ParseReceiverUpdated(log types.Log) (*BindingReceiverUpdated, error) { - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingRoyaltyUpdatedIterator is returned from FilterRoyaltyUpdated and is used to iterate over the raw logs and unpacked data for RoyaltyUpdated events raised by the Binding contract. -type BindingRoyaltyUpdatedIterator struct { - Event *BindingRoyaltyUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingRoyaltyUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingRoyaltyUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingRoyaltyUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingRoyaltyUpdated represents a RoyaltyUpdated event raised by the Binding contract. -type BindingRoyaltyUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterRoyaltyUpdated is a free log retrieval operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterRoyaltyUpdated(opts *bind.FilterOpts) (*BindingRoyaltyUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return &BindingRoyaltyUpdatedIterator{contract: _Binding.contract, event: "RoyaltyUpdated", logs: logs, sub: sub}, nil -} - -// WatchRoyaltyUpdated is a free log subscription operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchRoyaltyUpdated(opts *bind.WatchOpts, sink chan<- *BindingRoyaltyUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseRoyaltyUpdated is a log parse operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseRoyaltyUpdated(log types.Log) (*BindingRoyaltyUpdated, error) { - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Binding contract. -type BindingTransferIterator struct { - Event *BindingTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingTransfer represents a Transfer event raised by the Binding contract. -type BindingTransfer struct { - From common.Address - To common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address, tokenId []*big.Int) (*BindingTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingTransferIterator{contract: _Binding.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *BindingTransfer, from []common.Address, to []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseTransfer(log types.Log) (*BindingTransfer, error) { - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriFallbackUpdatedIterator is returned from FilterUriFallbackUpdated and is used to iterate over the raw logs and unpacked data for UriFallbackUpdated events raised by the Binding contract. -type BindingUriFallbackUpdatedIterator struct { - Event *BindingUriFallbackUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriFallbackUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriFallbackUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriFallbackUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriFallbackUpdated represents a UriFallbackUpdated event raised by the Binding contract. -type BindingUriFallbackUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriFallbackUpdated is a free log retrieval operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriFallbackUpdated(opts *bind.FilterOpts) (*BindingUriFallbackUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return &BindingUriFallbackUpdatedIterator{contract: _Binding.contract, event: "UriFallbackUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriFallbackUpdated is a free log subscription operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriFallbackUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriFallbackUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriFallbackUpdated is a log parse operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriFallbackUpdated(log types.Log) (*BindingUriFallbackUpdated, error) { - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriUpdatedIterator is returned from FilterUriUpdated and is used to iterate over the raw logs and unpacked data for UriUpdated events raised by the Binding contract. -type BindingUriUpdatedIterator struct { - Event *BindingUriUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriUpdated represents a UriUpdated event raised by the Binding contract. -type BindingUriUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriUpdated is a free log retrieval operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriUpdated(opts *bind.FilterOpts) (*BindingUriUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return &BindingUriUpdatedIterator{contract: _Binding.contract, event: "UriUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriUpdated is a free log subscription operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriUpdated is a log parse operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriUpdated(log types.Log) (*BindingUriUpdated, error) { - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/znft/contracts/dstorageerc721random/binding/dstorageerc721random.go b/znft/contracts/dstorageerc721random/binding/dstorageerc721random.go deleted file mode 100644 index 00e3a63ff..000000000 --- a/znft/contracts/dstorageerc721random/binding/dstorageerc721random.go +++ /dev/null @@ -1,3925 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// DStorageERC721RandomVRFConfig is an auto generated low-level Go binding around an user-defined struct. -type DStorageERC721RandomVRFConfig struct { - Coordinator common.Address - Link common.Address - Keyhash [32]byte - Fee *big.Int -} - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max_\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"price_\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"batch_\",\"type\":\"uint256\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"coordinator\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"link\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"keyhash\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"fee\",\"type\":\"uint256\"}],\"internalType\":\"structDStorageERC721Random.VRFConfig\",\"name\":\"vrf_\",\"type\":\"tuple\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"BatchUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"HiddenUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"}],\"name\":\"MetadataFrozen\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"previous\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"updated\",\"type\":\"bool\"}],\"name\":\"MintableUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previous\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"updated\",\"type\":\"address\"}],\"name\":\"PackUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"PriceUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previous\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"updated\",\"type\":\"address\"}],\"name\":\"ReceiverUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"previous\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"updated\",\"type\":\"bool\"}],\"name\":\"RevealableUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"RoyaltyUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"user\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"requestId\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256[]\",\"name\":\"tokens\",\"type\":\"uint256[]\"}],\"name\":\"TokenReveal\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriFallbackUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"previous\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"string\",\"name\":\"updated\",\"type\":\"string\"}],\"name\":\"UriUpdated\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"allocation\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"batch\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"freeze\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"frozen\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"hidden\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"max\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mintOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mintable\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"order\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pack\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pending\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"price\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"randomness\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"requestId\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"randomness\",\"type\":\"uint256\"}],\"name\":\"rawFulfillRandomness\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"receiver\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256[]\",\"name\":\"tokens\",\"type\":\"uint256[]\"}],\"name\":\"reveal\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"revealable\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"revealed\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"royalty\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"salePrice\",\"type\":\"uint256\"}],\"name\":\"royaltyInfo\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"allocation_\",\"type\":\"string\"}],\"name\":\"setAllocation\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"hidden_\",\"type\":\"string\"}],\"name\":\"setHidden\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status_\",\"type\":\"bool\"}],\"name\":\"setMintable\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"pack_\",\"type\":\"address\"}],\"name\":\"setPack\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver_\",\"type\":\"address\"}],\"name\":\"setReceiver\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status_\",\"type\":\"bool\"}],\"name\":\"setRevealable\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"royalty_\",\"type\":\"uint256\"}],\"name\":\"setRoyalty\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURI\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"uri_\",\"type\":\"string\"}],\"name\":\"setURIFallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"shuffle\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURIFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"total\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"update\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uri\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"uriFallback\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"vrfFee\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"vrfKeyHash\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCaller) Allocation(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "allocation") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// Allocation is a free data retrieval call binding the contract method 0x88a17bde. -// -// Solidity: function allocation() view returns(string) -func (_Binding *BindingCallerSession) Allocation() (string, error) { - return _Binding.Contract.Allocation(&_Binding.CallOpts) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "balanceOf", owner) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address owner) view returns(uint256) -func (_Binding *BindingCallerSession) BalanceOf(owner common.Address) (*big.Int, error) { - return _Binding.Contract.BalanceOf(&_Binding.CallOpts, owner) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCaller) Batch(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "batch") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Batch is a free data retrieval call binding the contract method 0xaf713566. -// -// Solidity: function batch() view returns(uint256) -func (_Binding *BindingCallerSession) Batch() (*big.Int, error) { - return _Binding.Contract.Batch(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCaller) Frozen(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "frozen") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// Frozen is a free data retrieval call binding the contract method 0x054f7d9c. -// -// Solidity: function frozen() view returns(bool) -func (_Binding *BindingCallerSession) Frozen() (bool, error) { - return _Binding.Contract.Frozen(&_Binding.CallOpts) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) GetApproved(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "getApproved", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// GetApproved is a free data retrieval call binding the contract method 0x081812fc. -// -// Solidity: function getApproved(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) GetApproved(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.GetApproved(&_Binding.CallOpts, tokenId) -} - -// Hidden is a free data retrieval call binding the contract method 0xaef6d4b1. -// -// Solidity: function hidden() view returns(string) -func (_Binding *BindingCaller) Hidden(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "hidden") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Hidden is a free data retrieval call binding the contract method 0xaef6d4b1. -// -// Solidity: function hidden() view returns(string) -func (_Binding *BindingSession) Hidden() (string, error) { - return _Binding.Contract.Hidden(&_Binding.CallOpts) -} - -// Hidden is a free data retrieval call binding the contract method 0xaef6d4b1. -// -// Solidity: function hidden() view returns(string) -func (_Binding *BindingCallerSession) Hidden() (string, error) { - return _Binding.Contract.Hidden(&_Binding.CallOpts) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCaller) IsApprovedForAll(opts *bind.CallOpts, owner common.Address, operator common.Address) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "isApprovedForAll", owner, operator) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5. -// -// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool) -func (_Binding *BindingCallerSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) { - return _Binding.Contract.IsApprovedForAll(&_Binding.CallOpts, owner, operator) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCaller) Max(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "max") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Max is a free data retrieval call binding the contract method 0x6ac5db19. -// -// Solidity: function max() view returns(uint256) -func (_Binding *BindingCallerSession) Max() (*big.Int, error) { - return _Binding.Contract.Max(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCaller) Mintable(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "mintable") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Mintable is a free data retrieval call binding the contract method 0x4bf365df. -// -// Solidity: function mintable() view returns(bool) -func (_Binding *BindingCallerSession) Mintable() (bool, error) { - return _Binding.Contract.Mintable(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_Binding *BindingCallerSession) Name() (string, error) { - return _Binding.Contract.Name(&_Binding.CallOpts) -} - -// Order is a free data retrieval call binding the contract method 0x21603f43. -// -// Solidity: function order(uint256 ) view returns(uint256) -func (_Binding *BindingCaller) Order(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "order", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Order is a free data retrieval call binding the contract method 0x21603f43. -// -// Solidity: function order(uint256 ) view returns(uint256) -func (_Binding *BindingSession) Order(arg0 *big.Int) (*big.Int, error) { - return _Binding.Contract.Order(&_Binding.CallOpts, arg0) -} - -// Order is a free data retrieval call binding the contract method 0x21603f43. -// -// Solidity: function order(uint256 ) view returns(uint256) -func (_Binding *BindingCallerSession) Order(arg0 *big.Int) (*big.Int, error) { - return _Binding.Contract.Order(&_Binding.CallOpts, arg0) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCallerSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCaller) OwnerOf(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "ownerOf", tokenId) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// OwnerOf is a free data retrieval call binding the contract method 0x6352211e. -// -// Solidity: function ownerOf(uint256 tokenId) view returns(address) -func (_Binding *BindingCallerSession) OwnerOf(tokenId *big.Int) (common.Address, error) { - return _Binding.Contract.OwnerOf(&_Binding.CallOpts, tokenId) -} - -// Pack is a free data retrieval call binding the contract method 0xef082838. -// -// Solidity: function pack() view returns(address) -func (_Binding *BindingCaller) Pack(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "pack") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Pack is a free data retrieval call binding the contract method 0xef082838. -// -// Solidity: function pack() view returns(address) -func (_Binding *BindingSession) Pack() (common.Address, error) { - return _Binding.Contract.Pack(&_Binding.CallOpts) -} - -// Pack is a free data retrieval call binding the contract method 0xef082838. -// -// Solidity: function pack() view returns(address) -func (_Binding *BindingCallerSession) Pack() (common.Address, error) { - return _Binding.Contract.Pack(&_Binding.CallOpts) -} - -// Pending is a free data retrieval call binding the contract method 0xe20ccec3. -// -// Solidity: function pending() view returns(uint256) -func (_Binding *BindingCaller) Pending(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "pending") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Pending is a free data retrieval call binding the contract method 0xe20ccec3. -// -// Solidity: function pending() view returns(uint256) -func (_Binding *BindingSession) Pending() (*big.Int, error) { - return _Binding.Contract.Pending(&_Binding.CallOpts) -} - -// Pending is a free data retrieval call binding the contract method 0xe20ccec3. -// -// Solidity: function pending() view returns(uint256) -func (_Binding *BindingCallerSession) Pending() (*big.Int, error) { - return _Binding.Contract.Pending(&_Binding.CallOpts) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCaller) Price(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "price") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Price is a free data retrieval call binding the contract method 0xa035b1fe. -// -// Solidity: function price() view returns(uint256) -func (_Binding *BindingCallerSession) Price() (*big.Int, error) { - return _Binding.Contract.Price(&_Binding.CallOpts) -} - -// Randomness is a free data retrieval call binding the contract method 0x36013189. -// -// Solidity: function randomness() view returns(uint256) -func (_Binding *BindingCaller) Randomness(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "randomness") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Randomness is a free data retrieval call binding the contract method 0x36013189. -// -// Solidity: function randomness() view returns(uint256) -func (_Binding *BindingSession) Randomness() (*big.Int, error) { - return _Binding.Contract.Randomness(&_Binding.CallOpts) -} - -// Randomness is a free data retrieval call binding the contract method 0x36013189. -// -// Solidity: function randomness() view returns(uint256) -func (_Binding *BindingCallerSession) Randomness() (*big.Int, error) { - return _Binding.Contract.Randomness(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCaller) Receiver(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "receiver") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Receiver is a free data retrieval call binding the contract method 0xf7260d3e. -// -// Solidity: function receiver() view returns(address) -func (_Binding *BindingCallerSession) Receiver() (common.Address, error) { - return _Binding.Contract.Receiver(&_Binding.CallOpts) -} - -// Revealable is a free data retrieval call binding the contract method 0x03d16985. -// -// Solidity: function revealable() view returns(bool) -func (_Binding *BindingCaller) Revealable(opts *bind.CallOpts) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "revealable") - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// Revealable is a free data retrieval call binding the contract method 0x03d16985. -// -// Solidity: function revealable() view returns(bool) -func (_Binding *BindingSession) Revealable() (bool, error) { - return _Binding.Contract.Revealable(&_Binding.CallOpts) -} - -// Revealable is a free data retrieval call binding the contract method 0x03d16985. -// -// Solidity: function revealable() view returns(bool) -func (_Binding *BindingCallerSession) Revealable() (bool, error) { - return _Binding.Contract.Revealable(&_Binding.CallOpts) -} - -// Revealed is a free data retrieval call binding the contract method 0x51830227. -// -// Solidity: function revealed() view returns(uint256) -func (_Binding *BindingCaller) Revealed(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "revealed") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Revealed is a free data retrieval call binding the contract method 0x51830227. -// -// Solidity: function revealed() view returns(uint256) -func (_Binding *BindingSession) Revealed() (*big.Int, error) { - return _Binding.Contract.Revealed(&_Binding.CallOpts) -} - -// Revealed is a free data retrieval call binding the contract method 0x51830227. -// -// Solidity: function revealed() view returns(uint256) -func (_Binding *BindingCallerSession) Revealed() (*big.Int, error) { - return _Binding.Contract.Revealed(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCaller) Royalty(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royalty") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// Royalty is a free data retrieval call binding the contract method 0x29ee566c. -// -// Solidity: function royalty() view returns(uint256) -func (_Binding *BindingCallerSession) Royalty() (*big.Int, error) { - return _Binding.Contract.Royalty(&_Binding.CallOpts) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCaller) RoyaltyInfo(opts *bind.CallOpts, tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "royaltyInfo", tokenId, salePrice) - - if err != nil { - return *new(common.Address), *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) - - return out0, out1, err - -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// RoyaltyInfo is a free data retrieval call binding the contract method 0x2a55205a. -// -// Solidity: function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns(address, uint256) -func (_Binding *BindingCallerSession) RoyaltyInfo(tokenId *big.Int, salePrice *big.Int) (common.Address, *big.Int, error) { - return _Binding.Contract.RoyaltyInfo(&_Binding.CallOpts, tokenId, salePrice) -} - -// Shuffle is a free data retrieval call binding the contract method 0xef6537b5. -// -// Solidity: function shuffle(uint256 ) view returns(uint256) -func (_Binding *BindingCaller) Shuffle(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "shuffle", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Shuffle is a free data retrieval call binding the contract method 0xef6537b5. -// -// Solidity: function shuffle(uint256 ) view returns(uint256) -func (_Binding *BindingSession) Shuffle(arg0 *big.Int) (*big.Int, error) { - return _Binding.Contract.Shuffle(&_Binding.CallOpts, arg0) -} - -// Shuffle is a free data retrieval call binding the contract method 0xef6537b5. -// -// Solidity: function shuffle(uint256 ) view returns(uint256) -func (_Binding *BindingCallerSession) Shuffle(arg0 *big.Int) (*big.Int, error) { - return _Binding.Contract.Shuffle(&_Binding.CallOpts, arg0) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "supportsInterface", interfaceId) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. -// -// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) -func (_Binding *BindingCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { - return _Binding.Contract.SupportsInterface(&_Binding.CallOpts, interfaceId) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_Binding *BindingCallerSession) Symbol() (string, error) { - return _Binding.Contract.Symbol(&_Binding.CallOpts) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURI(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURI", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd. -// -// Solidity: function tokenURI(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURI(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURI(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCaller) TokenURIFallback(opts *bind.CallOpts, tokenId *big.Int) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenURIFallback", tokenId) - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// TokenURIFallback is a free data retrieval call binding the contract method 0xc7c8f564. -// -// Solidity: function tokenURIFallback(uint256 tokenId) view returns(string) -func (_Binding *BindingCallerSession) TokenURIFallback(tokenId *big.Int) (string, error) { - return _Binding.Contract.TokenURIFallback(&_Binding.CallOpts, tokenId) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCaller) Total(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "total") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Total is a free data retrieval call binding the contract method 0x2ddbd13a. -// -// Solidity: function total() view returns(uint256) -func (_Binding *BindingCallerSession) Total() (*big.Int, error) { - return _Binding.Contract.Total(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCaller) Uri(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uri") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// Uri is a free data retrieval call binding the contract method 0xeac989f8. -// -// Solidity: function uri() view returns(string) -func (_Binding *BindingCallerSession) Uri() (string, error) { - return _Binding.Contract.Uri(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCaller) UriFallback(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "uriFallback") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// UriFallback is a free data retrieval call binding the contract method 0x6dd8e21a. -// -// Solidity: function uriFallback() view returns(string) -func (_Binding *BindingCallerSession) UriFallback() (string, error) { - return _Binding.Contract.UriFallback(&_Binding.CallOpts) -} - -// VrfFee is a free data retrieval call binding the contract method 0x1017507d. -// -// Solidity: function vrfFee() view returns(uint256) -func (_Binding *BindingCaller) VrfFee(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "vrfFee") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// VrfFee is a free data retrieval call binding the contract method 0x1017507d. -// -// Solidity: function vrfFee() view returns(uint256) -func (_Binding *BindingSession) VrfFee() (*big.Int, error) { - return _Binding.Contract.VrfFee(&_Binding.CallOpts) -} - -// VrfFee is a free data retrieval call binding the contract method 0x1017507d. -// -// Solidity: function vrfFee() view returns(uint256) -func (_Binding *BindingCallerSession) VrfFee() (*big.Int, error) { - return _Binding.Contract.VrfFee(&_Binding.CallOpts) -} - -// VrfKeyHash is a free data retrieval call binding the contract method 0x041d443e. -// -// Solidity: function vrfKeyHash() view returns(bytes32) -func (_Binding *BindingCaller) VrfKeyHash(opts *bind.CallOpts) ([32]byte, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "vrfKeyHash") - - if err != nil { - return *new([32]byte), err - } - - out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) - - return out0, err - -} - -// VrfKeyHash is a free data retrieval call binding the contract method 0x041d443e. -// -// Solidity: function vrfKeyHash() view returns(bytes32) -func (_Binding *BindingSession) VrfKeyHash() ([32]byte, error) { - return _Binding.Contract.VrfKeyHash(&_Binding.CallOpts) -} - -// VrfKeyHash is a free data retrieval call binding the contract method 0x041d443e. -// -// Solidity: function vrfKeyHash() view returns(bytes32) -func (_Binding *BindingCallerSession) VrfKeyHash() ([32]byte, error) { - return _Binding.Contract.VrfKeyHash(&_Binding.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) Approve(opts *bind.TransactOpts, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "approve", to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Approve(&_Binding.TransactOpts, to, tokenId) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactor) Freeze(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "freeze") -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Freeze is a paid mutator transaction binding the contract method 0x62a5af3b. -// -// Solidity: function freeze() returns() -func (_Binding *BindingTransactorSession) Freeze() (*types.Transaction, error) { - return _Binding.Contract.Freeze(&_Binding.TransactOpts) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactor) Mint(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mint", amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// Mint is a paid mutator transaction binding the contract method 0xa0712d68. -// -// Solidity: function mint(uint256 amount) payable returns() -func (_Binding *BindingTransactorSession) Mint(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.Mint(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactor) MintOwner(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "mintOwner", amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// MintOwner is a paid mutator transaction binding the contract method 0x33f88d22. -// -// Solidity: function mintOwner(uint256 amount) returns() -func (_Binding *BindingTransactorSession) MintOwner(amount *big.Int) (*types.Transaction, error) { - return _Binding.Contract.MintOwner(&_Binding.TransactOpts, amount) -} - -// RawFulfillRandomness is a paid mutator transaction binding the contract method 0x94985ddd. -// -// Solidity: function rawFulfillRandomness(bytes32 requestId, uint256 randomness) returns() -func (_Binding *BindingTransactor) RawFulfillRandomness(opts *bind.TransactOpts, requestId [32]byte, randomness *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "rawFulfillRandomness", requestId, randomness) -} - -// RawFulfillRandomness is a paid mutator transaction binding the contract method 0x94985ddd. -// -// Solidity: function rawFulfillRandomness(bytes32 requestId, uint256 randomness) returns() -func (_Binding *BindingSession) RawFulfillRandomness(requestId [32]byte, randomness *big.Int) (*types.Transaction, error) { - return _Binding.Contract.RawFulfillRandomness(&_Binding.TransactOpts, requestId, randomness) -} - -// RawFulfillRandomness is a paid mutator transaction binding the contract method 0x94985ddd. -// -// Solidity: function rawFulfillRandomness(bytes32 requestId, uint256 randomness) returns() -func (_Binding *BindingTransactorSession) RawFulfillRandomness(requestId [32]byte, randomness *big.Int) (*types.Transaction, error) { - return _Binding.Contract.RawFulfillRandomness(&_Binding.TransactOpts, requestId, randomness) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// Reveal is a paid mutator transaction binding the contract method 0xb93f208a. -// -// Solidity: function reveal(uint256[] tokens) returns(bytes32) -func (_Binding *BindingTransactor) Reveal(opts *bind.TransactOpts, tokens []*big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "reveal", tokens) -} - -// Reveal is a paid mutator transaction binding the contract method 0xb93f208a. -// -// Solidity: function reveal(uint256[] tokens) returns(bytes32) -func (_Binding *BindingSession) Reveal(tokens []*big.Int) (*types.Transaction, error) { - return _Binding.Contract.Reveal(&_Binding.TransactOpts, tokens) -} - -// Reveal is a paid mutator transaction binding the contract method 0xb93f208a. -// -// Solidity: function reveal(uint256[] tokens) returns(bytes32) -func (_Binding *BindingTransactorSession) Reveal(tokens []*big.Int) (*types.Transaction, error) { - return _Binding.Contract.Reveal(&_Binding.TransactOpts, tokens) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom", from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactor) SafeTransferFrom0(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "safeTransferFrom0", from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde. -// -// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns() -func (_Binding *BindingTransactorSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) { - return _Binding.Contract.SafeTransferFrom0(&_Binding.TransactOpts, from, to, tokenId, _data) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactor) SetAllocation(opts *bind.TransactOpts, allocation_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setAllocation", allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetAllocation is a paid mutator transaction binding the contract method 0x970a1fa8. -// -// Solidity: function setAllocation(string allocation_) returns() -func (_Binding *BindingTransactorSession) SetAllocation(allocation_ string) (*types.Transaction, error) { - return _Binding.Contract.SetAllocation(&_Binding.TransactOpts, allocation_) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactor) SetApprovalForAll(opts *bind.TransactOpts, operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setApprovalForAll", operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465. -// -// Solidity: function setApprovalForAll(address operator, bool approved) returns() -func (_Binding *BindingTransactorSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) { - return _Binding.Contract.SetApprovalForAll(&_Binding.TransactOpts, operator, approved) -} - -// SetHidden is a paid mutator transaction binding the contract method 0xd309aa2c. -// -// Solidity: function setHidden(string hidden_) returns() -func (_Binding *BindingTransactor) SetHidden(opts *bind.TransactOpts, hidden_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setHidden", hidden_) -} - -// SetHidden is a paid mutator transaction binding the contract method 0xd309aa2c. -// -// Solidity: function setHidden(string hidden_) returns() -func (_Binding *BindingSession) SetHidden(hidden_ string) (*types.Transaction, error) { - return _Binding.Contract.SetHidden(&_Binding.TransactOpts, hidden_) -} - -// SetHidden is a paid mutator transaction binding the contract method 0xd309aa2c. -// -// Solidity: function setHidden(string hidden_) returns() -func (_Binding *BindingTransactorSession) SetHidden(hidden_ string) (*types.Transaction, error) { - return _Binding.Contract.SetHidden(&_Binding.TransactOpts, hidden_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactor) SetMintable(opts *bind.TransactOpts, status_ bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setMintable", status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetMintable is a paid mutator transaction binding the contract method 0x285d70d4. -// -// Solidity: function setMintable(bool status_) returns() -func (_Binding *BindingTransactorSession) SetMintable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetMintable(&_Binding.TransactOpts, status_) -} - -// SetPack is a paid mutator transaction binding the contract method 0x353c65c5. -// -// Solidity: function setPack(address pack_) returns() -func (_Binding *BindingTransactor) SetPack(opts *bind.TransactOpts, pack_ common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setPack", pack_) -} - -// SetPack is a paid mutator transaction binding the contract method 0x353c65c5. -// -// Solidity: function setPack(address pack_) returns() -func (_Binding *BindingSession) SetPack(pack_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetPack(&_Binding.TransactOpts, pack_) -} - -// SetPack is a paid mutator transaction binding the contract method 0x353c65c5. -// -// Solidity: function setPack(address pack_) returns() -func (_Binding *BindingTransactorSession) SetPack(pack_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetPack(&_Binding.TransactOpts, pack_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactor) SetReceiver(opts *bind.TransactOpts, receiver_ common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setReceiver", receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetReceiver is a paid mutator transaction binding the contract method 0x718da7ee. -// -// Solidity: function setReceiver(address receiver_) returns() -func (_Binding *BindingTransactorSession) SetReceiver(receiver_ common.Address) (*types.Transaction, error) { - return _Binding.Contract.SetReceiver(&_Binding.TransactOpts, receiver_) -} - -// SetRevealable is a paid mutator transaction binding the contract method 0xb06194d3. -// -// Solidity: function setRevealable(bool status_) returns() -func (_Binding *BindingTransactor) SetRevealable(opts *bind.TransactOpts, status_ bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setRevealable", status_) -} - -// SetRevealable is a paid mutator transaction binding the contract method 0xb06194d3. -// -// Solidity: function setRevealable(bool status_) returns() -func (_Binding *BindingSession) SetRevealable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetRevealable(&_Binding.TransactOpts, status_) -} - -// SetRevealable is a paid mutator transaction binding the contract method 0xb06194d3. -// -// Solidity: function setRevealable(bool status_) returns() -func (_Binding *BindingTransactorSession) SetRevealable(status_ bool) (*types.Transaction, error) { - return _Binding.Contract.SetRevealable(&_Binding.TransactOpts, status_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactor) SetRoyalty(opts *bind.TransactOpts, royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setRoyalty", royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetRoyalty is a paid mutator transaction binding the contract method 0x4209a2e1. -// -// Solidity: function setRoyalty(uint256 royalty_) returns() -func (_Binding *BindingTransactorSession) SetRoyalty(royalty_ *big.Int) (*types.Transaction, error) { - return _Binding.Contract.SetRoyalty(&_Binding.TransactOpts, royalty_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactor) SetURI(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURI", uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURI is a paid mutator transaction binding the contract method 0x02fe5305. -// -// Solidity: function setURI(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURI(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURI(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactor) SetURIFallback(opts *bind.TransactOpts, uri_ string) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "setURIFallback", uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// SetURIFallback is a paid mutator transaction binding the contract method 0x0c8ab6e1. -// -// Solidity: function setURIFallback(string uri_) returns() -func (_Binding *BindingTransactorSession) SetURIFallback(uri_ string) (*types.Transaction, error) { - return _Binding.Contract.SetURIFallback(&_Binding.TransactOpts, uri_) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferFrom", from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns() -func (_Binding *BindingTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) { - return _Binding.Contract.TransferFrom(&_Binding.TransactOpts, from, to, tokenId) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// Update is a paid mutator transaction binding the contract method 0xa2e62045. -// -// Solidity: function update() returns() -func (_Binding *BindingTransactor) Update(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "update") -} - -// Update is a paid mutator transaction binding the contract method 0xa2e62045. -// -// Solidity: function update() returns() -func (_Binding *BindingSession) Update() (*types.Transaction, error) { - return _Binding.Contract.Update(&_Binding.TransactOpts) -} - -// Update is a paid mutator transaction binding the contract method 0xa2e62045. -// -// Solidity: function update() returns() -func (_Binding *BindingTransactorSession) Update() (*types.Transaction, error) { - return _Binding.Contract.Update(&_Binding.TransactOpts) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "withdraw") -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b. -// -// Solidity: function withdraw() returns() -func (_Binding *BindingTransactorSession) Withdraw() (*types.Transaction, error) { - return _Binding.Contract.Withdraw(&_Binding.TransactOpts) -} - -// BindingApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Binding contract. -type BindingApprovalIterator struct { - Event *BindingApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApproval represents a Approval event raised by the Binding contract. -type BindingApproval struct { - Owner common.Address - Approved common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, approved []common.Address, tokenId []*big.Int) (*BindingApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingApprovalIterator{contract: _Binding.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *BindingApproval, owner []common.Address, approved []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var approvedRule []interface{} - for _, approvedItem := range approved { - approvedRule = append(approvedRule, approvedItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseApproval(log types.Log) (*BindingApproval, error) { - event := new(BindingApproval) - if err := _Binding.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingApprovalForAllIterator is returned from FilterApprovalForAll and is used to iterate over the raw logs and unpacked data for ApprovalForAll events raised by the Binding contract. -type BindingApprovalForAllIterator struct { - Event *BindingApprovalForAll // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingApprovalForAllIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingApprovalForAll) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingApprovalForAllIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingApprovalForAllIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingApprovalForAll represents a ApprovalForAll event raised by the Binding contract. -type BindingApprovalForAll struct { - Owner common.Address - Operator common.Address - Approved bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApprovalForAll is a free log retrieval operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) FilterApprovalForAll(opts *bind.FilterOpts, owner []common.Address, operator []common.Address) (*BindingApprovalForAllIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return &BindingApprovalForAllIterator{contract: _Binding.contract, event: "ApprovalForAll", logs: logs, sub: sub}, nil -} - -// WatchApprovalForAll is a free log subscription operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) WatchApprovalForAll(opts *bind.WatchOpts, sink chan<- *BindingApprovalForAll, owner []common.Address, operator []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var operatorRule []interface{} - for _, operatorItem := range operator { - operatorRule = append(operatorRule, operatorItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ApprovalForAll", ownerRule, operatorRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApprovalForAll is a log parse operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31. -// -// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved) -func (_Binding *BindingFilterer) ParseApprovalForAll(log types.Log) (*BindingApprovalForAll, error) { - event := new(BindingApprovalForAll) - if err := _Binding.contract.UnpackLog(event, "ApprovalForAll", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingBatchUpdatedIterator is returned from FilterBatchUpdated and is used to iterate over the raw logs and unpacked data for BatchUpdated events raised by the Binding contract. -type BindingBatchUpdatedIterator struct { - Event *BindingBatchUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingBatchUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingBatchUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingBatchUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingBatchUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingBatchUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingBatchUpdated represents a BatchUpdated event raised by the Binding contract. -type BindingBatchUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterBatchUpdated is a free log retrieval operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterBatchUpdated(opts *bind.FilterOpts) (*BindingBatchUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "BatchUpdated") - if err != nil { - return nil, err - } - return &BindingBatchUpdatedIterator{contract: _Binding.contract, event: "BatchUpdated", logs: logs, sub: sub}, nil -} - -// WatchBatchUpdated is a free log subscription operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchBatchUpdated(opts *bind.WatchOpts, sink chan<- *BindingBatchUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "BatchUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingBatchUpdated) - if err := _Binding.contract.UnpackLog(event, "BatchUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseBatchUpdated is a log parse operation binding the contract event 0x656359bd8624a98c9559c454e7835a5e93f0867eacab61bfda9d2d0fce4e3097. -// -// Solidity: event BatchUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseBatchUpdated(log types.Log) (*BindingBatchUpdated, error) { - event := new(BindingBatchUpdated) - if err := _Binding.contract.UnpackLog(event, "BatchUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingHiddenUpdatedIterator is returned from FilterHiddenUpdated and is used to iterate over the raw logs and unpacked data for HiddenUpdated events raised by the Binding contract. -type BindingHiddenUpdatedIterator struct { - Event *BindingHiddenUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingHiddenUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingHiddenUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingHiddenUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingHiddenUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingHiddenUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingHiddenUpdated represents a HiddenUpdated event raised by the Binding contract. -type BindingHiddenUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterHiddenUpdated is a free log retrieval operation binding the contract event 0x57189fe32dda35d8b092ccd5a7d65eeecb46be25ce11a28ad02b5b0d3f662505. -// -// Solidity: event HiddenUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterHiddenUpdated(opts *bind.FilterOpts) (*BindingHiddenUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "HiddenUpdated") - if err != nil { - return nil, err - } - return &BindingHiddenUpdatedIterator{contract: _Binding.contract, event: "HiddenUpdated", logs: logs, sub: sub}, nil -} - -// WatchHiddenUpdated is a free log subscription operation binding the contract event 0x57189fe32dda35d8b092ccd5a7d65eeecb46be25ce11a28ad02b5b0d3f662505. -// -// Solidity: event HiddenUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchHiddenUpdated(opts *bind.WatchOpts, sink chan<- *BindingHiddenUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "HiddenUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingHiddenUpdated) - if err := _Binding.contract.UnpackLog(event, "HiddenUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseHiddenUpdated is a log parse operation binding the contract event 0x57189fe32dda35d8b092ccd5a7d65eeecb46be25ce11a28ad02b5b0d3f662505. -// -// Solidity: event HiddenUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseHiddenUpdated(log types.Log) (*BindingHiddenUpdated, error) { - event := new(BindingHiddenUpdated) - if err := _Binding.contract.UnpackLog(event, "HiddenUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMetadataFrozenIterator is returned from FilterMetadataFrozen and is used to iterate over the raw logs and unpacked data for MetadataFrozen events raised by the Binding contract. -type BindingMetadataFrozenIterator struct { - Event *BindingMetadataFrozen // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMetadataFrozenIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMetadataFrozen) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMetadataFrozenIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMetadataFrozenIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMetadataFrozen represents a MetadataFrozen event raised by the Binding contract. -type BindingMetadataFrozen struct { - Uri string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMetadataFrozen is a free log retrieval operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) FilterMetadataFrozen(opts *bind.FilterOpts) (*BindingMetadataFrozenIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return &BindingMetadataFrozenIterator{contract: _Binding.contract, event: "MetadataFrozen", logs: logs, sub: sub}, nil -} - -// WatchMetadataFrozen is a free log subscription operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) WatchMetadataFrozen(opts *bind.WatchOpts, sink chan<- *BindingMetadataFrozen) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MetadataFrozen") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMetadataFrozen is a log parse operation binding the contract event 0xac32328134cd103aa01cccc8f61d479f9613e7f9c1de6bfc70c78412b15c18e3. -// -// Solidity: event MetadataFrozen(string uri) -func (_Binding *BindingFilterer) ParseMetadataFrozen(log types.Log) (*BindingMetadataFrozen, error) { - event := new(BindingMetadataFrozen) - if err := _Binding.contract.UnpackLog(event, "MetadataFrozen", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingMintableUpdatedIterator is returned from FilterMintableUpdated and is used to iterate over the raw logs and unpacked data for MintableUpdated events raised by the Binding contract. -type BindingMintableUpdatedIterator struct { - Event *BindingMintableUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingMintableUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingMintableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingMintableUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingMintableUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingMintableUpdated represents a MintableUpdated event raised by the Binding contract. -type BindingMintableUpdated struct { - Previous bool - Updated bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterMintableUpdated is a free log retrieval operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) FilterMintableUpdated(opts *bind.FilterOpts) (*BindingMintableUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return &BindingMintableUpdatedIterator{contract: _Binding.contract, event: "MintableUpdated", logs: logs, sub: sub}, nil -} - -// WatchMintableUpdated is a free log subscription operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) WatchMintableUpdated(opts *bind.WatchOpts, sink chan<- *BindingMintableUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "MintableUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMintableUpdated is a log parse operation binding the contract event 0x8d9383d773c0600295154578f39da3106938ba8d1fe1767bcfabe8bf05f555f4. -// -// Solidity: event MintableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) ParseMintableUpdated(log types.Log) (*BindingMintableUpdated, error) { - event := new(BindingMintableUpdated) - if err := _Binding.contract.UnpackLog(event, "MintableUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Binding contract. -type BindingOwnershipTransferredIterator struct { - Event *BindingOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingOwnershipTransferred represents a OwnershipTransferred event raised by the Binding contract. -type BindingOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*BindingOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &BindingOwnershipTransferredIterator{contract: _Binding.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *BindingOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) ParseOwnershipTransferred(log types.Log) (*BindingOwnershipTransferred, error) { - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingPackUpdatedIterator is returned from FilterPackUpdated and is used to iterate over the raw logs and unpacked data for PackUpdated events raised by the Binding contract. -type BindingPackUpdatedIterator struct { - Event *BindingPackUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingPackUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingPackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingPackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingPackUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingPackUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingPackUpdated represents a PackUpdated event raised by the Binding contract. -type BindingPackUpdated struct { - Previous common.Address - Updated common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterPackUpdated is a free log retrieval operation binding the contract event 0x69c956910dd41d384c8eaa85a91003a538ae5d5ceb57ae4e530072e3908b10f4. -// -// Solidity: event PackUpdated(address previous, address updated) -func (_Binding *BindingFilterer) FilterPackUpdated(opts *bind.FilterOpts) (*BindingPackUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "PackUpdated") - if err != nil { - return nil, err - } - return &BindingPackUpdatedIterator{contract: _Binding.contract, event: "PackUpdated", logs: logs, sub: sub}, nil -} - -// WatchPackUpdated is a free log subscription operation binding the contract event 0x69c956910dd41d384c8eaa85a91003a538ae5d5ceb57ae4e530072e3908b10f4. -// -// Solidity: event PackUpdated(address previous, address updated) -func (_Binding *BindingFilterer) WatchPackUpdated(opts *bind.WatchOpts, sink chan<- *BindingPackUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "PackUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingPackUpdated) - if err := _Binding.contract.UnpackLog(event, "PackUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParsePackUpdated is a log parse operation binding the contract event 0x69c956910dd41d384c8eaa85a91003a538ae5d5ceb57ae4e530072e3908b10f4. -// -// Solidity: event PackUpdated(address previous, address updated) -func (_Binding *BindingFilterer) ParsePackUpdated(log types.Log) (*BindingPackUpdated, error) { - event := new(BindingPackUpdated) - if err := _Binding.contract.UnpackLog(event, "PackUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingPriceUpdatedIterator is returned from FilterPriceUpdated and is used to iterate over the raw logs and unpacked data for PriceUpdated events raised by the Binding contract. -type BindingPriceUpdatedIterator struct { - Event *BindingPriceUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingPriceUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingPriceUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingPriceUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingPriceUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingPriceUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingPriceUpdated represents a PriceUpdated event raised by the Binding contract. -type BindingPriceUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterPriceUpdated is a free log retrieval operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterPriceUpdated(opts *bind.FilterOpts) (*BindingPriceUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "PriceUpdated") - if err != nil { - return nil, err - } - return &BindingPriceUpdatedIterator{contract: _Binding.contract, event: "PriceUpdated", logs: logs, sub: sub}, nil -} - -// WatchPriceUpdated is a free log subscription operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchPriceUpdated(opts *bind.WatchOpts, sink chan<- *BindingPriceUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "PriceUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingPriceUpdated) - if err := _Binding.contract.UnpackLog(event, "PriceUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParsePriceUpdated is a log parse operation binding the contract event 0x945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838. -// -// Solidity: event PriceUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParsePriceUpdated(log types.Log) (*BindingPriceUpdated, error) { - event := new(BindingPriceUpdated) - if err := _Binding.contract.UnpackLog(event, "PriceUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingReceiverUpdatedIterator is returned from FilterReceiverUpdated and is used to iterate over the raw logs and unpacked data for ReceiverUpdated events raised by the Binding contract. -type BindingReceiverUpdatedIterator struct { - Event *BindingReceiverUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingReceiverUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingReceiverUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingReceiverUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingReceiverUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingReceiverUpdated represents a ReceiverUpdated event raised by the Binding contract. -type BindingReceiverUpdated struct { - Previous common.Address - Updated common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterReceiverUpdated is a free log retrieval operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) FilterReceiverUpdated(opts *bind.FilterOpts) (*BindingReceiverUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return &BindingReceiverUpdatedIterator{contract: _Binding.contract, event: "ReceiverUpdated", logs: logs, sub: sub}, nil -} - -// WatchReceiverUpdated is a free log subscription operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) WatchReceiverUpdated(opts *bind.WatchOpts, sink chan<- *BindingReceiverUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ReceiverUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceiverUpdated is a log parse operation binding the contract event 0xbda2bcccbfa5ae883ab7d9f03480ab68fe68e9200c9b52c0c47abc21d2c90ec9. -// -// Solidity: event ReceiverUpdated(address previous, address updated) -func (_Binding *BindingFilterer) ParseReceiverUpdated(log types.Log) (*BindingReceiverUpdated, error) { - event := new(BindingReceiverUpdated) - if err := _Binding.contract.UnpackLog(event, "ReceiverUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingRevealableUpdatedIterator is returned from FilterRevealableUpdated and is used to iterate over the raw logs and unpacked data for RevealableUpdated events raised by the Binding contract. -type BindingRevealableUpdatedIterator struct { - Event *BindingRevealableUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingRevealableUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingRevealableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingRevealableUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingRevealableUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingRevealableUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingRevealableUpdated represents a RevealableUpdated event raised by the Binding contract. -type BindingRevealableUpdated struct { - Previous bool - Updated bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterRevealableUpdated is a free log retrieval operation binding the contract event 0x84cc45418127802859711bdf440a92a3a6d3819145166e3f884db8d202aa5ebf. -// -// Solidity: event RevealableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) FilterRevealableUpdated(opts *bind.FilterOpts) (*BindingRevealableUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "RevealableUpdated") - if err != nil { - return nil, err - } - return &BindingRevealableUpdatedIterator{contract: _Binding.contract, event: "RevealableUpdated", logs: logs, sub: sub}, nil -} - -// WatchRevealableUpdated is a free log subscription operation binding the contract event 0x84cc45418127802859711bdf440a92a3a6d3819145166e3f884db8d202aa5ebf. -// -// Solidity: event RevealableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) WatchRevealableUpdated(opts *bind.WatchOpts, sink chan<- *BindingRevealableUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "RevealableUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingRevealableUpdated) - if err := _Binding.contract.UnpackLog(event, "RevealableUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseRevealableUpdated is a log parse operation binding the contract event 0x84cc45418127802859711bdf440a92a3a6d3819145166e3f884db8d202aa5ebf. -// -// Solidity: event RevealableUpdated(bool previous, bool updated) -func (_Binding *BindingFilterer) ParseRevealableUpdated(log types.Log) (*BindingRevealableUpdated, error) { - event := new(BindingRevealableUpdated) - if err := _Binding.contract.UnpackLog(event, "RevealableUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingRoyaltyUpdatedIterator is returned from FilterRoyaltyUpdated and is used to iterate over the raw logs and unpacked data for RoyaltyUpdated events raised by the Binding contract. -type BindingRoyaltyUpdatedIterator struct { - Event *BindingRoyaltyUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingRoyaltyUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingRoyaltyUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingRoyaltyUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingRoyaltyUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingRoyaltyUpdated represents a RoyaltyUpdated event raised by the Binding contract. -type BindingRoyaltyUpdated struct { - Previous *big.Int - Updated *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterRoyaltyUpdated is a free log retrieval operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) FilterRoyaltyUpdated(opts *bind.FilterOpts) (*BindingRoyaltyUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return &BindingRoyaltyUpdatedIterator{contract: _Binding.contract, event: "RoyaltyUpdated", logs: logs, sub: sub}, nil -} - -// WatchRoyaltyUpdated is a free log subscription operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) WatchRoyaltyUpdated(opts *bind.WatchOpts, sink chan<- *BindingRoyaltyUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "RoyaltyUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseRoyaltyUpdated is a log parse operation binding the contract event 0x54e506cda8889617ec187c699f1c3b373053eb5796248194796f7e1501dfab24. -// -// Solidity: event RoyaltyUpdated(uint256 previous, uint256 updated) -func (_Binding *BindingFilterer) ParseRoyaltyUpdated(log types.Log) (*BindingRoyaltyUpdated, error) { - event := new(BindingRoyaltyUpdated) - if err := _Binding.contract.UnpackLog(event, "RoyaltyUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingTokenRevealIterator is returned from FilterTokenReveal and is used to iterate over the raw logs and unpacked data for TokenReveal events raised by the Binding contract. -type BindingTokenRevealIterator struct { - Event *BindingTokenReveal // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingTokenRevealIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingTokenReveal) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingTokenReveal) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingTokenRevealIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingTokenRevealIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingTokenReveal represents a TokenReveal event raised by the Binding contract. -type BindingTokenReveal struct { - User common.Address - RequestId [32]byte - Tokens []*big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTokenReveal is a free log retrieval operation binding the contract event 0xf78fdbb14693a4df69f9724dd4d02cb841094dbff2f6dac48ad20cda511f2d12. -// -// Solidity: event TokenReveal(address indexed user, bytes32 requestId, uint256[] tokens) -func (_Binding *BindingFilterer) FilterTokenReveal(opts *bind.FilterOpts, user []common.Address) (*BindingTokenRevealIterator, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "TokenReveal", userRule) - if err != nil { - return nil, err - } - return &BindingTokenRevealIterator{contract: _Binding.contract, event: "TokenReveal", logs: logs, sub: sub}, nil -} - -// WatchTokenReveal is a free log subscription operation binding the contract event 0xf78fdbb14693a4df69f9724dd4d02cb841094dbff2f6dac48ad20cda511f2d12. -// -// Solidity: event TokenReveal(address indexed user, bytes32 requestId, uint256[] tokens) -func (_Binding *BindingFilterer) WatchTokenReveal(opts *bind.WatchOpts, sink chan<- *BindingTokenReveal, user []common.Address) (event.Subscription, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "TokenReveal", userRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingTokenReveal) - if err := _Binding.contract.UnpackLog(event, "TokenReveal", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTokenReveal is a log parse operation binding the contract event 0xf78fdbb14693a4df69f9724dd4d02cb841094dbff2f6dac48ad20cda511f2d12. -// -// Solidity: event TokenReveal(address indexed user, bytes32 requestId, uint256[] tokens) -func (_Binding *BindingFilterer) ParseTokenReveal(log types.Log) (*BindingTokenReveal, error) { - event := new(BindingTokenReveal) - if err := _Binding.contract.UnpackLog(event, "TokenReveal", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Binding contract. -type BindingTransferIterator struct { - Event *BindingTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingTransfer represents a Transfer event raised by the Binding contract. -type BindingTransfer struct { - From common.Address - To common.Address - TokenId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address, tokenId []*big.Int) (*BindingTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return &BindingTransferIterator{contract: _Binding.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *BindingTransfer, from []common.Address, to []common.Address, tokenId []*big.Int) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var tokenIdRule []interface{} - for _, tokenIdItem := range tokenId { - tokenIdRule = append(tokenIdRule, tokenIdItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "Transfer", fromRule, toRule, tokenIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId) -func (_Binding *BindingFilterer) ParseTransfer(log types.Log) (*BindingTransfer, error) { - event := new(BindingTransfer) - if err := _Binding.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriFallbackUpdatedIterator is returned from FilterUriFallbackUpdated and is used to iterate over the raw logs and unpacked data for UriFallbackUpdated events raised by the Binding contract. -type BindingUriFallbackUpdatedIterator struct { - Event *BindingUriFallbackUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriFallbackUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriFallbackUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriFallbackUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriFallbackUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriFallbackUpdated represents a UriFallbackUpdated event raised by the Binding contract. -type BindingUriFallbackUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriFallbackUpdated is a free log retrieval operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriFallbackUpdated(opts *bind.FilterOpts) (*BindingUriFallbackUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return &BindingUriFallbackUpdatedIterator{contract: _Binding.contract, event: "UriFallbackUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriFallbackUpdated is a free log subscription operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriFallbackUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriFallbackUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriFallbackUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriFallbackUpdated is a log parse operation binding the contract event 0xe1b7ff5efe58018e39b7877b5cfa772bb90f32504be7b2330b078d2a9b114bbe. -// -// Solidity: event UriFallbackUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriFallbackUpdated(log types.Log) (*BindingUriFallbackUpdated, error) { - event := new(BindingUriFallbackUpdated) - if err := _Binding.contract.UnpackLog(event, "UriFallbackUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingUriUpdatedIterator is returned from FilterUriUpdated and is used to iterate over the raw logs and unpacked data for UriUpdated events raised by the Binding contract. -type BindingUriUpdatedIterator struct { - Event *BindingUriUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingUriUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingUriUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingUriUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingUriUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingUriUpdated represents a UriUpdated event raised by the Binding contract. -type BindingUriUpdated struct { - Previous string - Updated string - Raw types.Log // Blockchain specific contextual infos -} - -// FilterUriUpdated is a free log retrieval operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) FilterUriUpdated(opts *bind.FilterOpts) (*BindingUriUpdatedIterator, error) { - - logs, sub, err := _Binding.contract.FilterLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return &BindingUriUpdatedIterator{contract: _Binding.contract, event: "UriUpdated", logs: logs, sub: sub}, nil -} - -// WatchUriUpdated is a free log subscription operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) WatchUriUpdated(opts *bind.WatchOpts, sink chan<- *BindingUriUpdated) (event.Subscription, error) { - - logs, sub, err := _Binding.contract.WatchLogs(opts, "UriUpdated") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseUriUpdated is a log parse operation binding the contract event 0x7d8ebb5abe647a67ba3a2649e11557ae5aa256cf3449245e0c840c98132e5a37. -// -// Solidity: event UriUpdated(string previous, string updated) -func (_Binding *BindingFilterer) ParseUriUpdated(log types.Log) (*BindingUriUpdated, error) { - event := new(BindingUriUpdated) - if err := _Binding.contract.UnpackLog(event, "UriUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/znft/contracts/factory/binding/factory.go b/znft/contracts/factory/binding/factory.go deleted file mode 100644 index d91d1cfb3..000000000 --- a/znft/contracts/factory/binding/factory.go +++ /dev/null @@ -1,862 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"status\",\"type\":\"bool\"}],\"name\":\"ModuleRegistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"TokenCreated\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"count\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"create\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"moduleRegistry\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"status\",\"type\":\"bool\"}],\"name\":\"register\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"tokenList\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"tokenMapping\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// Count is a free data retrieval call binding the contract method 0x06661abd. -// -// Solidity: function count() view returns(uint256) -func (_Binding *BindingCaller) Count(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "count") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Count is a free data retrieval call binding the contract method 0x06661abd. -// -// Solidity: function count() view returns(uint256) -func (_Binding *BindingSession) Count() (*big.Int, error) { - return _Binding.Contract.Count(&_Binding.CallOpts) -} - -// Count is a free data retrieval call binding the contract method 0x06661abd. -// -// Solidity: function count() view returns(uint256) -func (_Binding *BindingCallerSession) Count() (*big.Int, error) { - return _Binding.Contract.Count(&_Binding.CallOpts) -} - -// ModuleRegistry is a free data retrieval call binding the contract method 0x082a1051. -// -// Solidity: function moduleRegistry(address ) view returns(bool) -func (_Binding *BindingCaller) ModuleRegistry(opts *bind.CallOpts, arg0 common.Address) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "moduleRegistry", arg0) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// ModuleRegistry is a free data retrieval call binding the contract method 0x082a1051. -// -// Solidity: function moduleRegistry(address ) view returns(bool) -func (_Binding *BindingSession) ModuleRegistry(arg0 common.Address) (bool, error) { - return _Binding.Contract.ModuleRegistry(&_Binding.CallOpts, arg0) -} - -// ModuleRegistry is a free data retrieval call binding the contract method 0x082a1051. -// -// Solidity: function moduleRegistry(address ) view returns(bool) -func (_Binding *BindingCallerSession) ModuleRegistry(arg0 common.Address) (bool, error) { - return _Binding.Contract.ModuleRegistry(&_Binding.CallOpts, arg0) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCaller) Owner(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "owner") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. -// -// Solidity: function owner() view returns(address) -func (_Binding *BindingCallerSession) Owner() (common.Address, error) { - return _Binding.Contract.Owner(&_Binding.CallOpts) -} - -// TokenList is a free data retrieval call binding the contract method 0x9ead7222. -// -// Solidity: function tokenList(uint256 ) view returns(address) -func (_Binding *BindingCaller) TokenList(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenList", arg0) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// TokenList is a free data retrieval call binding the contract method 0x9ead7222. -// -// Solidity: function tokenList(uint256 ) view returns(address) -func (_Binding *BindingSession) TokenList(arg0 *big.Int) (common.Address, error) { - return _Binding.Contract.TokenList(&_Binding.CallOpts, arg0) -} - -// TokenList is a free data retrieval call binding the contract method 0x9ead7222. -// -// Solidity: function tokenList(uint256 ) view returns(address) -func (_Binding *BindingCallerSession) TokenList(arg0 *big.Int) (common.Address, error) { - return _Binding.Contract.TokenList(&_Binding.CallOpts, arg0) -} - -// TokenMapping is a free data retrieval call binding the contract method 0xba27f50b. -// -// Solidity: function tokenMapping(address ) view returns(bool) -func (_Binding *BindingCaller) TokenMapping(opts *bind.CallOpts, arg0 common.Address) (bool, error) { - var out []interface{} - err := _Binding.contract.Call(opts, &out, "tokenMapping", arg0) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// TokenMapping is a free data retrieval call binding the contract method 0xba27f50b. -// -// Solidity: function tokenMapping(address ) view returns(bool) -func (_Binding *BindingSession) TokenMapping(arg0 common.Address) (bool, error) { - return _Binding.Contract.TokenMapping(&_Binding.CallOpts, arg0) -} - -// TokenMapping is a free data retrieval call binding the contract method 0xba27f50b. -// -// Solidity: function tokenMapping(address ) view returns(bool) -func (_Binding *BindingCallerSession) TokenMapping(arg0 common.Address) (bool, error) { - return _Binding.Contract.TokenMapping(&_Binding.CallOpts, arg0) -} - -// Create is a paid mutator transaction binding the contract method 0x9eeeaa75. -// -// Solidity: function create(address module, string name, string symbol, string uri, bytes data) returns(address) -func (_Binding *BindingTransactor) Create(opts *bind.TransactOpts, module common.Address, name string, symbol string, uri string, data []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "create", module, name, symbol, uri, data) -} - -// Create is a paid mutator transaction binding the contract method 0x9eeeaa75. -// -// Solidity: function create(address module, string name, string symbol, string uri, bytes data) returns(address) -func (_Binding *BindingSession) Create(module common.Address, name string, symbol string, uri string, data []byte) (*types.Transaction, error) { - return _Binding.Contract.Create(&_Binding.TransactOpts, module, name, symbol, uri, data) -} - -// Create is a paid mutator transaction binding the contract method 0x9eeeaa75. -// -// Solidity: function create(address module, string name, string symbol, string uri, bytes data) returns(address) -func (_Binding *BindingTransactorSession) Create(module common.Address, name string, symbol string, uri string, data []byte) (*types.Transaction, error) { - return _Binding.Contract.Create(&_Binding.TransactOpts, module, name, symbol, uri, data) -} - -// Register is a paid mutator transaction binding the contract method 0xab01b469. -// -// Solidity: function register(address module, bool status) returns() -func (_Binding *BindingTransactor) Register(opts *bind.TransactOpts, module common.Address, status bool) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "register", module, status) -} - -// Register is a paid mutator transaction binding the contract method 0xab01b469. -// -// Solidity: function register(address module, bool status) returns() -func (_Binding *BindingSession) Register(module common.Address, status bool) (*types.Transaction, error) { - return _Binding.Contract.Register(&_Binding.TransactOpts, module, status) -} - -// Register is a paid mutator transaction binding the contract method 0xab01b469. -// -// Solidity: function register(address module, bool status) returns() -func (_Binding *BindingTransactorSession) Register(module common.Address, status bool) (*types.Transaction, error) { - return _Binding.Contract.Register(&_Binding.TransactOpts, module, status) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "renounceOwnership") -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. -// -// Solidity: function renounceOwnership() returns() -func (_Binding *BindingTransactorSession) RenounceOwnership() (*types.Transaction, error) { - return _Binding.Contract.RenounceOwnership(&_Binding.TransactOpts) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "transferOwnership", newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. -// -// Solidity: function transferOwnership(address newOwner) returns() -func (_Binding *BindingTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { - return _Binding.Contract.TransferOwnership(&_Binding.TransactOpts, newOwner) -} - -// BindingModuleRegisteredIterator is returned from FilterModuleRegistered and is used to iterate over the raw logs and unpacked data for ModuleRegistered events raised by the Binding contract. -type BindingModuleRegisteredIterator struct { - Event *BindingModuleRegistered // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingModuleRegisteredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingModuleRegistered) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingModuleRegistered) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingModuleRegisteredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingModuleRegisteredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingModuleRegistered represents a ModuleRegistered event raised by the Binding contract. -type BindingModuleRegistered struct { - Module common.Address - Status bool - Raw types.Log // Blockchain specific contextual infos -} - -// FilterModuleRegistered is a free log retrieval operation binding the contract event 0x30091f391c7fccd6f943ec02ae164c4197ea3e43a67edc2edf908f3efc371876. -// -// Solidity: event ModuleRegistered(address indexed module, bool status) -func (_Binding *BindingFilterer) FilterModuleRegistered(opts *bind.FilterOpts, module []common.Address) (*BindingModuleRegisteredIterator, error) { - - var moduleRule []interface{} - for _, moduleItem := range module { - moduleRule = append(moduleRule, moduleItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "ModuleRegistered", moduleRule) - if err != nil { - return nil, err - } - return &BindingModuleRegisteredIterator{contract: _Binding.contract, event: "ModuleRegistered", logs: logs, sub: sub}, nil -} - -// WatchModuleRegistered is a free log subscription operation binding the contract event 0x30091f391c7fccd6f943ec02ae164c4197ea3e43a67edc2edf908f3efc371876. -// -// Solidity: event ModuleRegistered(address indexed module, bool status) -func (_Binding *BindingFilterer) WatchModuleRegistered(opts *bind.WatchOpts, sink chan<- *BindingModuleRegistered, module []common.Address) (event.Subscription, error) { - - var moduleRule []interface{} - for _, moduleItem := range module { - moduleRule = append(moduleRule, moduleItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "ModuleRegistered", moduleRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingModuleRegistered) - if err := _Binding.contract.UnpackLog(event, "ModuleRegistered", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseModuleRegistered is a log parse operation binding the contract event 0x30091f391c7fccd6f943ec02ae164c4197ea3e43a67edc2edf908f3efc371876. -// -// Solidity: event ModuleRegistered(address indexed module, bool status) -func (_Binding *BindingFilterer) ParseModuleRegistered(log types.Log) (*BindingModuleRegistered, error) { - event := new(BindingModuleRegistered) - if err := _Binding.contract.UnpackLog(event, "ModuleRegistered", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Binding contract. -type BindingOwnershipTransferredIterator struct { - Event *BindingOwnershipTransferred // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingOwnershipTransferredIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingOwnershipTransferred) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingOwnershipTransferredIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingOwnershipTransferredIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingOwnershipTransferred represents a OwnershipTransferred event raised by the Binding contract. -type BindingOwnershipTransferred struct { - PreviousOwner common.Address - NewOwner common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*BindingOwnershipTransferredIterator, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return &BindingOwnershipTransferredIterator{contract: _Binding.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil -} - -// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *BindingOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { - - var previousOwnerRule []interface{} - for _, previousOwnerItem := range previousOwner { - previousOwnerRule = append(previousOwnerRule, previousOwnerItem) - } - var newOwnerRule []interface{} - for _, newOwnerItem := range newOwner { - newOwnerRule = append(newOwnerRule, newOwnerItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. -// -// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) -func (_Binding *BindingFilterer) ParseOwnershipTransferred(log types.Log) (*BindingOwnershipTransferred, error) { - event := new(BindingOwnershipTransferred) - if err := _Binding.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// BindingTokenCreatedIterator is returned from FilterTokenCreated and is used to iterate over the raw logs and unpacked data for TokenCreated events raised by the Binding contract. -type BindingTokenCreatedIterator struct { - Event *BindingTokenCreated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *BindingTokenCreatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(BindingTokenCreated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(BindingTokenCreated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *BindingTokenCreatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *BindingTokenCreatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// BindingTokenCreated represents a TokenCreated event raised by the Binding contract. -type BindingTokenCreated struct { - Owner common.Address - Token common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTokenCreated is a free log retrieval operation binding the contract event 0xd5f9bdf12adf29dab0248c349842c3822d53ae2bb4f36352f301630d018c8139. -// -// Solidity: event TokenCreated(address indexed owner, address token) -func (_Binding *BindingFilterer) FilterTokenCreated(opts *bind.FilterOpts, owner []common.Address) (*BindingTokenCreatedIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - - logs, sub, err := _Binding.contract.FilterLogs(opts, "TokenCreated", ownerRule) - if err != nil { - return nil, err - } - return &BindingTokenCreatedIterator{contract: _Binding.contract, event: "TokenCreated", logs: logs, sub: sub}, nil -} - -// WatchTokenCreated is a free log subscription operation binding the contract event 0xd5f9bdf12adf29dab0248c349842c3822d53ae2bb4f36352f301630d018c8139. -// -// Solidity: event TokenCreated(address indexed owner, address token) -func (_Binding *BindingFilterer) WatchTokenCreated(opts *bind.WatchOpts, sink chan<- *BindingTokenCreated, owner []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - - logs, sub, err := _Binding.contract.WatchLogs(opts, "TokenCreated", ownerRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(BindingTokenCreated) - if err := _Binding.contract.UnpackLog(event, "TokenCreated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTokenCreated is a log parse operation binding the contract event 0xd5f9bdf12adf29dab0248c349842c3822d53ae2bb4f36352f301630d018c8139. -// -// Solidity: event TokenCreated(address indexed owner, address token) -func (_Binding *BindingFilterer) ParseTokenCreated(log types.Log) (*BindingTokenCreated, error) { - event := new(BindingTokenCreated) - if err := _Binding.contract.UnpackLog(event, "TokenCreated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/znft/contracts/factorymoduleerc721/binding/factorymoduleerc721.go b/znft/contracts/factorymoduleerc721/binding/factorymoduleerc721.go deleted file mode 100644 index becdae417..000000000 --- a/znft/contracts/factorymoduleerc721/binding/factorymoduleerc721.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"createToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 , uint256 , bytes ) returns(address) -func (_Binding *BindingTransactor) CreateToken(opts *bind.TransactOpts, owner common.Address, name string, symbol string, uri string, max *big.Int, arg5 *big.Int, arg6 *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "createToken", owner, name, symbol, uri, max, arg5, arg6, arg7) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 , uint256 , bytes ) returns(address) -func (_Binding *BindingSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, arg5 *big.Int, arg6 *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, arg5, arg6, arg7) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 , uint256 , bytes ) returns(address) -func (_Binding *BindingTransactorSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, arg5 *big.Int, arg6 *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, arg5, arg6, arg7) -} diff --git a/znft/contracts/factorymoduleerc721fixed/binding/factorymoduleerc721fixed.go b/znft/contracts/factorymoduleerc721fixed/binding/factorymoduleerc721fixed.go deleted file mode 100644 index eb6bfaff7..000000000 --- a/znft/contracts/factorymoduleerc721fixed/binding/factorymoduleerc721fixed.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"price\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"batch\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"createToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes ) returns(address) -func (_Binding *BindingTransactor) CreateToken(opts *bind.TransactOpts, owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "createToken", owner, name, symbol, uri, max, price, batch, arg7) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes ) returns(address) -func (_Binding *BindingSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, price, batch, arg7) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes ) returns(address) -func (_Binding *BindingTransactorSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, price, batch, arg7) -} diff --git a/znft/contracts/factorymoduleerc721pack/binding/factorymoduleerc721pack.go b/znft/contracts/factorymoduleerc721pack/binding/factorymoduleerc721pack.go deleted file mode 100644 index d27aae231..000000000 --- a/znft/contracts/factorymoduleerc721pack/binding/factorymoduleerc721pack.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"factory_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"random_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"price\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"batch\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"createToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes data) returns(address) -func (_Binding *BindingTransactor) CreateToken(opts *bind.TransactOpts, owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, data []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "createToken", owner, name, symbol, uri, max, price, batch, data) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes data) returns(address) -func (_Binding *BindingSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, data []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, price, batch, data) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes data) returns(address) -func (_Binding *BindingTransactorSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, data []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, price, batch, data) -} diff --git a/znft/contracts/factorymoduleerc721random/binding/factorymoduleerc721random.go b/znft/contracts/factorymoduleerc721random/binding/factorymoduleerc721random.go deleted file mode 100644 index 37cfefa52..000000000 --- a/znft/contracts/factorymoduleerc721random/binding/factorymoduleerc721random.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package binding - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// BindingMetaData contains all meta data concerning the Binding contract. -var BindingMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"vrfCoordinator_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"vrfLink_\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"vrfKeyHash_\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"vrfFee_\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"uri\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"price\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"batch\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"createToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", -} - -// BindingABI is the input ABI used to generate the binding from. -// Deprecated: Use BindingMetaData.ABI instead. -var BindingABI = BindingMetaData.ABI - -// Binding is an auto generated Go binding around an Ethereum contract. -type Binding struct { - BindingCaller // Read-only binding to the contract - BindingTransactor // Write-only binding to the contract - BindingFilterer // Log filterer for contract events -} - -// BindingCaller is an auto generated read-only Go binding around an Ethereum contract. -type BindingCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingTransactor is an auto generated write-only Go binding around an Ethereum contract. -type BindingTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type BindingFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// BindingSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type BindingSession struct { - Contract *Binding // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type BindingCallerSession struct { - Contract *BindingCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// BindingTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type BindingTransactorSession struct { - Contract *BindingTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// BindingRaw is an auto generated low-level Go binding around an Ethereum contract. -type BindingRaw struct { - Contract *Binding // Generic contract binding to access the raw methods on -} - -// BindingCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type BindingCallerRaw struct { - Contract *BindingCaller // Generic read-only contract binding to access the raw methods on -} - -// BindingTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type BindingTransactorRaw struct { - Contract *BindingTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewBinding creates a new instance of Binding, bound to a specific deployed contract. -func NewBinding(address common.Address, backend bind.ContractBackend) (*Binding, error) { - contract, err := bindBinding(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Binding{BindingCaller: BindingCaller{contract: contract}, BindingTransactor: BindingTransactor{contract: contract}, BindingFilterer: BindingFilterer{contract: contract}}, nil -} - -// NewBindingCaller creates a new read-only instance of Binding, bound to a specific deployed contract. -func NewBindingCaller(address common.Address, caller bind.ContractCaller) (*BindingCaller, error) { - contract, err := bindBinding(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &BindingCaller{contract: contract}, nil -} - -// NewBindingTransactor creates a new write-only instance of Binding, bound to a specific deployed contract. -func NewBindingTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingTransactor, error) { - contract, err := bindBinding(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &BindingTransactor{contract: contract}, nil -} - -// NewBindingFilterer creates a new log filterer instance of Binding, bound to a specific deployed contract. -func NewBindingFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingFilterer, error) { - contract, err := bindBinding(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &BindingFilterer{contract: contract}, nil -} - -// bindBinding binds a generic wrapper to an already deployed contract. -func bindBinding(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(BindingABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.BindingCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.BindingTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Binding *BindingCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Binding.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Binding *BindingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Binding.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Binding *BindingTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Binding.Contract.contract.Transact(opts, method, params...) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes ) returns(address) -func (_Binding *BindingTransactor) CreateToken(opts *bind.TransactOpts, owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.contract.Transact(opts, "createToken", owner, name, symbol, uri, max, price, batch, arg7) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes ) returns(address) -func (_Binding *BindingSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, price, batch, arg7) -} - -// CreateToken is a paid mutator transaction binding the contract method 0x3d774115. -// -// Solidity: function createToken(address owner, string name, string symbol, string uri, uint256 max, uint256 price, uint256 batch, bytes ) returns(address) -func (_Binding *BindingTransactorSession) CreateToken(owner common.Address, name string, symbol string, uri string, max *big.Int, price *big.Int, batch *big.Int, arg7 []byte) (*types.Transaction, error) { - return _Binding.Contract.CreateToken(&_Binding.TransactOpts, owner, name, symbol, uri, max, price, batch, arg7) -} diff --git a/znft/doc.go b/znft/doc.go deleted file mode 100644 index fd18d5ce3..000000000 --- a/znft/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// 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/ethereum_wallet.go b/znft/ethereum_wallet.go deleted file mode 100644 index d1a26a411..000000000 --- a/znft/ethereum_wallet.go +++ /dev/null @@ -1,110 +0,0 @@ -package znft - -import ( - "context" - "math/big" - "path" - "time" - - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" - "github.com/pkg/errors" -) - -func CreateEthClient(ethereumNodeURL string) (*ethclient.Client, error) { - client, err := ethclient.Dial(ethereumNodeURL) - if err != nil { - Logger.Error(err) - return nil, err - } - return client, err -} - -func (app *Znft) createSignedTransactionFromKeyStore(ctx context.Context) (*bind.TransactOpts, error) { - var ( - signerAddress = common.HexToAddress(app.cfg.WalletAddress) - password = app.cfg.VaultPassword - value = app.cfg.Value - ) - - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - err := errors.Wrap(err, "failed to create ethereum client") - Logger.Fatal(err) - return nil, err - } - - keyDir := path.Join(app.cfg.Homedir, WalletDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - signer := accounts.Account{ - Address: signerAddress, - } - signerAcc, err := ks.Find(signer) - if err != nil { - err := errors.Wrapf(err, "signer: %s", signerAddress.Hex()) - Logger.Fatal(err) - return nil, err - } - - chainID, err := client.ChainID(ctx) - if err != nil { - err := errors.Wrap(err, "failed to get chain ID") - Logger.Fatal(err) - return nil, err - } - - err = ks.TimedUnlock(signer, password, time.Second*2) - if err != nil { - Logger.Fatal(err) - return nil, err - } - - opts, err := bind.NewKeyStoreTransactorWithChainID(ks, signerAcc, chainID) - if err != nil { - Logger.Fatal(err) - return nil, err - } - - valueWei := new(big.Int).Mul(big.NewInt(value), big.NewInt(params.Wei)) - - opts.Value = valueWei // in wei (= no funds) - - return opts, nil -} - -func (app *Znft) createSignedTransactionFromKeyStoreWithGasPrice(ctx context.Context, gasLimitUnits uint64) (*bind.TransactOpts, error) { //nolint - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - err := errors.Wrap(err, "failed to create ethereum client") - Logger.Fatal(err) - return nil, err - } - - nonce, err := client.PendingNonceAt(ctx, common.HexToAddress(app.cfg.WalletAddress)) - if err != nil { - Logger.Fatal(err) - return nil, err - } - - gasPriceWei, err := client.SuggestGasPrice(ctx) - if err != nil { - Logger.Fatal(err) - return nil, err - } - - opts, err := app.createSignedTransactionFromKeyStore(ctx) - if err != nil { - Logger.Fatal(err) - return nil, err - } - - opts.Nonce = big.NewInt(int64(nonce)) // (nil = use pending state), look at bind.CallOpts{Pending: true} - opts.GasLimit = gasLimitUnits // in units (0 = estimate) - opts.GasPrice = gasPriceWei // wei (nil = gas price oracle) - - return opts, nil -} diff --git a/znft/example/go.mod b/znft/example/go.mod deleted file mode 100644 index 7d7b3f3b6..000000000 --- a/znft/example/go.mod +++ /dev/null @@ -1,34 +0,0 @@ -module example - -go 1.22.5 - -toolchain go1.23.3 - -require github.com/0chain/gosdk v1.8.9 - -require ( - github.com/btcsuite/btcd v0.23.4 // indirect - github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect - github.com/btcsuite/btcd/btcutil v1.1.3 // indirect - github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 // indirect - github.com/deckarep/golang-set v1.8.0 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect - github.com/ethereum/go-ethereum v1.10.26 // indirect - github.com/go-ole/go-ole v1.2.6 // indirect - github.com/go-stack/stack v1.8.1 // indirect - github.com/google/uuid v1.3.0 // indirect - github.com/gorilla/websocket v1.5.0 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/rjeczalik/notify v0.9.2 // indirect - github.com/shirou/gopsutil v3.21.11+incompatible // indirect - github.com/tklauser/go-sysconf v0.3.11 // indirect - github.com/tklauser/numcpus v0.6.0 // indirect - github.com/tyler-smith/go-bip39 v1.1.0 // indirect - github.com/yusufpapurcu/wmi v1.2.2 // indirect - golang.org/x/crypto v0.17.0 // indirect - golang.org/x/sys v0.15.0 // indirect - gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect -) - -replace github.com/0chain/gosdk => ../../ diff --git a/znft/example/go.sum b/znft/example/go.sum deleted file mode 100644 index 288f8e83e..000000000 --- a/znft/example/go.sum +++ /dev/null @@ -1,184 +0,0 @@ -github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o= -github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= -github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= -github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M= -github.com/btcsuite/btcd v0.23.0/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= -github.com/btcsuite/btcd v0.23.2 h1:/YOgUp25sdCnP5ho6Hl3s0E438zlX+Kak7E6TgBgoT0= -github.com/btcsuite/btcd v0.23.2/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= -github.com/btcsuite/btcd v0.23.4/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= -github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA= -github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE= -github.com/btcsuite/btcd/btcec/v2 v2.2.1 h1:xP60mv8fvp+0khmrN0zTdPC3cNm24rfeE6lh2R/Yv3E= -github.com/btcsuite/btcd/btcec/v2 v2.2.1/go.mod h1:9/CSmJxmuvqzX9Wh2fXMWToLOHhPd11lSPuIupwTkI8= -github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= -github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A= -github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE= -github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= -github.com/btcsuite/btcd/btcutil v1.1.2/go.mod h1:UR7dsSJzJUfMmFiiLlIrMq1lS9jh9EdCV7FStZSnpi0= -github.com/btcsuite/btcd/btcutil v1.1.3/go.mod h1:UR7dsSJzJUfMmFiiLlIrMq1lS9jh9EdCV7FStZSnpi0= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= -github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= -github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= -github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= -github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= -github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= -github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= -github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= -github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= -github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= -github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= -github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= -github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4= -github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= -github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= -github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= -github.com/ethereum/go-ethereum v1.10.25 h1:5dFrKJDnYf8L6/5o42abCE6a9yJm9cs4EJVRyYMr55s= -github.com/ethereum/go-ethereum v1.10.25/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= -github.com/ethereum/go-ethereum v1.10.26/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= -github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= -github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= -github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= -github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= -github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= -github.com/golang-jwt/jwt/v4 v4.3.0 h1:kHL1vqdqWNfATmA0FNMdmZNMyZI1U6O31X4rlIPoBog= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/hashicorp/go-bexpr v0.1.10 h1:9kuI5PFotCboP3dkDYFr/wi0gg0QVbSNz5oFRpxn4uE= -github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= -github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= -github.com/holiman/uint256 v1.2.0 h1:gpSYcPLWGv4sG43I2mVLiDZCNDh/EpGjSk8tmtxitHM= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huin/goupnp v1.0.3 h1:N8No57ls+MnjlB+JPiCVSOyy/ot7MJTqlo7rn+NYSqQ= -github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus= -github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= -github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= -github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= -github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= -github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= -github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= -github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= -github.com/rjeczalik/notify v0.9.2 h1:MiTWrPj55mNDHEiIX5YUSKefw/+lCQVoAFmD6oQm5w8= -github.com/rjeczalik/notify v0.9.2/go.mod h1:aErll2f0sUX9PXZnVNyeiObbmTlk5jnMoCa4QEjJeqM= -github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= -github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= -github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4 h1:Gb2Tyox57NRNuZ2d3rmvB3pcmbu7O1RS3m8WRx7ilrg= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= -github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= -github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= -github.com/tklauser/go-sysconf v0.3.10 h1:IJ1AZGZRWbY8T5Vfk04D9WOA5WSejdflXxP03OUqALw= -github.com/tklauser/go-sysconf v0.3.10/go.mod h1:C8XykCvCb+Gn0oNCWPIlcb0RuglQTYaQ2hGm7jmxEFk= -github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= -github.com/tklauser/numcpus v0.4.0/go.mod h1:1+UI3pD8NW14VMwdgJNJ1ESk2UnwhAnz5hMwiKKqXCQ= -github.com/tklauser/numcpus v0.5.0 h1:ooe7gN0fg6myJ0EKoTAf5hebTZrH52px3New/D9iJ+A= -github.com/tklauser/numcpus v0.5.0/go.mod h1:OGzpTxpcIMNGYQdit2BYL1pvk/dSOaJWjKoflh+RQjo= -github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= -github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= -github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= -github.com/urfave/cli/v2 v2.10.2 h1:x3p8awjp/2arX+Nl/G2040AZpOCHS/eMJJ1/a+mye4Y= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= -github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= -github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20221012134737-56aed061732a h1:NmSIgad6KjE6VvHciPZuNRTKxGhlPfD6OA87W/PLkqg= -golang.org/x/crypto v0.0.0-20221012134737-56aed061732a/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/znft/example/main.go b/znft/example/main.go deleted file mode 100644 index 182b2b5c8..000000000 --- a/znft/example/main.go +++ /dev/null @@ -1,141 +0,0 @@ -//go:build ignore -// +build ignore - -// Example usage of the znft package - do not use. -package main - -import ( - "context" - "fmt" - "log" - "math/big" - "os" - - "github.com/0chain/gosdk_common/znft" -) - -var mnemonic string - -func main() { - mnemonic = "use your mnemonic to import account to a local storage" - - // Create this configuration from console app - cfg := &znft.Configuration{ - FactoryAddress: "0xD98602749e7f46036d496e8D3deb6eb9F90996a6", - FactoryModuleERC721Address: "", - FactoryModuleERC721FixedAddress: "", - FactoryModuleERC721RandomAddress: "", - FactoryModuleERC721PackedAddress: "", - EthereumNodeURL: "https://rinkeby.infura.io/v3/22cb2849f5f74b8599f3dc2a23085bd4", - WalletAddress: "0x860FA46F170a87dF44D7bB867AA4a5D2813127c1", - VaultPassword: "pass", - Homedir: "", // optional, default = "~/.zcn" - Value: 0, // mandatory, default > 0 - } - - if cfg.Homedir == "" { - cfg.Homedir = znft.GetConfigDir() - } - - if !znft.AccountExists(cfg.Homedir, cfg.WalletAddress) { - _, err := znft.ImportAccount(cfg.Homedir, mnemonic, cfg.VaultPassword) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - } - - // Creating NFTs with factories: - // -------------------------------- - // CreateFactoryERC721Session - // CreateFactoryERC721PackSession - // CreateFactoryERC721FixedSession - // CreateFactoryERC721RandomSession - - app := znft.NewNFTApplication(cfg) - - factorySession, err := app.CreateFactoryERC721Session(context.Background(), cfg.FactoryAddress) - if err != nil { - panic(err) - } - - data := []byte("") - max := new(big.Int).SetInt64(10000) - err = factorySession.CreateToken( - cfg.WalletAddress, - "TestFixedPriceToken", - "dNFT", - "https://api.0chain.net/v1/file/abcdefgh/", - max, - data, - ) - if err != nil { - panic(err) - } - - // When addresses are received after deployment with factories... - // Reading and writing to NFT smart contracts using DStorageSessions - // -------------------------------- - // CreateStorageERC721Session - // CreateStorageERC721PackSession - // CreateStorageERC721RandomSession - // CreateStorageERC721FixedSession - - // Create session of NFT token - sessionRandom, err := app.CreateStorageERC721RandomSession(context.Background(), "received from deployment") - if err != nil { - panic(err) - } - - // Start using session - price, err := sessionRandom.Price() - if err != nil { - panic(err) - } - log.Print(price) - - // ERC721Fixed - - // Create session of NFT token - sessionFixed, err := app.CreateStorageERC721FixedSession(context.Background(), "received from deployment") - if err != nil { - panic(err) - } - - // Start using session - price, err = sessionFixed.Price() - if err != nil { - panic(err) - } - log.Print(price) - - // ERC721Pack - - // Create session of NFT token - sessionPack, err := app.CreateStorageERC721PackSession(context.Background(), "received from deployment") - if err != nil { - panic(err) - } - - // Start using session - price, err = sessionPack.Price() - if err != nil { - panic(err) - } - log.Print(price) - - // ERC721 - - // Create session of NFT token - session, err := app.CreateStorageERC721Session(context.Background(), "received from deployment") - if err != nil { - panic(err) - } - - // Start using session - price, err = session.Price() - if err != nil { - panic(err) - } - log.Print(price) -} diff --git a/znft/factoryerc721.go b/znft/factoryerc721.go deleted file mode 100644 index d62d440ce..000000000 --- a/znft/factoryerc721.go +++ /dev/null @@ -1,48 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - "github.com/pkg/errors" - - "github.com/ethereum/go-ethereum/common" - - factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721/binding" -) - -// Solidity functions - -// function createToken( -// address owner, -// string calldata name, -// string calldata symbol, -// string calldata uri, -// uint256 max, -// uint256, -// uint256, -// bytes calldata -//) external returns (address) { - -type IFactoryERC721 interface { - CreateToken(owner, name, symbol, uri string, max *big.Int, data []byte) error -} - -type FactoryERC721 struct { - session *factory.BindingSession - ctx context.Context -} - -func (s *FactoryERC721) CreateToken(owner, name, symbol, uri string, max *big.Int, data []byte) error { - ownerAddress := common.HexToAddress(owner) - evmTr, err := s.session.CreateToken(ownerAddress, name, symbol, uri, max, nil, nil, data) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "CreateToken") - Logger.Error(err) - return err - } - - Logger.Info("Executed CreateToken, hash: ", evmTr.Hash().Hex()) - - return nil -} diff --git a/znft/factoryerc721fixed.go b/znft/factoryerc721fixed.go deleted file mode 100644 index fe2d7832c..000000000 --- a/znft/factoryerc721fixed.go +++ /dev/null @@ -1,47 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" - - factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721fixed/binding" -) - -// Solidity functions - -// function createToken( -// address owner, -// string calldata name, -// string calldata symbol, -// string calldata uri, -// uint256 max, -// uint256 price, -// uint256 batch, -// bytes calldata -//) external returns (address) { - -type IFactoryFixed interface { - CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error -} - -type FactoryFixed struct { - session *factory.BindingSession - ctx context.Context -} - -func (s *FactoryFixed) CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error { - ownerAddress := common.HexToAddress(owner) - evmTr, err := s.session.CreateToken(ownerAddress, name, symbol, uri, max, price, batch, calldata) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "CreateToken") - Logger.Error(err) - return err - } - - Logger.Info("Executed CreateToken, hash: ", evmTr.Hash().Hex()) - - return nil -} diff --git a/znft/factoryerc721pack.go b/znft/factoryerc721pack.go deleted file mode 100644 index 304324526..000000000 --- a/znft/factoryerc721pack.go +++ /dev/null @@ -1,47 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" - - factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721pack/binding" -) - -// Solidity functions - -// function createToken( -// address owner, -// string calldata name, -// string calldata symbol, -// string calldata uri, -// uint256 max, -// uint256 price, -// uint256 batch, -// bytes calldata -//) external returns (address) { - -type IFactoryPack interface { - CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error -} - -type FactoryPack struct { - session *factory.BindingSession - ctx context.Context -} - -func (s *FactoryPack) CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error { - ownerAddress := common.HexToAddress(owner) - evmTr, err := s.session.CreateToken(ownerAddress, name, symbol, uri, max, price, batch, calldata) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "CreateToken") - Logger.Error(err) - return err - } - - Logger.Info("Executed CreateToken, hash: ", evmTr.Hash().Hex()) - - return nil -} diff --git a/znft/factoryerc721random.go b/znft/factoryerc721random.go deleted file mode 100644 index c06f5abb4..000000000 --- a/znft/factoryerc721random.go +++ /dev/null @@ -1,47 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" - - factory "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721random/binding" -) - -// Solidity functions - -// function createToken( -// address owner, -// string calldata name, -// string calldata symbol, -// string calldata uri, -// uint256 max, -// uint256 price, -// uint256 batch, -// bytes calldata -//) external returns (address) { - -type IFactoryRandom interface { - CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error -} - -type FactoryRandom struct { - session *factory.BindingSession - ctx context.Context -} - -func (s *FactoryRandom) CreateToken(owner, name, symbol, uri string, max, price, batch *big.Int, calldata []byte) error { - ownerAddress := common.HexToAddress(owner) - evmTr, err := s.session.CreateToken(ownerAddress, name, symbol, uri, max, price, batch, calldata) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "CreateToken") - Logger.Error(err) - return err - } - - Logger.Info("Executed CreateToken, hash: ", evmTr.Hash().Hex()) - - return nil -} diff --git a/znft/keystore.go b/znft/keystore.go deleted file mode 100644 index 3e14a8984..000000000 --- a/znft/keystore.go +++ /dev/null @@ -1,156 +0,0 @@ -package znft - -import ( - "fmt" - "os" - "path" - - hdw "github.com/0chain/gosdk_common/zcncore/ethhdwallet" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" - "gopkg.in/yaml.v2" -) - -// ListStorageAccounts List available accounts -func ListStorageAccounts(homedir string) []common.Address { - am := getAccountManager(homedir) - addresses := am.Accounts() - - return addresses -} - -// DeleteAccount deletes account from wallet -func DeleteAccount(homedir, address string) bool { - am := getAccountManager(homedir) - - wallet, err := am.Find(accounts.Account{ - Address: common.HexToAddress(address), - }) - - if err != nil && wallet == nil { - fmt.Printf("failed to find account %s, error: %s", address, err) - return false - } - - return true -} - -func getAccountManager(homedir string) *accounts.Manager { - keyDir := path.Join(homedir, WalletDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - config := &accounts.Config{InsecureUnlockAllowed: false} - am := accounts.NewManager(config, ks) - return am -} - -// AccountExists checks if account exists -func AccountExists(homedir, address string) bool { - am := getAccountManager(homedir) - - wallet, err := am.Find(accounts.Account{ - Address: common.HexToAddress(address), - }) - - if err != nil && wallet == nil { - fmt.Printf("failed to find account %s, error: %s\n", address, err) - return false - } - - status, _ := wallet.Status() - url := wallet.URL() - - fmt.Printf("Account exists. Status: %s, Path: %s\n", status, url) - - return true -} - -// CreateKeyStorage create, restore or unlock key storage -func CreateKeyStorage(homedir, password string) error { - keyDir := path.Join(homedir, WalletDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - account, err := ks.NewAccount(password) - if err != nil { - return errors.Wrap(err, "failed to create keystore") - } - fmt.Printf("Created account: %s", account.Address.Hex()) - - return nil -} - -// UpdateClientEthereumAddress updates Ethereum address -func UpdateClientEthereumAddress(homedir, address string) (err error) { - configFile := path.Join(homedir, ConfigFile) - buf, err := os.ReadFile(configFile) - if err != nil { - return err - } - cfg := &Configuration{} - err = yaml.Unmarshal(buf, cfg) - if err != nil { - return err - } - - cfg.WalletAddress = address - - text, err := yaml.Marshal(cfg) - if err != nil { - return err - } - - err = os.WriteFile(configFile, text, 0644) - - return err -} - -// ImportAccount imports account using mnemonic -// password is used to lock and unlock keystorage before signing transaction -func ImportAccount(homedir, mnemonic, password string) (string, error) { - // 1. Create storage and account if it doesn't exist and add account to it - keyDir := path.Join(homedir, WalletDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - - // 2. Init wallet - wallet, err := hdw.NewFromMnemonic(mnemonic) - if err != nil { - return "", errors.Wrap(err, "failed to import from mnemonic") - } - - // DefaultBaseDerivationPath is the base path from which custom derivation endpoints - // are incremented. As such, the first account will be at m/44'/60'/0'/0, the second - // at m/44'/60'/0'/1, etc - // from basic library: - // var DefaultBaseDerivationPath = accounts.DefaultBaseDerivationPath - // from the BIP44 specification, the HD derivation path is defined as - // m / purpose' / coin_type' / account' / change / address_index - // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki - - pathD := hdw.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := wallet.Derive(pathD, true) - if err != nil { - return "", errors.Wrap(err, "failed parse derivation path") - } - - key, err := wallet.PrivateKey(account) - if err != nil { - return "", errors.Wrap(err, "failed to get private key") - } - - // 3. Find key - acc, err := ks.Find(account) - if err == nil { - fmt.Printf("Account already exists: %s\nPath: %s\n\n", acc.Address.Hex(), acc.URL.Path) - return acc.Address.Hex(), nil - } - - // 4. Import the key if it doesn't exist - acc, err = ks.ImportECDSA(key, password) - if err != nil { - return "", errors.Wrap(err, "failed to get import private key") - } - - fmt.Printf("Imported account %s to path: %s\n", acc.Address.Hex(), acc.URL.Path) - - return acc.Address.Hex(), nil -} diff --git a/znft/storageerc721.go b/znft/storageerc721.go deleted file mode 100644 index 59ffd6f01..000000000 --- a/znft/storageerc721.go +++ /dev/null @@ -1,347 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - storageerc721 "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721/binding" - - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" -) - -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" -) - -// Solidity Functions -// - withdraw() -// - setReceiver(address receiver_) -// - setRoyalty(uint256 royalty_) -// - setMintable(bool status_) -// - setMax(uint256 max_) -// - setAllocation(string calldata allocation_) -// - setURI(string calldata uri_) -// - setURIFallback(string calldata uri_) -// - tokenURIFallback(uint256 tokenId) returns (string memory) -// - price() returns (uint256) -// - mint(uint256 amount) -// - mintOwner(uint256 amount) -// - royaltyInfo(uint256 tokenId, uint256 salePrice) returns (address, uint256) -// - freeze() -// Fields: -// uint256 public total; -// uint256 public max; -// uint256 public batch; -// bool public mintable; -// string public allocation; -// string public uri; -// string public uriFallback; -// uint256 public royalty; -// address public receiver; - -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) -} - -var ( - _ IStorageECR721 = (*StorageECR721)(nil) -) - -type StorageECR721 struct { - session *storageerc721.BindingSession - ctx context.Context -} - -func (s *StorageECR721) SetURIFallback(uri string) error { - evmTr, err := s.session.SetURIFallback(uri) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetURIFallback") - Logger.Error(err) - return err - } - - Logger.Info("Executed SetURIFallback, hash: ", evmTr.Hash().Hex()) - - return nil -} - -func (s *StorageECR721) Total() (*big.Int, error) { - total, err := s.session.Total() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Total") - Logger.Error(err) - return nil, err - } - - return total, nil -} - -func (s *StorageECR721) Batch() (*big.Int, error) { - batch, err := s.session.Batch() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Batch") - Logger.Error(err) - return nil, err - } - - return batch, nil -} - -func (s *StorageECR721) Mintable() (bool, error) { - mintable, err := s.session.Mintable() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Mintable") - Logger.Error(err) - return false, err - } - - return mintable, nil -} - -func (s *StorageECR721) Allocation() (string, error) { - allocation, err := s.session.Allocation() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Allocation") - Logger.Error(err) - return "", err - } - - return allocation, nil -} - -func (s *StorageECR721) Uri() (string, error) { - uri, err := s.session.Uri() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "URI") - Logger.Error(err) - return "", err - } - - return uri, nil -} - -func (s *StorageECR721) UriFallback() (string, error) { - uri, err := s.session.UriFallback() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "URIFallback") - Logger.Error(err) - return "", err - } - - return uri, nil -} - -func (s *StorageECR721) Royalty() (*big.Int, error) { - value, err := s.session.Royalty() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Royalty") - Logger.Error(err) - return nil, err - } - - return value, nil -} - -func (s *StorageECR721) Receiver() (string, error) { - value, err := s.session.Receiver() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Receiver") - Logger.Error(err) - return "", err - } - - return value.String(), nil -} - -func (s *StorageECR721) Max() (*big.Int, error) { - max, err := s.session.Max() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Max") - Logger.Error(err) - return nil, err - } - - return max, nil -} - -func (s *StorageECR721) Mint(amount *big.Int) error { - evmTr, err := s.session.Mint(amount) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", Mint) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", Mint, "hash: ", evmTr.Hash().Hex()) - - return nil -} - -func (s *StorageECR721) RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) { - address, sum, err := s.session.RoyaltyInfo(tokenId, salePrice) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", RoyaltyInfo) - Logger.Error(err) - return "", nil, err - } - - return address.Hex(), sum, nil -} - -func (s *StorageECR721) MintOwner(amount *big.Int) error { - evmTr, err := s.session.MintOwner(amount) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", MintOwner) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", MintOwner, "hash: ", evmTr.Hash().Hex()) - - return nil -} - -func (s *StorageECR721) TokenURIFallback(token *big.Int) (string, error) { - tokenURI, err := s.session.TokenURIFallback(token) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", TokenURIFallback) - Logger.Error(err) - return "", err - } - - return tokenURI, nil -} - -// Price returns price -func (s *StorageECR721) Price() (*big.Int, error) { - price, err := s.session.Price() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", Price) - Logger.Error(err) - return nil, err - } - - return price, nil -} - -// SetURI updates uri -func (s *StorageECR721) SetURI(uri string) error { - evmTr, err := s.session.SetURI(uri) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetURI) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetURI, "hash: ", evmTr.Hash().String()) - - return nil -} - -// SetAllocation updates allocation -func (s *StorageECR721) SetAllocation(allocation string) error { - evmTr, err := s.session.SetAllocation(allocation) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetAllocation) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetAllocation, " hash: ", evmTr.Hash()) - - return nil -} - -// SetMintable updates mintable state -func (s *StorageECR721) SetMintable(status bool) error { - evmTr, err := s.session.SetMintable(status) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetMintable) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetMintable, " hash: ", evmTr.Hash()) - - return nil -} - -// SetRoyalty eth balance from token contract - setReceiver(address receiver_) -func (s *StorageECR721) SetRoyalty(sum *big.Int) error { - evmTr, err := s.session.SetRoyalty(sum) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetRoyalty) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetRoyalty, "hash: ", evmTr.Hash()) - - return nil -} - -// SetReceiver eth balance from token contract - setReceiver(address receiver_) -func (s *StorageECR721) SetReceiver(receiver string) error { - address := common.HexToAddress(receiver) - - evmTr, err := s.session.SetReceiver(address) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetReceiver) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetReceiver, "hash: ", evmTr.Hash()) - - return nil -} - -// Withdraw eth balance from token contract - withdraw() -func (s *StorageECR721) Withdraw() error { - evmTr, err := s.session.Withdraw() - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", Withdraw) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", Withdraw, " hash: ", evmTr.Hash()) - - return nil -} diff --git a/znft/storageerc721fixed.go b/znft/storageerc721fixed.go deleted file mode 100644 index 80ce95a25..000000000 --- a/znft/storageerc721fixed.go +++ /dev/null @@ -1,297 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - storageerc721fixed "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721fixed/binding" - - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" -) - -// Solidity Functions -// function mint(uint256 amount) -// function price() public view override returns (uint256) - -type IStorageECR721Fixed interface { - IStorageECR721 -} - -var ( - _ IStorageECR721Fixed = (*StorageECR721Fixed)(nil) -) - -type StorageECR721Fixed struct { - session *storageerc721fixed.BindingSession - ctx context.Context -} - -func (s *StorageECR721Fixed) SetURIFallback(uri string) error { - evmTr, err := s.session.SetURIFallback(uri) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetURIFallback") - Logger.Error(err) - return err - } - - Logger.Info("Executed SetURIFallback, hash: ", evmTr.Hash().Hex()) - - return nil -} - -func (s *StorageECR721Fixed) Total() (*big.Int, error) { - total, err := s.session.Total() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Total") - Logger.Error(err) - return nil, err - } - - return total, nil -} - -func (s *StorageECR721Fixed) Batch() (*big.Int, error) { - batch, err := s.session.Batch() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Batch") - Logger.Error(err) - return nil, err - } - - return batch, nil -} - -func (s *StorageECR721Fixed) Mintable() (bool, error) { - mintable, err := s.session.Mintable() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Mintable") - Logger.Error(err) - return false, err - } - - return mintable, nil -} - -func (s *StorageECR721Fixed) Allocation() (string, error) { - allocation, err := s.session.Allocation() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Allocation") - Logger.Error(err) - return "", err - } - - return allocation, nil -} - -func (s *StorageECR721Fixed) Uri() (string, error) { - uri, err := s.session.Uri() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "URI") - Logger.Error(err) - return "", err - } - - return uri, nil -} - -func (s *StorageECR721Fixed) UriFallback() (string, error) { - uri, err := s.session.UriFallback() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "URIFallback") - Logger.Error(err) - return "", err - } - - return uri, nil -} - -func (s *StorageECR721Fixed) Royalty() (*big.Int, error) { - value, err := s.session.Royalty() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Royalty") - Logger.Error(err) - return nil, err - } - - return value, nil -} - -func (s *StorageECR721Fixed) Receiver() (string, error) { - value, err := s.session.Receiver() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Receiver") - Logger.Error(err) - return "", err - } - - return value.String(), nil -} - -func (s *StorageECR721Fixed) Max() (*big.Int, error) { - max, err := s.session.Max() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Max") - Logger.Error(err) - return nil, err - } - - return max, nil -} - -func (s *StorageECR721Fixed) Mint(amount *big.Int) error { - evmTr, err := s.session.Mint(amount) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", Mint) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", Mint, "hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Fixed) RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) { - address, sum, err := s.session.RoyaltyInfo(tokenId, salePrice) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", RoyaltyInfo) - Logger.Error(err) - return "", nil, err - } - - return address.Hex(), sum, nil -} - -func (s *StorageECR721Fixed) MintOwner(amount *big.Int) error { - evmTr, err := s.session.MintOwner(amount) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", MintOwner) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", MintOwner, "hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Fixed) TokenURI(token *big.Int) (string, error) { - tokenURI, err := s.session.TokenURI(token) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", TokenURI) - Logger.Error(err) - return "", err - } - - return tokenURI, nil -} - -func (s *StorageECR721Fixed) TokenURIFallback(token *big.Int) (string, error) { - tokenURI, err := s.session.TokenURIFallback(token) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", TokenURIFallback) - Logger.Error(err) - return "", err - } - - return tokenURI, nil -} - -// Price returns price -func (s *StorageECR721Fixed) Price() (*big.Int, error) { - price, err := s.session.Price() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", Price) - Logger.Error(err) - return nil, err - } - - return price, nil -} - -// SetURI updates uri -func (s *StorageECR721Fixed) SetURI(uri string) error { - evmTr, err := s.session.SetURI(uri) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetURI) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetURI, " hash: ", evmTr.Hash()) - - return nil -} - -// SetAllocation updates allocation -func (s *StorageECR721Fixed) SetAllocation(allocation string) error { - evmTr, err := s.session.SetAllocation(allocation) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetAllocation) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetAllocation, "hash: ", evmTr.Hash()) - - return nil -} - -// SetMintable updates mintable state -func (s *StorageECR721Fixed) SetMintable(status bool) error { - evmTr, err := s.session.SetMintable(status) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetMintable) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetMintable, "hash: ", evmTr.Hash()) - - return nil -} - -// SetRoyalty eth balance from token contract - setReceiver(address receiver_) -func (s *StorageECR721Fixed) SetRoyalty(sum *big.Int) error { - evmTr, err := s.session.SetRoyalty(sum) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetRoyalty) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetRoyalty, " hash: ", evmTr.Hash()) - - return nil -} - -// SetReceiver eth balance from token contract - setReceiver(address receiver_) -func (s *StorageECR721Fixed) SetReceiver(receiver string) error { - address := common.HexToAddress(receiver) - - evmTr, err := s.session.SetReceiver(address) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetReceiver) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetReceiver, " hash: ", evmTr.Hash()) - - return nil -} - -// Withdraw eth balance from token contract - withdraw() -func (s *StorageECR721Fixed) Withdraw() error { - evmTr, err := s.session.Withdraw() - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", Withdraw) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", Withdraw, " hash: ", evmTr.Hash()) - - return nil -} diff --git a/znft/storageerc721pack.go b/znft/storageerc721pack.go deleted file mode 100644 index 2d7b9b498..000000000 --- a/znft/storageerc721pack.go +++ /dev/null @@ -1,344 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - storageerc721pack "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721pack/binding" - - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" -) - -// Solidity Functions -// function mintOwner(uint256 amount) -// function mint(uint256 amount) -// function reveal(uint256 tokenId) external returns (bytes32) -// function withdraw(uint256 tokenId) -// function tokenURI(uint256 tokenId) returns (string memory) -// function tokenURIFallback(uint256 tokenId) returns (string memory) -// function setClosed(string calldata closed_) -// function setOpened(string calldata opened_) - -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 -} - -var ( - _ IStorageECR721Pack = (*StorageECR721Pack)(nil) -) - -type StorageECR721Pack struct { - session *storageerc721pack.BindingSession - ctx context.Context -} - -func (s *StorageECR721Pack) SetURIFallback(uri string) error { - evmTr, err := s.session.SetURIFallback(uri) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetURIFallback") - Logger.Error(err) - return err - } - - Logger.Info("Executed SetURIFallback, hash: ", evmTr.Hash().Hex()) - - return nil -} - -func (s *StorageECR721Pack) Withdraw() error { - evmTr, err := s.session.Withdraw() - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", Withdraw) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", Withdraw, " hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) SetReceiver(receiver string) error { - address := common.HexToAddress(receiver) - - evmTr, err := s.session.SetReceiver(address) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetReceiver) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetReceiver, " hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) SetRoyalty(sum *big.Int) error { - evmTr, err := s.session.SetRoyalty(sum) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetRoyalty) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetRoyalty, " hash: ", SetRoyalty, evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) SetMintable(status bool) error { - evmTr, err := s.session.SetMintable(status) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetMintable) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetMintable, " hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) SetAllocation(allocation string) error { - evmTr, err := s.session.SetAllocation(allocation) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetAllocation) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetAllocation, " hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) SetURI(uri string) error { - evmTr, err := s.session.SetURI(uri) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", SetURI) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", SetURI, "hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) Price() (*big.Int, error) { - price, err := s.session.Price() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", Price) - Logger.Error(err) - return nil, err - } - - return price, nil -} - -func (s *StorageECR721Pack) RoyaltyInfo(tokenId, salePrice *big.Int) (string, *big.Int, error) { - address, sum, err := s.session.RoyaltyInfo(tokenId, salePrice) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", RoyaltyInfo) - Logger.Error(err) - return "", nil, err - } - - return address.Hex(), sum, nil -} - -func (s *StorageECR721Pack) Max() (*big.Int, error) { - max, err := s.session.Max() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Max") - Logger.Error(err) - return nil, err - } - - return max, nil -} - -func (s *StorageECR721Pack) Total() (*big.Int, error) { - total, err := s.session.Total() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Total") - Logger.Error(err) - return nil, err - } - - return total, nil -} - -func (s *StorageECR721Pack) Batch() (*big.Int, error) { - batch, err := s.session.Batch() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Batch") - Logger.Error(err) - return nil, err - } - - return batch, nil -} - -func (s *StorageECR721Pack) Mintable() (bool, error) { - mintable, err := s.session.Mintable() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Mintable") - Logger.Error(err) - return false, err - } - - return mintable, nil -} - -func (s *StorageECR721Pack) Allocation() (string, error) { - allocation, err := s.session.Allocation() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Allocation") - Logger.Error(err) - return "", err - } - - return allocation, nil -} - -func (s *StorageECR721Pack) Uri() (string, error) { - uri, err := s.session.Uri() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "URI") - Logger.Error(err) - return "", err - } - - return uri, nil -} - -func (s *StorageECR721Pack) UriFallback() (string, error) { - uri, err := s.session.UriFallback() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "URIFallback") - Logger.Error(err) - return "", err - } - - return uri, nil -} - -func (s *StorageECR721Pack) Royalty() (*big.Int, error) { - value, err := s.session.Royalty() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Royalty") - Logger.Error(err) - return nil, err - } - - return value, nil -} - -func (s *StorageECR721Pack) Receiver() (string, error) { - value, err := s.session.Receiver() - if err != nil { - err = errors.Wrapf(err, "failed to read %s", "Receiver") - Logger.Error(err) - return "", err - } - - return value.String(), nil -} - -func (s *StorageECR721Pack) MintOwner(amount *big.Int) error { - evmTr, err := s.session.MintOwner(amount) - if err != nil { - return err - } - - Logger.Info("Executed MintOwner, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) Mint(amount *big.Int) error { - evmTr, err := s.session.Mint(amount) - if err != nil { - return err - } - - Logger.Info("Executed Mint, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) Redeem(tokenId *big.Int) error { - evmTr, err := s.session.Redeem(tokenId) - if err != nil { - return err - } - - Logger.Info("Executed Reveal, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) Reveal(tokenId *big.Int) error { - evmTr, err := s.session.Reveal(tokenId) - if err != nil { - return err - } - - Logger.Info("Executed Reveal, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) TokenURI(tokenId *big.Int) (string, error) { - token, err := s.session.TokenURI(tokenId) - if err != nil { - return "", err - } - - Logger.Info("Executed TokenURI, hash: ", token) - - return token, nil -} - -func (s *StorageECR721Pack) TokenURIFallback(tokenId *big.Int) (string, error) { - token, err := s.session.TokenURIFallback(tokenId) - if err != nil { - return "", err - } - - Logger.Info("Executed TokenURIFallback, hash: ", token) - - return token, nil -} - -func (s *StorageECR721Pack) SetClosed(closed string) error { - evmTr, err := s.session.SetClosed(closed) - if err != nil { - return err - } - - Logger.Info("Executed SetClosed, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Pack) SetOpened(opened string) error { - evmTr, err := s.session.SetOpened(opened) - if err != nil { - return err - } - - Logger.Info("Executed SetOpened, hash: ", evmTr.Hash()) - - return nil -} diff --git a/znft/storageerc721random.go b/znft/storageerc721random.go deleted file mode 100644 index 71b295723..000000000 --- a/znft/storageerc721random.go +++ /dev/null @@ -1,154 +0,0 @@ -package znft - -import ( - "context" - "math/big" - - "github.com/ethereum/go-ethereum/common" - - "github.com/pkg/errors" - - storageerc721random "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721random/binding" -) - -// Solidity Functions -// function mintOwner(uint256 amount) -// function mint(uint256 amount) -// function reveal(uint256[] calldata tokens) external returns (bytes32) -// function tokenURI(uint256 tokenId) returns (string memory) -// function tokenURIFallback(uint256 tokenId) returns (string memory) -// function setHidden(string calldata hidden_) -// function setPack(address pack_) -// function setRevealable(bool status_) - -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) -} - -var ( - _ IStorageECR721Random = (*StorageECR721Random)(nil) -) - -type StorageECR721Random struct { - session *storageerc721random.BindingSession - ctx context.Context -} - -func (s *StorageECR721Random) MintOwner(amount *big.Int) error { - evmTr, err := s.session.MintOwner(amount) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", MintOwner) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", MintOwner, " hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Random) Mint(amount *big.Int) error { - evmTr, err := s.session.Mint(amount) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", Mint) - Logger.Error(err) - return err - } - - Logger.Info("Executed ", Mint, "hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Random) Reveal(tokens []*big.Int) error { - evmTr, err := s.session.Reveal(tokens) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "Reveal") - Logger.Error(err) - return err - } - - Logger.Info("Executed Reveal, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Random) TokenURI(token *big.Int) (string, error) { - tokenURI, err := s.session.TokenURI(token) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", TokenURI) - Logger.Error(err) - return "", err - } - - return tokenURI, nil -} - -func (s *StorageECR721Random) TokenURIFallback(token *big.Int) (string, error) { - tokenURI, err := s.session.TokenURIFallback(token) - if err != nil { - err = errors.Wrapf(err, "failed to read %s", TokenURIFallback) - Logger.Error(err) - return "", err - } - - return tokenURI, nil -} - -func (s *StorageECR721Random) SetHidden(hidden string) error { - evmTr, err := s.session.SetHidden(hidden) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetHidden") - Logger.Error(err) - return err - } - - Logger.Info("Executed SetHidden, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Random) SetPack(address common.Address) error { - evmTr, err := s.session.SetPack(address) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetPack") - Logger.Error(err) - return err - } - - Logger.Info("Executed SetPack, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Random) SetRevealable(status bool) error { - evmTr, err := s.session.SetRevealable(status) - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetRevealable") - Logger.Error(err) - return err - } - - Logger.Info("Executed SetRevealable, hash: ", evmTr.Hash()) - - return nil -} - -func (s *StorageECR721Random) Price() (*big.Int, error) { - price, err := s.session.Price() - if err != nil { - err = errors.Wrapf(err, "failed to execute %s", "SetMax") - Logger.Error(err) - return price, err - } - - return price, nil -} diff --git a/znft/transaction.go b/znft/transaction.go deleted file mode 100644 index 6263f6c31..000000000 --- a/znft/transaction.go +++ /dev/null @@ -1,52 +0,0 @@ -package znft - -import ( - "context" - - eth "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" -) - -func (app *Znft) createTransactionWithGasPrice(ctx context.Context, address string, pack []byte) (*bind.TransactOpts, error) { //nolint - gasLimitUnits, err := app.estimateGas(ctx, address, pack) - if err != nil { - return nil, err - } - - transactOpts, err := app.createSignedTransactionFromKeyStoreWithGasPrice(ctx, gasLimitUnits) - - return transactOpts, err -} - -func (app *Znft) createTransaction(ctx context.Context) (*bind.TransactOpts, error) { - transactOpts, err := app.createSignedTransactionFromKeyStore(ctx) - - return transactOpts, err -} - -func (app *Znft) estimateGas(ctx context.Context, address string, pack []byte) (uint64, error) { //nolint - etherClient, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return 0, errors.Wrap(err, "failed to create etherClient") - } - - // To (contract) - contractAddress := common.HexToAddress(address) - - // Gas limits in units - fromAddress := common.HexToAddress(app.cfg.WalletAddress) - - // Estimate gas - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: fromAddress, - Data: pack, - }) - if err != nil { - return 0, errors.Wrap(err, "failed to estimate gas") - } - - return gasLimitUnits, nil -} diff --git a/znft/znft.go b/znft/znft.go deleted file mode 100644 index 62323a8aa..000000000 --- a/znft/znft.go +++ /dev/null @@ -1,505 +0,0 @@ -package znft - -import ( - "context" - "fmt" - "os" - - "github.com/0chain/gosdk_common/core/logger" - - storageerc721 "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721/binding" - storageerc721fixed "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721fixed/binding" - storageerc721pack "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721pack/binding" - storageerc721random "github.com/0chain/gosdk_common/znft/contracts/dstorageerc721random/binding" - - factoryerc721 "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721/binding" - factoryerc721fixed "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721fixed/binding" - factoryerc721pack "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721pack/binding" - factoryerc721random "github.com/0chain/gosdk_common/znft/contracts/factorymoduleerc721random/binding" - - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" -) - -var defaultLogLevel = logger.DEBUG -var Logger logger.Logger - -const ( - ConfigFile = "config.yaml" - WalletDir = "wallets" -) - -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 Znft struct { - cfg *Configuration -} - -func init() { - Logger.Init(defaultLogLevel, "0chain-znft-sdk") -} - -func NewNFTApplication(c *Configuration) *Znft { - return &Znft{c} -} - -func GetConfigDir() string { - var configDir string - home, err := os.UserHomeDir() - if err != nil { - fmt.Println(err) - os.Exit(1) - } - configDir = home + "/.zcn" - return configDir -} - -// Functions used by session factories to create session - -func (app *Znft) constructFactoryERC721(ctx context.Context, address string) (*factoryerc721.Binding, *bind.TransactOpts, error) { - storage, err := app.createFactoryERC721(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", "FactoryERC721") - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructFactoryERC721Fixed(ctx context.Context, address string) (*factoryerc721fixed.Binding, *bind.TransactOpts, error) { - storage, err := app.createFactoryERC721Fixed(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", "FactoryERC721Fixed") - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructFactoryERC721Pack(ctx context.Context, address string) (*factoryerc721pack.Binding, *bind.TransactOpts, error) { - storage, err := app.createFactoryERC721Pack(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", "FactoryERC721Pack") - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructFactoryERC721Random(ctx context.Context, address string) (*factoryerc721random.Binding, *bind.TransactOpts, error) { - storage, err := app.createFactoryERC721Random(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", "FactoryERC721Random") - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructStorageERC721Random(ctx context.Context, address string) (*storageerc721random.Binding, *bind.TransactOpts, error) { - storage, err := app.createStorageERC721Random(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", ContractStorageERC721RandomName) - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructStorageERC721Pack(ctx context.Context, address string) (*storageerc721pack.Binding, *bind.TransactOpts, error) { - storage, err := app.createStorageERC721Pack(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", ContractStorageERC721PackName) - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructStorageERC721Fixed(ctx context.Context, address string) (*storageerc721fixed.Binding, *bind.TransactOpts, error) { - storage, err := app.createStorageERC721Fixed(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", ContractStorageERC721FixedName) - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -func (app *Znft) constructStorageERC721(ctx context.Context, address string) (*storageerc721.Binding, *bind.TransactOpts, error) { - storage, err := app.createStorageERC721(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to construct %s", ContractStorageERC721Name) - } - - transaction, err := app.createTransactOpts(ctx) - - return storage, transaction, err -} - -// Used to create StorageERC721 with preliminary gas estimation -func (app *Znft) constructWithEstimation( //nolint - ctx context.Context, - address string, - method string, - params ...interface{}, -) (*storageerc721.Binding, *bind.TransactOpts, error) { - erc721, err := app.createStorageERC721(address) - if err != nil { - return nil, nil, errors.Wrapf(err, "failed to create %s in method: %s", ContractStorageERC721Name, method) - } - - transaction, err := app.createTransactOptsWithEstimation(ctx, address, method, params) - - return erc721, transaction, err -} - -// Create transaction opts with sender signature -func (app *Znft) createTransactOpts(ctx context.Context) (*bind.TransactOpts, error) { - transaction, err := app.createTransaction(ctx) - if err != nil { - return nil, errors.Wrapf(err, "failed to create createTransactOpts in %s", ContractStorageERC721Name) - } - - return transaction, nil -} - -func (app *Znft) createTransactOptsWithEstimation( //nolint - ctx context.Context, - address, method string, - params ...interface{}, -) (*bind.TransactOpts, error) { - // Get ABI of the contract - abi, err := storageerc721.BindingMetaData.GetAbi() - if err != nil { - return nil, errors.Wrapf(err, "failed to get ABI in %s, method: %s", ContractStorageERC721Name, method) - } - - // Pack the method arguments - pack, err := abi.Pack(method, params...) - if err != nil { - return nil, errors.Wrapf(err, "failed to pack arguments in %s, method: %s", ContractStorageERC721Name, method) - } - - transaction, err := app.createTransactionWithGasPrice(ctx, address, pack) - if err != nil { - return nil, errors.Wrapf(err, "failed to create createTransaction in %s, method: %s", ContractStorageERC721Name, method) - } - - return transaction, nil -} - -// Session factories - -// Factory Sessions - -func (app *Znft) CreateFactoryERC721Session(ctx context.Context, addr string) (IFactoryERC721, error) { - contract, transact, err := app.constructFactoryERC721(ctx, addr) - if err != nil { - return nil, err - } - - session := &factoryerc721.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &FactoryERC721{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -func (app *Znft) CreateFactoryERC721PackSession(ctx context.Context, addr string) (IFactoryPack, error) { - contract, transact, err := app.constructFactoryERC721Pack(ctx, addr) - if err != nil { - return nil, err - } - - session := &factoryerc721pack.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &FactoryPack{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -func (app *Znft) CreateFactoryERC721FixedSession(ctx context.Context, addr string) (IFactoryFixed, error) { - contract, transact, err := app.constructFactoryERC721Fixed(ctx, addr) - if err != nil { - return nil, err - } - - session := &factoryerc721fixed.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &FactoryFixed{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -func (app *Znft) CreateFactoryERC721RandomSession(ctx context.Context, addr string) (IFactoryRandom, error) { - contract, transact, err := app.constructFactoryERC721Random(ctx, addr) - if err != nil { - return nil, err - } - - session := &factoryerc721random.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &FactoryRandom{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -// Storage Sessions - -func (app *Znft) CreateStorageERC721PackSession(ctx context.Context, addr string) (IStorageECR721Pack, error) { - contract, transact, err := app.constructStorageERC721Pack(ctx, addr) - if err != nil { - return nil, err - } - - session := &storageerc721pack.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &StorageECR721Pack{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -func (app *Znft) CreateStorageERC721RandomSession(ctx context.Context, addr string) (IStorageECR721Random, error) { - contract, transact, err := app.constructStorageERC721Random(ctx, addr) - if err != nil { - return nil, err - } - - session := &storageerc721random.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &StorageECR721Random{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -func (app *Znft) CreateStorageERC721FixedSession(ctx context.Context, addr string) (IStorageECR721Fixed, error) { - contract, transact, err := app.constructStorageERC721Fixed(ctx, addr) - if err != nil { - return nil, err - } - - session := &storageerc721fixed.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &StorageECR721Fixed{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -func (app *Znft) CreateStorageERC721Session(ctx context.Context, addr string) (IStorageECR721, error) { - contract, transact, err := app.constructStorageERC721(ctx, addr) - if err != nil { - return nil, err - } - - session := &storageerc721.BindingSession{ - Contract: contract, - CallOpts: bind.CallOpts{ - Pending: true, - From: transact.From, - Context: ctx, - }, - TransactOpts: *transact, - } - - storage := &StorageECR721{ - session: session, - ctx: ctx, - } - - return storage, nil -} - -// Binding factories - -func (app *Znft) createStorageERC721(address string) (*storageerc721.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := storageerc721.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createStorageERC721Fixed(address string) (*storageerc721fixed.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := storageerc721fixed.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createStorageERC721Random(address string) (*storageerc721random.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := storageerc721random.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createStorageERC721Pack(address string) (*storageerc721pack.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := storageerc721pack.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createFactoryERC721(address string) (*factoryerc721.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := factoryerc721.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createFactoryERC721Pack(address string) (*factoryerc721pack.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := factoryerc721pack.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createFactoryERC721Random(address string) (*factoryerc721random.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := factoryerc721random.NewBinding(addr, client) - - return instance, err -} - -func (app *Znft) createFactoryERC721Fixed(address string) (*factoryerc721fixed.Binding, error) { - client, err := CreateEthClient(app.cfg.EthereumNodeURL) - if err != nil { - return nil, err - } - - addr := common.HexToAddress(address) - instance, err := factoryerc721fixed.NewBinding(addr, client) - - return instance, err -} From a0ce8cc0b3b878e912168e18480434daadda7d0b Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 16:06:29 +0530 Subject: [PATCH 070/107] added version --- core/version/.emptydir | 0 core/version/doc.go | 3 +++ core/version/version.go | 5 +++++ mobilesdk/sdk/sdk.go | 2 +- 4 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 core/version/.emptydir create mode 100644 core/version/doc.go create mode 100644 core/version/version.go diff --git a/core/version/.emptydir b/core/version/.emptydir new file mode 100644 index 000000000..e69de29bb diff --git a/core/version/doc.go b/core/version/doc.go new file mode 100644 index 000000000..3c7ff49dc --- /dev/null +++ b/core/version/doc.go @@ -0,0 +1,3 @@ +// AUTOGENERATED! Do not use. +// Provide current version of the SDK +package version diff --git a/core/version/version.go b/core/version/version.go new file mode 100644 index 000000000..fa0af25cc --- /dev/null +++ b/core/version/version.go @@ -0,0 +1,5 @@ +//====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== + +package version + +const VERSIONSTR = "v1.17.11-269-g7fd90660" diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index a5a56da23..fde7cedc6 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -23,7 +23,7 @@ import ( l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk/mobilesdk/zbox" - "github.com/0chain/gosdk_common/mobilesdk/zboxapi" + "github.com/0chain/gosdk/mobilesdk/zboxapi" "github.com/0chain/gosdk_common/zcncore" ) From cd7b1e17b54a14dfac7519d35d05d73ef241dcb2 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 16:31:49 +0530 Subject: [PATCH 071/107] wasm fix --- wasmsdk/common.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/wasmsdk/common.go b/wasmsdk/common.go index 64008c620..a5f22744c 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -89,3 +89,11 @@ func (h *hasher) WriteToValidationMT(_ []byte) error { func (h *hasher) Finalize() error { return nil } + +func (h *hasher) GetBlockHash() (string, error) { + return "", nil +} + +func (h *hasher) WriteToBlockHasher(buf []byte) error { + return nil +} From bdbf983b5095c2781b7eb845e54d9b3d19d85475 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 17:34:50 +0530 Subject: [PATCH 072/107] revert some changes --- wasmsdk/proxy.go | 4 ++-- wasmsdk/sdk.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 49de72ae5..5cc0b15c9 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -216,7 +216,7 @@ func main() { "getLookupHash": getLookupHash, "createThumbnail": createThumbnail, "makeSCRestAPICall": makeSCRestAPICall, - "wasmType": getWasmType, + "getWasmType": getWasmType, //blobber "delete": Delete, @@ -336,7 +336,7 @@ func main() { fmt.Println("__wasm_initialized__ = true;") zcn.Set("__wasm_initialized__", true) - zcn.Set("wasmType", "normal") + zcn.Set("wasmType", "enterprise") } else { PrintError("__zcn_wasm__.sdk is not installed yet") } diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 94a760179..cf4e3d582 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -72,7 +72,7 @@ func getVersion() string { } func getWasmType() string { - return "normal" + return "enterprise" } var sdkLogger *logger.Logger From 3fb79d2814946185bc4faafdd2c690f20bde4df3 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 17:54:39 +0530 Subject: [PATCH 073/107] revert changes --- wasmsdk/demo/index.html | 6 +- wasmsdk/demo/main.go | 13 +- wasmsdk/demo/zcn.js | 9 +- wasmsdk/jsbridge/async.go | 148 ++++++++++++++ wasmsdk/jsbridge/bytes.go | 40 ++++ wasmsdk/jsbridge/doc.go | 3 + wasmsdk/jsbridge/error.go | 23 +++ wasmsdk/jsbridge/file_reader.go | 124 ++++++++++++ wasmsdk/jsbridge/file_writer.go | 241 ++++++++++++++++++++++ wasmsdk/jsbridge/func.go | 171 ++++++++++++++++ wasmsdk/jsbridge/func_test.go | 88 ++++++++ wasmsdk/jsbridge/input.go | 285 ++++++++++++++++++++++++++ wasmsdk/jsbridge/input_test.go | 105 ++++++++++ wasmsdk/jsbridge/object.go | 74 +++++++ wasmsdk/jsbridge/output.go | 100 ++++++++++ wasmsdk/jsbridge/self.go | 24 +++ wasmsdk/jsbridge/sync.go | 103 ++++++++++ wasmsdk/jsbridge/template_data.go | 92 +++++++++ wasmsdk/jsbridge/timer.go | 50 +++++ wasmsdk/jsbridge/vars.go | 26 +++ wasmsdk/jsbridge/webworker.go | 320 ++++++++++++++++++++++++++++++ wasmsdk/jsbridge/zcnworker.js.tpl | 101 ++++++++++ 22 files changed, 2129 insertions(+), 17 deletions(-) create mode 100644 wasmsdk/jsbridge/async.go create mode 100644 wasmsdk/jsbridge/bytes.go create mode 100644 wasmsdk/jsbridge/doc.go create mode 100644 wasmsdk/jsbridge/error.go create mode 100644 wasmsdk/jsbridge/file_reader.go create mode 100644 wasmsdk/jsbridge/file_writer.go create mode 100644 wasmsdk/jsbridge/func.go create mode 100644 wasmsdk/jsbridge/func_test.go create mode 100644 wasmsdk/jsbridge/input.go create mode 100644 wasmsdk/jsbridge/input_test.go create mode 100644 wasmsdk/jsbridge/object.go create mode 100644 wasmsdk/jsbridge/output.go create mode 100644 wasmsdk/jsbridge/self.go create mode 100644 wasmsdk/jsbridge/sync.go create mode 100644 wasmsdk/jsbridge/template_data.go create mode 100644 wasmsdk/jsbridge/timer.go create mode 100644 wasmsdk/jsbridge/vars.go create mode 100644 wasmsdk/jsbridge/webworker.go create mode 100644 wasmsdk/jsbridge/zcnworker.js.tpl diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index e6846532f..b73e91cde 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -241,8 +241,6 @@

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

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

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates let stringifiedArray = JSON.stringify(objects); try { - const results = await goWasm.sdk.multiDownload('', stringifiedArray, '', '') + const results = await goWasm.sdk.multiDownload('', stringifiedArray, 'eyJjbGllbnRfaWQiOiIiLCJvd25lcl9pZCI6IjI2ZTIzMjFhZWMxZmEyZDY1NGQ1MDQ5OWY3ZjhmYWJhNjNkYWMxYTExYTQwZDU3NDJkNDAzMWJmMzEzMzAxMTYiLCJhbGxvY2F0aW9uX2lkIjoiMDAwMzAzOTA1MGI3ZDdiM2FlNmI3MGEwZTVjMWU4ZjRhOTkxNzc1YWJiOTQ2NjljMDg4YzczNzJlMzYwMzkyYiIsImZpbGVfcGF0aF9oYXNoIjoiYWEzODE0NTM2ZWI2OWQwNjU4ZWM0OTgyZmE3ZTIwM2I2ZGI2ZWExYmU4ZmMxODRiMWJhOTZhMTk3NmMwM2JlOCIsImFjdHVhbF9maWxlX2hhc2giOiIxMjUwMjJhZGRiZTIwZDNhOWUzYjcxZTA0NjUzZjY3YiIsImZpbGVfbmFtZSI6InVidW50dS0yMi4wNC40LWxpdmUtc2VydmVyLWFtZDY0LmlzbyIsInJlZmVyZW5jZV90eXBlIjoiZiIsImV4cGlyYXRpb24iOjAsInRpbWVzdGFtcCI6MTcxNjM3ODIxNiwiZW5jcnlwdGVkIjpmYWxzZSwic2lnbmF0dXJlIjoiYmEzNzQ1NzlmZTczZDc1MWIwMTNiMjM2NjUzZDRiMGYyYzNjZDJlYTMyNTFkODg0MmRiNWQxNTlhNjBiN2ExMiJ9', '') console.log(JSON.stringify(results)) } catch (e) { alert(e) diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 02c903934..6c899cdd7 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,13 +7,15 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zcncore" "github.com/uptrace/bunrouter" ) func main() { + zcncore.InitSignatureScheme("bls0chain") + ctx, cf := context.WithCancel(context.Background()) router := bunrouter.New() @@ -34,10 +36,7 @@ func main() { } w.WriteHeader(http.StatusOK) - _, err = w.Write([]byte(wallet)) - if err != nil { - return err - } + w.Write([]byte(wallet)) return nil }) @@ -56,7 +55,7 @@ func main() { } -type statusBar struct { //nolint:unused +type statusBar struct { walletString string wg *sync.WaitGroup success bool diff --git a/wasmsdk/demo/zcn.js b/wasmsdk/demo/zcn.js index 63585cfb9..d64388d24 100644 --- a/wasmsdk/demo/zcn.js +++ b/wasmsdk/demo/zcn.js @@ -308,7 +308,7 @@ async function createWasm() { (_, key) => (...args) => // eslint-disable-next-line - new Promise(async (resolve, reject) => { + new Promise(async (resolve, reject) => { if (!go || go.exited) { return reject(new Error('The Go instance is not active.')) } @@ -368,11 +368,8 @@ async function createWasm() { ) const proxy = { - bulkUpload, - setWallet, - getWalletId, - getPrivateKey, - getPeerPublicKey, + bulkUpload: bulkUpload, + setWallet: setWallet, sdk: sdkProxy, //expose sdk methods for js jsProxy, //expose js methods for go } diff --git a/wasmsdk/jsbridge/async.go b/wasmsdk/jsbridge/async.go new file mode 100644 index 000000000..23d96910a --- /dev/null +++ b/wasmsdk/jsbridge/async.go @@ -0,0 +1,148 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "fmt" + "reflect" + "syscall/js" +) + +type AsyncInvoker func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) + +func Async(funcType reflect.Type) (AsyncInvoker, error) { + + outputBinder, err := NewOutputBuilder(funcType).Build() + if err != nil { + return nil, err + } + + switch funcType.NumOut() { + case 0: + return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { + defer func() { + if r := recover(); r != nil { + fmt.Println("[recover]", r) + } + }() + if err != nil { + jsErr := NewJsError(err.Error()) + resolve.Invoke(js.ValueOf(jsErr)) + return + } + + fn.Call(in) + resolve.Invoke() + + }, nil + case 1: + + outputType := funcType.Out(0) + //func(...)error + if outputType.String() == TypeError { + return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { + defer func() { + if r := recover(); r != nil { + fmt.Println("[recover]", r) + } + }() + if err != nil { + jsErr := NewJsError(err.Error()) + resolve.Invoke(js.ValueOf(jsErr)) + return + } + + output := fn.Call(in) + + if output[0].IsNil() { + resolve.Invoke() + } else { + args := outputBinder(output) + resolve.Invoke(args[0]) + } + }, nil + } else { //func(...) T + return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { + if err != nil { + jsErr := NewJsError(err.Error()) + resolve.Invoke(js.ValueOf(jsErr)) + return + } + + output := fn.Call(in) + args := outputBinder(output) + resolve.Invoke(args[0]) + }, nil + } + case 2: + + errOutputType := funcType.Out(1) + + if errOutputType.String() != TypeError { + return nil, ErrFuncNotSupported + } + //func(...) (T,error) + return func(resolve, reject js.Value, fn reflect.Value, in []reflect.Value, err error) { + defer func() { + if r := recover(); r != nil { + fmt.Println("[recover]", r) + } + }() + if err != nil { + jsErr := NewJsError(err.Error()) + resolve.Invoke(js.ValueOf(jsErr)) + return + } + + output := fn.Call(in) + + args := outputBinder(output) + if output[1].IsNil() { + resolve.Invoke(args[0]) + } else { + resolve.Invoke(args[1]) + } + + }, nil + + default: + return nil, ErrFuncNotSupported + } + +} + +// This function try to execute wasm functions that are wrapped with "Promise" +// see: https://stackoverflow.com/questions/68426700/how-to-wait-a-js-async-function-from-golang-wasm/68427221#comment120939975_68427221 +func Await(awaitable js.Value) ([]js.Value, []js.Value) { + then := make(chan []js.Value) + defer close(then) + thenFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + then <- args + return nil + }) + defer thenFunc.Release() + + catch := make(chan []js.Value) + defer close(catch) + catchFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + errObj := args[0] + + // Print the error value + errValue := errObj.Get("message").String() + fmt.Println("catch error value:", errValue) + + catch <- args + return nil + }) + defer catchFunc.Release() + + awaitable.Call("then", thenFunc).Call("catch", catchFunc) + + select { + case result := <-then: + return result, []js.Value{js.Null()} + case err := <-catch: + return []js.Value{js.Null()}, err + } +} diff --git a/wasmsdk/jsbridge/bytes.go b/wasmsdk/jsbridge/bytes.go new file mode 100644 index 000000000..9a5d74972 --- /dev/null +++ b/wasmsdk/jsbridge/bytes.go @@ -0,0 +1,40 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "strconv" + "strings" +) + +type Bytes struct { + Buffer []byte +} + +func (bytes *Bytes) UnmarshalJSON(buf []byte) error { + + if len(buf) > 0 { + + src := strings.Trim(string(buf), "\"") + + if len(src) > 0 { + items := strings.Split(src, ",") + + bytes.Buffer = make([]byte, len(items)) + + for k, v := range items { + it, err := strconv.ParseUint(v, 10, 64) + if err != nil { + return err + } + + bytes.Buffer[k] = byte(it) + } + + } + + } + + return nil +} 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/jsbridge/error.go b/wasmsdk/jsbridge/error.go new file mode 100644 index 000000000..371f0e71a --- /dev/null +++ b/wasmsdk/jsbridge/error.go @@ -0,0 +1,23 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import "errors" + +var ( + // ErrMismatchedInputLength the length of input are mismatched + ErrMismatchedInputLength = errors.New("binder: mismatched input length") + + // ErrMismatchedOutputLength the length of output are mismatched + ErrMismatchedOutputLength = errors.New("binder: mismatched output length") + + // ErrBinderNotImplemented the type binder is not implemented yet + ErrBinderNotImplemented = errors.New("binder: not impelmented") + + // ErrFuncNotSupported the type function is not supported yet + ErrFuncNotSupported = errors.New("func: not supported") + + // ErrIsNotFunc bind works with func only + ErrIsNotFunc = errors.New("func: bind works with func only") +) diff --git a/wasmsdk/jsbridge/file_reader.go b/wasmsdk/jsbridge/file_reader.go new file mode 100644 index 000000000..17b27a1e7 --- /dev/null +++ b/wasmsdk/jsbridge/file_reader.go @@ -0,0 +1,124 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "errors" + "io" + "syscall/js" + + "github.com/0chain/gosdk/core/common" + "github.com/valyala/bytebufferpool" +) + +type FileReader struct { + size int64 + offset int64 + readChunk js.Value + buf []byte + bufOffset int + chunkReadSize int64 + endOfFile bool +} + +const ( + bufferSize = 16 * 1024 * 1024 //16MB +) + +func NewFileReader(readChunkFuncName string, fileSize, chunkReadSize int64) (*FileReader, error) { + readChunk := js.Global().Get(readChunkFuncName) + return &FileReader{ + size: fileSize, + readChunk: readChunk, + chunkReadSize: chunkReadSize, + }, nil +} + +func (r *FileReader) Read(p []byte) (int, error) { + //js.Value doesn't work in parallel invoke + size := len(p) + if len(r.buf) == 0 && !r.endOfFile { + r.initBuffer() + } + + if len(r.buf)-r.bufOffset < size && !r.endOfFile { + r.bufOffset = 0 //reset buffer offset + result, err := Await(r.readChunk.Invoke(r.offset, len(r.buf))) + + if len(err) > 0 && !err[0].IsNull() { + return 0, errors.New("file_reader: " + err[0].String()) + } + + chunk := result[0] + + n := js.CopyBytesToGo(r.buf, chunk) + r.offset += int64(n) + if n < len(r.buf) { + r.buf = r.buf[:n] + r.endOfFile = true + } + } + + n := copy(p, r.buf[r.bufOffset:]) + r.bufOffset += n + if r.endOfFile && r.bufOffset == len(r.buf) { + buff := &bytebufferpool.ByteBuffer{ + B: r.buf, + } + common.MemPool.Put(buff) + return n, io.EOF + } + + return n, nil +} + +func (r *FileReader) initBuffer() error { + bufSize := r.size + if bufferSize < bufSize { + bufSize = (r.chunkReadSize * (bufferSize / r.chunkReadSize)) + } + buff := common.MemPool.Get() + if cap(buff.B) < int(bufSize) { + buff.B = make([]byte, bufSize) + } + r.buf = buff.B[:bufSize] + result, err := Await(r.readChunk.Invoke(0, len(r.buf))) + + if len(err) > 0 && !err[0].IsNull() { + return errors.New("file_reader: " + err[0].String()) + } + + chunk := result[0] + + n := js.CopyBytesToGo(r.buf, chunk) + r.offset += int64(n) + if n < len(r.buf) { + r.buf = r.buf[:n] + } + r.endOfFile = len(r.buf) == int(r.size) + return nil +} + +func (r *FileReader) Seek(offset int64, whence int) (int64, error) { + + var abs int64 + switch whence { + case io.SeekStart: + abs = offset + case io.SeekCurrent: + abs = r.offset + offset + case io.SeekEnd: + abs = r.size + offset + default: + return 0, errors.New("FileReader.Seek: invalid whence") + } + if abs < 0 { + return 0, errors.New("FileReader.Seek: negative position") + } + if abs > int64(len(r.buf)) { + return 0, errors.New("FileReader.Seek: position out of bounds") + } + r.bufOffset = int(abs) + return abs, nil +} diff --git a/wasmsdk/jsbridge/file_writer.go b/wasmsdk/jsbridge/file_writer.go new file mode 100644 index 000000000..81b69a0c6 --- /dev/null +++ b/wasmsdk/jsbridge/file_writer.go @@ -0,0 +1,241 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "errors" + "io/fs" + "syscall/js" + + "github.com/0chain/gosdk/core/common" + "github.com/valyala/bytebufferpool" +) + +type FileWriter struct { + writableStream js.Value + uint8Array js.Value + fileHandle js.Value + bufLen int + buf []byte + bufWriteOffset int + writeError bool +} + +const writeBlocks = 10 + +// len(p) will always be <= 64KB +func (w *FileWriter) Write(p []byte) (int, error) { + //init buffer if not initialized + if len(w.buf) == 0 { + w.buf = make([]byte, len(p)*writeBlocks) + } + + //copy bytes to buf + if w.bufWriteOffset+len(p) > len(w.buf) { + err := w.flush() + if err != nil { + return 0, err + } + } + n := copy(w.buf[w.bufWriteOffset:], p) + w.bufWriteOffset += n + if w.bufWriteOffset == len(w.buf) { + //write to file + err := w.flush() + if err != nil { + return 0, err + } + } + return len(p), nil +} + +func (w *FileWriter) flush() error { + if w.bufWriteOffset == 0 { + return nil + } + if w.bufLen != w.bufWriteOffset { + w.bufLen = w.bufWriteOffset + w.uint8Array = js.Global().Get("Uint8Array").New(w.bufLen) + } + js.CopyBytesToJS(w.uint8Array, w.buf[:w.bufWriteOffset]) + _, err := Await(w.writableStream.Call("write", w.uint8Array)) + if len(err) > 0 && !err[0].IsNull() { + w.writeError = true + return errors.New("file_writer: " + err[0].String()) + } + //reset buffer + w.bufWriteOffset = 0 + return nil +} + +// func (w *FileWriter) WriteAt(p []byte, offset int64) (int, error) { +// uint8Array := js.Global().Get("Uint8Array").New(len(p)) +// js.CopyBytesToJS(uint8Array, p) +// options := js.Global().Get("Object").New() +// options.Set("type", "write") +// options.Set("position", offset) +// options.Set("data", uint8Array) +// options.Set("size", len(p)) +// _, err := Await(w.writableStream.Call("write", options)) +// if len(err) > 0 && !err[0].IsNull() { +// return 0, errors.New("file_writer: " + err[0].String()) +// } +// return len(p), nil +// } + +func (w *FileWriter) Close() error { + + if w.bufWriteOffset > 0 && !w.writeError { + w.buf = w.buf[:w.bufWriteOffset] + uint8Array := js.Global().Get("Uint8Array").New(len(w.buf)) + js.CopyBytesToJS(uint8Array, w.buf) + _, err := Await(w.writableStream.Call("write", uint8Array)) + if len(err) > 0 && !err[0].IsNull() { + return errors.New("file_writer: " + err[0].String()) + } + } + + _, err := Await(w.writableStream.Call("close")) + if len(err) > 0 && !err[0].IsNull() { + return errors.New("file_writer: " + err[0].String()) + } + return nil +} + +func (w *FileWriter) Read(p []byte) (int, error) { + return 0, errors.New("file_writer: not supported") +} + +func (w *FileWriter) Seek(offset int64, whence int) (int64, error) { + return 0, nil +} + +func (w *FileWriter) Sync() error { + return nil +} + +func (w *FileWriter) Stat() (fs.FileInfo, error) { + return nil, nil +} + +func NewFileWriter(filename string) (*FileWriter, error) { + + if !js.Global().Get("window").Get("showSaveFilePicker").Truthy() || !js.Global().Get("window").Get("WritableStream").Truthy() { + return nil, errors.New("file_writer: not supported") + } + + showSaveFilePicker := js.Global().Get("window").Get("showSaveFilePicker") + //create options with suggested name + options := js.Global().Get("Object").New() + options.Set("suggestedName", filename) + + //request a file handle + fileHandle, err := Await(showSaveFilePicker.Invoke(options)) + if len(err) > 0 && !err[0].IsNull() { + return nil, errors.New("file_writer: " + err[0].String()) + } + //create a writable stream + writableStream, err := Await(fileHandle[0].Call("createWritable")) + if len(err) > 0 && !err[0].IsNull() { + return nil, errors.New("file_writer: " + err[0].String()) + } + return &FileWriter{ + writableStream: writableStream[0], + fileHandle: fileHandle[0], + }, nil +} + +func NewFileWriterFromHandle(dirHandler js.Value, name string) (*FileWriter, error) { + options := js.Global().Get("Object").New() + options.Set("create", true) + fileHandler, err := Await(dirHandler.Call("getFileHandle", name, options)) + if len(err) > 0 && !err[0].IsNull() { + return nil, errors.New("dir_picker: " + err[0].String()) + } + + writableStream, err := Await(fileHandler[0].Call("createWritable")) + if len(err) > 0 && !err[0].IsNull() { + return nil, errors.New("file_writer: " + err[0].String()) + } + return &FileWriter{ + writableStream: writableStream[0], + fileHandle: fileHandler[0], + }, nil +} + +type FileCallbackWriter struct { + writeChunk js.Value + buf []byte + offset int64 + lookupHash string +} + +const bufCallbackCap = 4 * 1024 * 1024 //4MB + +func NewFileCallbackWriter(writeChunkFuncName, lookupHash string) *FileCallbackWriter { + writeChunk := js.Global().Get(writeChunkFuncName) + if !writeChunk.Truthy() { + return nil + } + return &FileCallbackWriter{ + writeChunk: writeChunk, + lookupHash: lookupHash, + } +} + +func (wc *FileCallbackWriter) Write(p []byte) (int, error) { + if len(wc.buf) == 0 { + buff := common.MemPool.Get() + if cap(buff.B) < bufCallbackCap { + buff.B = make([]byte, 0, bufCallbackCap) + } + wc.buf = buff.B + } + if len(wc.buf)+len(p) > cap(wc.buf) { + uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) + js.CopyBytesToJS(uint8Array, wc.buf) + _, err := Await(wc.writeChunk.Invoke(wc.lookupHash, uint8Array, wc.offset)) + if len(err) > 0 && !err[0].IsNull() { + return 0, errors.New("file_writer: " + err[0].String()) + } + wc.offset += int64(len(wc.buf)) + wc.buf = wc.buf[:0] + } + wc.buf = append(wc.buf, p...) + return len(p), nil +} + +func (wc *FileCallbackWriter) Close() error { + if len(wc.buf) > 0 { + uint8Array := js.Global().Get("Uint8Array").New(len(wc.buf)) + js.CopyBytesToJS(uint8Array, wc.buf) + _, err := Await(wc.writeChunk.Invoke(wc.lookupHash, uint8Array, wc.offset)) + if len(err) > 0 && !err[0].IsNull() { + return errors.New("file_writer: " + err[0].String()) + } + wc.offset += int64(len(wc.buf)) + wc.buf = wc.buf[:0] + } + buff := &bytebufferpool.ByteBuffer{ + B: wc.buf, + } + common.MemPool.Put(buff) + return nil +} + +func (wc *FileCallbackWriter) Read(p []byte) (int, error) { + return 0, errors.New("file_writer: not supported") +} + +func (wc *FileCallbackWriter) Seek(offset int64, whence int) (int64, error) { + return 0, nil +} + +func (wc *FileCallbackWriter) Sync() error { + return nil +} + +func (wc *FileCallbackWriter) Stat() (fs.FileInfo, error) { + return nil, nil +} diff --git a/wasmsdk/jsbridge/func.go b/wasmsdk/jsbridge/func.go new file mode 100644 index 000000000..bc4f08429 --- /dev/null +++ b/wasmsdk/jsbridge/func.go @@ -0,0 +1,171 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "fmt" + "log" + "reflect" + "syscall/js" +) + +// BindFunc bind go func to js func in global +// only support +// - func(...) +// - func(...) error +// - func(...) T +// - func(...) (T,error) +func BindFunc(global js.Value, jsFuncName string, fn interface{}) error { + + jsFunc, err := promise(fn) + if err != nil { + return err + } + + global.Set(jsFuncName, jsFunc) + + return nil +} + +func BindAsyncFuncs(global js.Value, fnList map[string]interface{}) { + + for jsFuncName, fn := range fnList { + if jsFuncName == "registerAuthorizer" || jsFuncName == "callAuth" || jsFuncName == "registerAuthCommon" { + global.Set(jsFuncName, fn) + } else { + jsFunc, err := promise(fn) + + if err != nil { + log.Println("bridge promise failed:", jsFuncName, err) + } + + global.Set(jsFuncName, jsFunc) + } + } +} + +func BindFuncs(global js.Value, fnList map[string]interface{}) { + + for jsFuncName, fn := range fnList { + jsFunc, err := invoke(fn) + + if err != nil { + log.Println("[", jsFuncName, "]", err) + continue + } + + global.Set(jsFuncName, jsFunc) + } + +} + +func invoke(fn interface{}) (js.Func, error) { + funcType := reflect.TypeOf(fn) + + if funcType.Kind() != reflect.Func { + return js.Func{}, ErrIsNotFunc + } + + numOut := funcType.NumOut() + + if numOut > 2 { + return js.Func{}, ErrFuncNotSupported + } + + syncInvoker, err := Sync(funcType) + + if err != nil { + return js.Func{}, err + } + + invoker := reflect.ValueOf(fn) + + if err != nil { + return js.Func{}, err + } + + inputBuilder, err := NewInputBuilder(funcType).Build() + + if err != nil { + return js.Func{}, err + } + + jsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + defer func() { + if r := recover(); r != nil { + fmt.Println("[recover]", r) + } + }() + + in, err := inputBuilder(args) + if err != nil { + return NewJsError(err.Error()) + } + + result := syncInvoker(invoker, in) + + return result + }) + + jsFuncList = append(jsFuncList, jsFunc) + + return jsFunc, nil +} + +func promise(fn interface{}) (js.Func, error) { + funcType := reflect.TypeOf(fn) + + if funcType.Kind() != reflect.Func { + return js.Func{}, ErrIsNotFunc + } + + numOut := funcType.NumOut() + + if numOut > 2 { + return js.Func{}, ErrFuncNotSupported + } + + awaiter, err := Async(funcType) + + if err != nil { + return js.Func{}, err + } + + inputBuilder, err := NewInputBuilder(funcType).Build() + + if err != nil { + return js.Func{}, err + } + + invoker := reflect.ValueOf(fn) + + jsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + + defer func() { + if r := recover(); r != nil { + fmt.Println("[recover]", r) + } + }() + + in, err := inputBuilder(args) + + handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + resolve := args[0] + reject := args[1] + + go awaiter(resolve, reject, invoker, in, err) + + return nil + }) + + jsFuncList = append(jsFuncList, handler) + + promise := js.Global().Get("Promise") + return promise.New(handler) + }) + + jsFuncList = append(jsFuncList, jsFunc) + + return jsFunc, nil +} diff --git a/wasmsdk/jsbridge/func_test.go b/wasmsdk/jsbridge/func_test.go new file mode 100644 index 000000000..e1a41a72e --- /dev/null +++ b/wasmsdk/jsbridge/func_test.go @@ -0,0 +1,88 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "syscall/js" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBindAsyncFunc(t *testing.T) { + tests := []struct { + Name string + Func func() js.Func + Output func(outputs []js.Value) interface{} + Result interface{} + }{ + {Name: "ReturnString", Func: func() js.Func { + fn, _ := promise(func() string { + return "ReturnString" + }) + + return fn + }, Output: func(outputs []js.Value) interface{} { + return outputs[0].String() + }, Result: "ReturnString"}, + {Name: "ReturnInt", Func: func() js.Func { + fn, _ := promise(func() int { + return 1 + }) + + return fn + }, Output: func(outputs []js.Value) interface{} { + return outputs[0].Int() + }, Result: 1}, + {Name: "ReturnInt32", Func: func() js.Func { + fn, _ := promise(func() int32 { + return int32(1) + }) + + return fn + }, Output: func(outputs []js.Value) interface{} { + return int32(outputs[0].Int()) + }, Result: int32(1)}, + {Name: "ReturnInt64", Func: func() js.Func { + fn, _ := promise(func() int64 { + return int64(1) + }) + + return fn + }, Output: func(outputs []js.Value) interface{} { + return int64(outputs[0].Int()) + }, Result: int64(1)}, + {Name: "ReturnFloat32", Func: func() js.Func { + fn, _ := promise(func() float32 { + return float32(1) + }) + + return fn + }, Output: func(outputs []js.Value) interface{} { + return float32(outputs[0].Float()) + }, Result: float32(1)}, + {Name: "ReturnFloat64", Func: func() js.Func { + fn, _ := promise(func() float64 { + return float64(1) + }) + + return fn + }, Output: func(outputs []js.Value) interface{} { + return outputs[0].Float() + }, Result: float64(1)}, + } + + for _, it := range tests { + t.Run(it.Name, func(test *testing.T) { + + jsFunc := it.Func() + + outputs, _ := Await(jsFunc.Invoke()) + + require.Equal(test, it.Result, it.Output(outputs)) + + }) + } + +} diff --git a/wasmsdk/jsbridge/input.go b/wasmsdk/jsbridge/input.go new file mode 100644 index 000000000..5b3fb5831 --- /dev/null +++ b/wasmsdk/jsbridge/input.go @@ -0,0 +1,285 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "fmt" + "reflect" + "syscall/js" +) + +// InputBinder convert inputs from js.Value to reflect.Value +type InputBinder func([]js.Value) ([]reflect.Value, error) + +// InputBuilder binder builder +type InputBuilder struct { + fn reflect.Type + numIn int + IsVariadic bool + binders []func(jv js.Value) (reflect.Value, error) +} + +// NewInputBuilder create InputBuilder +func NewInputBuilder(fn reflect.Type) *InputBuilder { + return &InputBuilder{ + fn: fn, + numIn: fn.NumIn(), + IsVariadic: fn.IsVariadic(), + } +} + +// Build build InputBinder +// js.ValueOf returns x as a JavaScript value: +// +// | Go | JavaScript | +// | ---------------------- | ---------------------- | +// | js.Value | [its value] | +// | js.Func | function | +// | nil | null | +// | bool | boolean | +// | integers and floats | number | +// | string | string | +// | []interface{} | new array | +// | map[string]interface{} | new object | +// +// Panics if x is not one of the expected types. +func (b *InputBuilder) Build() (InputBinder, error) { + defer func() { + if r := recover(); r != nil { + fmt.Println("[recover]InputBuilder.Build: ", r) + } + }() + + b.binders = make([]func(jv js.Value) (reflect.Value, error), b.numIn) + + if b.IsVariadic { + b.numIn-- + } + + for i := 0; i < b.numIn; i++ { + inputType := b.fn.In(i) + + v := reflect.New(inputType).Interface() + + switch v.(type) { + case *string: + b.binders[i] = jsValueToString + + case *int: + b.binders[i] = jsValueToInt + case *int32: + b.binders[i] = jsValueToInt32 + case *int64: + b.binders[i] = jsValueToInt64 + case *uint64: + b.binders[i] = jsValueToUInt64 + case *float32: + b.binders[i] = jsValueToFloat32 + case *float64: + b.binders[i] = jsValueToFloat64 + case *bool: + b.binders[i] = jsValueToBool + case *[]string: + b.binders[i] = jsValueToStringSlice + case *[]byte: + b.binders[i] = jsValueToBytes + default: + fmt.Printf("TYPE: %#v\n", reflect.TypeOf(v)) + return nil, ErrBinderNotImplemented + } + + } + + return b.Bind, nil +} + +// Bind bind js inputs to reflect values +func (b *InputBuilder) Bind(args []js.Value) ([]reflect.Value, error) { + if len(args) != b.numIn { + fmt.Println("args:", args) + return nil, ErrMismatchedInputLength + } + + values := make([]reflect.Value, b.numIn) + for i := 0; i < b.numIn; i++ { + val, err := b.binders[i](args[i]) + if err != nil { + return nil, err + } + values[i] = val + } + + return values, nil +} + +func jsValueToString(jv js.Value) (val reflect.Value, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + + i := "" + if jv.Truthy() { + i = jv.String() + } + + val = reflect.ValueOf(i) + return +} + +func jsValueToInt(jv js.Value) (val reflect.Value, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + i := 0 + if jv.Truthy() { + i = jv.Int() + } + + val = reflect.ValueOf(i) + return +} + +func jsValueToInt32(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + i := 0 + if jv.Truthy() { + i = jv.Int() + } + + val = reflect.ValueOf(int32(i)) + return +} + +func jsValueToInt64(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + i := 0 + if jv.Truthy() { + i = jv.Int() + } + + val = reflect.ValueOf(int64(i)) + return +} + +func jsValueToUInt64(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + i := 0 + if jv.Truthy() { + i = jv.Int() + } + + val = reflect.ValueOf(uint64(i)) + return +} + +func jsValueToBool(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + i := false + if jv.Truthy() { + i = jv.Bool() + } + + val = reflect.ValueOf(i) + return +} + +func jsValueToFloat32(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + var i float64 + if jv.Truthy() { + i = jv.Float() + } + + val = reflect.ValueOf(float32(i)) + return +} + +func jsValueToFloat64(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + var i float64 + if jv.Truthy() { + i = jv.Float() + } + + val = reflect.ValueOf(i) + return +} + +func jsValueToStringSlice(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + var list []string + + if jv.Truthy() { + if js.Global().Get("Array").Call("isArray", jv).Bool() { + list = make([]string, jv.Length()) + for i := 0; i < len(list); i++ { + it := jv.Index(i) + if it.Truthy() { + list[i] = it.String() + } + } + } + } + + val = reflect.ValueOf(list) + return +} + +func jsValueToBytes(jv js.Value) (val reflect.Value, err error) { + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("input: %s", r) + } + }() + + var buf []byte + + if jv.Truthy() { + buf = make([]byte, jv.Length()) + js.CopyBytesToGo(buf, jv) + } + + val = reflect.ValueOf(buf) + return +} diff --git a/wasmsdk/jsbridge/input_test.go b/wasmsdk/jsbridge/input_test.go new file mode 100644 index 000000000..36665bbc4 --- /dev/null +++ b/wasmsdk/jsbridge/input_test.go @@ -0,0 +1,105 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "crypto/rand" + "encoding/hex" + "reflect" + "strings" + "syscall/js" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestInputBinder(t *testing.T) { + + buf := make([]byte, 100) + rand.Read(buf) //nolint + + tests := []struct { + Name string + In []js.Value + Out interface{} + Func func() reflect.Value + }{ + {Name: "string", Func: func() reflect.Value { + fn := func(i string) string { + return i + } + + return reflect.ValueOf(fn) + }, In: []js.Value{js.ValueOf("1")}, Out: "1"}, + + {Name: "int", Func: func() reflect.Value { + fn := func(i int) int { + return i + } + + return reflect.ValueOf(fn) + }, In: []js.Value{js.ValueOf(1)}, Out: 1}, + {Name: "int32", Func: func() reflect.Value { + fn := func(i int32) int32 { + return i + } + + return reflect.ValueOf(fn) + }, In: []js.Value{js.ValueOf(1)}, Out: int32(1)}, + {Name: "int64", Func: func() reflect.Value { + fn := func(i int64) int64 { + return i + } + + return reflect.ValueOf(fn) + }, In: []js.Value{js.ValueOf(1)}, Out: int64(1)}, + + {Name: "float32", Func: func() reflect.Value { + fn := func(i float32) float32 { + return i + } + + return reflect.ValueOf(fn) + }, In: []js.Value{js.ValueOf(1)}, Out: float32(1)}, + {Name: "float64", Func: func() reflect.Value { + fn := func(i float64) float64 { + return i + } + + return reflect.ValueOf(fn) + }, In: []js.Value{js.ValueOf(1)}, Out: float64(1)}, + {Name: "[]string", Func: func() reflect.Value { + fn := func(list []string) string { + return strings.Join(list, ",") + } + + return reflect.ValueOf(fn) + }, In: []js.Value{NewArray("a", "b")}, Out: "a,b"}, + {Name: "[]byte", Func: func() reflect.Value { + fn := func(buf []byte) string { + return hex.EncodeToString(buf) + } + + return reflect.ValueOf(fn) + }, In: []js.Value{NewBytes(buf)}, Out: hex.EncodeToString(buf)}, + } + + for _, it := range tests { + t.Run(it.Name, func(test *testing.T) { + fn := it.Func() + b, err := NewInputBuilder(fn.Type()).Build() + + require.NoError(test, err) + + in, err := b(it.In) + require.NoError(test, err) + + out := fn.Call(in) + + require.Equal(test, it.Out, out[0].Interface()) + + }) + } + +} diff --git a/wasmsdk/jsbridge/object.go b/wasmsdk/jsbridge/object.go new file mode 100644 index 000000000..cdae12a86 --- /dev/null +++ b/wasmsdk/jsbridge/object.go @@ -0,0 +1,74 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "encoding/json" + "fmt" + "syscall/js" +) + +func NewArray(items ...interface{}) js.Value { + + defer func() { + if r := recover(); r != nil { + fmt.Println("NewStrings: ", r) + } + }() + + list := js.Global().Get("Array").New() + + for _, it := range items { + list.Call("push", js.ValueOf(it)) + } + + return list +} + +func NewJsError(message interface{}) js.Value { + return js.ValueOf(map[string]interface{}{ + "error": fmt.Sprint(message), + }) +} + +func NewObject(obj interface{}) js.Value { + buf, err := json.Marshal(obj) + if err != nil { + return js.Null() + } + + j := js.Global().Get("JSON") + + return j.Call("parse", string(buf)) +} + +func NewBytes(buf []byte) js.Value { + + uint8Array := js.Global().Get("Uint8Array").New(len(buf)) + + js.CopyBytesToJS(uint8Array, buf) + + return uint8Array +} + +// var arrayBuffer = new ArrayBuffer(100); +// var uint8Array = new Uint8Array(arrayBuffer); +// for (var i = 0; i < 100; i++) { +// uint8Array[i] = i; +// } + +// var blob = new Blob([uint8Array], { type: "image/png" }); +// var blobVal = URL.createObjectURL(blob); +// func CreateObjectURL(buf []byte) string { +// j := js.Global().Get("URL") + +// options := js.Global().Get("Object").New() +// options.Set("type", "") + +// blob := js.Global().Get("Blob").New(args ...interface{}) + +// u := j.Call("createObjectURL", object) + +// return u.String() +// } diff --git a/wasmsdk/jsbridge/output.go b/wasmsdk/jsbridge/output.go new file mode 100644 index 000000000..6e2560523 --- /dev/null +++ b/wasmsdk/jsbridge/output.go @@ -0,0 +1,100 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "reflect" + "syscall/js" +) + +// OutputBinder convert Outputs from js.Value to reflect.Value +type OutputBinder func([]reflect.Value) []js.Value + +// OutputBuilder binder builder +type OutputBuilder struct { + fn reflect.Type + numOut int + binders []func(rv reflect.Value) js.Value +} + +// NewOutputBuilder create OutputBuilder +func NewOutputBuilder(fn reflect.Type) *OutputBuilder { + return &OutputBuilder{ + fn: fn, + numOut: fn.NumOut(), + } +} + +// Build build OutputBinder +// js.ValueOf returns x as a JavaScript value: +// +// | Go | JavaScript | +// | ---------------------- | ---------------------- | +// | js.Value | [its value] | +// | js.Func | function | +// | nil | null | +// | bool | boolean | +// | integers and floats | number | +// | string | string | +// | []interface{} | new array | +// | map[string]interface{} | new object | +// +// Panics if x is not one of the expected types. +func (b *OutputBuilder) Build() (OutputBinder, error) { + + b.binders = make([]func(rv reflect.Value) js.Value, b.numOut) + + for i := 0; i < b.numOut; i++ { + outputType := b.fn.Out(i) + + // TODO: Fast path for basic types that do not require reflection. + switch outputType.String() { + case TypeError: + b.binders[i] = func(rv reflect.Value) js.Value { + if rv.IsNil() { + return js.Null() + } + + err := rv.Interface().(error) + if err != nil { + jsErr := NewJsError(err.Error()) + return js.ValueOf(jsErr) + } + return js.Null() + + } + case TypeBytes: + b.binders[i] = func(rv reflect.Value) js.Value { + if rv.IsNil() { + return js.Null() + } + + buf := rv.Interface().([]byte) + + return NewBytes(buf) + + } + default: + b.binders[i] = func(rv reflect.Value) js.Value { + + if rv.CanInterface() && rv.Interface() == nil { + return js.Null() + } + + return NewObject(rv.Interface()) + } + } + } + + return b.Bind, nil +} + +// Bind bind js Outputs to reflect values +func (b *OutputBuilder) Bind(args []reflect.Value) []js.Value { + values := make([]js.Value, b.numOut) + for i := 0; i < b.numOut; i++ { + values[i] = b.binders[i](args[i]) + } + return values +} diff --git a/wasmsdk/jsbridge/self.go b/wasmsdk/jsbridge/self.go new file mode 100644 index 000000000..f3d979b91 --- /dev/null +++ b/wasmsdk/jsbridge/self.go @@ -0,0 +1,24 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "github.com/hack-pad/go-webworkers/worker" +) + +var ( + selfWorker *worker.GlobalSelf +) + +func NewSelfWorker() (*worker.GlobalSelf, error) { + worker, err := worker.Self() + if worker != nil { + selfWorker = worker + } + return selfWorker, err +} + +func GetSelfWorker() *worker.GlobalSelf { + return selfWorker +} diff --git a/wasmsdk/jsbridge/sync.go b/wasmsdk/jsbridge/sync.go new file mode 100644 index 000000000..ca0c1a7b8 --- /dev/null +++ b/wasmsdk/jsbridge/sync.go @@ -0,0 +1,103 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "reflect" + "syscall/js" +) + +type SyncInvoker func(fn reflect.Value, in []reflect.Value) js.Value + +func Sync(funcType reflect.Type) (SyncInvoker, error) { + outputBinder, err := NewOutputBuilder(funcType).Build() + if err != nil { + return nil, err + } + + switch funcType.NumOut() { + case 0: + return func(fn reflect.Value, in []reflect.Value) (result js.Value) { + + defer func() { + if r := recover(); r != nil { + result = NewJsError(r) + } + }() + + fn.Call(in) + + return + + }, nil + case 1: + outputType := funcType.Out(0) + //func(...)error + if outputType.String() == TypeError { + return func(fn reflect.Value, in []reflect.Value) (result js.Value) { + + defer func() { + if r := recover(); r != nil { + result = NewJsError(r) + } + }() + + err := fn.Call(in)[0] + + // err != nil + if !err.IsNil() { + result = NewJsError(err.Interface()) + } + + return + }, nil + } else { //func(...) T + return func(fn reflect.Value, in []reflect.Value) (result js.Value) { + + defer func() { + if r := recover(); r != nil { + result = NewJsError(r) + } + }() + + output := fn.Call(in) + + result = outputBinder(output)[0] + + return + + }, nil + } + case 2: + + errOutputType := funcType.Out(1) + + if errOutputType.String() != TypeError { + return nil, ErrFuncNotSupported + } + //func(...) (T,error) + return func(fn reflect.Value, in []reflect.Value) (result js.Value) { + defer func() { + if r := recover(); r != nil { + result = NewJsError(r) + } + }() + output := fn.Call(in) + + err := output[1] + + // err == nil + if err.IsNil() { + result = outputBinder(output)[0] + } else { + result = NewJsError(err.Interface()) + } + + return + }, nil + + default: + return nil, ErrFuncNotSupported + } +} diff --git a/wasmsdk/jsbridge/template_data.go b/wasmsdk/jsbridge/template_data.go new file mode 100644 index 000000000..c1723ff18 --- /dev/null +++ b/wasmsdk/jsbridge/template_data.go @@ -0,0 +1,92 @@ +//go:build js && wasm + +package jsbridge + +import ( + "bytes" + _ "embed" + "fmt" + "net/url" + "os" + "path" + "strings" + "syscall/js" + "text/template" + + "github.com/0chain/gosdk/core/version" +) + +//go:embed zcnworker.js.tpl +var WorkerJSTpl []byte + +func buildWorkerJS(args, env []string, path string) (string, error) { + return buildJS(args, env, path, WorkerJSTpl) +} + +func buildJS(args, env []string, wasmPath string, tpl []byte) (string, error) { + var workerJS bytes.Buffer + + if len(args) == 0 { + args = []string{wasmPath} + } + + if len(env) == 0 { + env = os.Environ() + } + var cachePath string + if uRL, err := url.ParseRequestURI(wasmPath); err != nil || !uRL.IsAbs() { + origin := js.Global().Get("location").Get("origin").String() + u, err := url.Parse(origin) + if err != nil { + return "", err + } + u.Path = path.Join(u.Path, wasmPath) + cachePath = u.String() + params := url.Values{} + params.Add("v", version.VERSIONSTR) + u.RawQuery = params.Encode() + wasmPath = u.String() + } + suffix := os.Getenv("SUFFIX") + if suffix == "" { + suffix = "dev" + } + cdnPath := fmt.Sprintf("https://webapps-staticfiles.s3.us-east-2.amazonaws.com/%s/enterprise-zcn.wasm", suffix) + data := templateData{ + Path: cdnPath, + Args: args, + Env: env, + FallbackPath: wasmPath, + CachePath: cachePath, + } + if err := template.Must(template.New("js").Parse(string(tpl))).Execute(&workerJS, data); err != nil { + return "", err + } + return workerJS.String(), nil +} + +type templateData struct { + Path string + Args []string + Env []string + FallbackPath string + CachePath string +} + +func (d templateData) ArgsToJS() string { + el := []string{} + for _, e := range d.Args { + el = append(el, `"`+e+`"`) + } + return "[" + strings.Join(el, ",") + "]" +} + +func (d templateData) EnvToJS() string { + el := []string{} + for _, entry := range d.Env { + if k, v, ok := strings.Cut(entry, "="); ok { + el = append(el, fmt.Sprintf(`"%s":"%s"`, k, v)) + } + } + return "{" + strings.Join(el, ",") + "}" +} diff --git a/wasmsdk/jsbridge/timer.go b/wasmsdk/jsbridge/timer.go new file mode 100644 index 000000000..289e2ad90 --- /dev/null +++ b/wasmsdk/jsbridge/timer.go @@ -0,0 +1,50 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "sync" + "syscall/js" + "time" +) + +type Timer struct { + sync.Mutex + id js.Value + enabled bool + interval time.Duration + callback func() +} + +func NewTimer(interval time.Duration, callback func()) *Timer { + return &Timer{ + interval: interval, + callback: callback, + } +} + +func (t *Timer) Start() { + t.Lock() + defer t.Unlock() + + if !t.enabled { + cb, _ := promise(t.updated) + t.id = js.Global().Call("setInterval", cb, t.interval.Milliseconds()) + t.enabled = true + } +} + +func (t *Timer) Stop() { + if t.enabled { + js.Global().Call("clearInterval", t.id) + } + + t.enabled = false +} + +func (t *Timer) updated() { + if t.enabled { + t.callback() + } +} diff --git a/wasmsdk/jsbridge/vars.go b/wasmsdk/jsbridge/vars.go new file mode 100644 index 000000000..99d42a24e --- /dev/null +++ b/wasmsdk/jsbridge/vars.go @@ -0,0 +1,26 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "reflect" + "syscall/js" +) + +var ( + jsFuncList = make([]js.Func, 0, 200) +) + +var ( + TypeFunc = reflect.TypeOf(func() {}).String() + TypeError = "error" + TypeString = reflect.TypeOf("string").String() + TypeBytes = reflect.TypeOf([]byte{}).String() +) + +func Close() { + for _, fn := range jsFuncList { + fn.Release() + } +} diff --git a/wasmsdk/jsbridge/webworker.go b/wasmsdk/jsbridge/webworker.go new file mode 100644 index 000000000..33d281ab7 --- /dev/null +++ b/wasmsdk/jsbridge/webworker.go @@ -0,0 +1,320 @@ +//go:build js && wasm +// +build js,wasm + +package jsbridge + +import ( + "context" + "errors" + "fmt" + "strconv" + "sync" + "syscall/js" + + "github.com/google/uuid" + "github.com/hack-pad/go-webworkers/worker" + "github.com/hack-pad/safejs" +) + +const ( + MsgTypeAuth = "auth" + MsgTypeAuthRsp = "auth_rsp" + MsgTypeUpload = "upload" + MsgTypeUpdateWallet = "update_wallet" +) + +type WasmWebWorker struct { + // Name specifies an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes. + // If this is not specified, `Start` will create a UUIDv4 for it and populate back. + Name string + + // Path is the path of the WASM to run as the Web Worker. + // This can be a relative path on the server, or an abosolute URL. + Path string + + // Args holds command line arguments, including the WASM as Args[0]. + // If the Args field is empty or nil, Run uses {Path}. + Args []string + + // Env specifies the environment of the process. + // Each entry is of the form "key=value". + // If Env is nil, the new Web Worker uses the current context's + // environment. + // If Env contains duplicate environment keys, only the last + // value in the slice for each duplicate key is used. + Env []string + worker *worker.Worker + + // For subscribing to events + ctx context.Context + cancelContext context.CancelFunc + subscribers map[string]chan worker.MessageEvent + numberOfSubs int + subMutex sync.Mutex + + //isTerminated bool + isTerminated bool +} + +var ( + workers = make(map[string]*WasmWebWorker) + gZauthServer string +) + +func NewWasmWebWorker(blobberID, blobberURL, clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) (*WasmWebWorker, bool, error) { + created := false + _, ok := workers[blobberID] + if ok { + return workers[blobberID], created, nil + } + + fmt.Println("New wasm web worker, zauth server:", gZauthServer) + w := &WasmWebWorker{ + Name: blobberURL, + Env: []string{"BLOBBER_URL=" + blobberURL, + "CLIENT_ID=" + clientID, + "CLIENT_KEY=" + clientKey, + "PEER_PUBLIC_KEY=" + peerPublicKey, + "PRIVATE_KEY=" + privateKey, + "MODE=worker", + "PUBLIC_KEY=" + publicKey, + "IS_SPLIT=" + strconv.FormatBool(isSplit), + "MNEMONIC=" + mnemonic, + "ZAUTH_SERVER=" + gZauthServer}, + Path: "enterprise-zcn.wasm", + subscribers: make(map[string]chan worker.MessageEvent), + } + + if err := w.Start(); err != nil { + return nil, created, err + } + workers[blobberID] = w + created = true + return w, created, nil +} + +func GetWorker(blobberID string) *WasmWebWorker { + return workers[blobberID] +} + +func RemoveWorker(blobberID string) { + worker, ok := workers[blobberID] + if ok { + worker.subMutex.Lock() + if worker.numberOfSubs == 0 { + worker.Terminate() + delete(workers, blobberID) + worker.isTerminated = true + } + worker.subMutex.Unlock() + } +} + +// pass a buffered channel to subscribe to events so that the caller is not blocked +func (ww *WasmWebWorker) SubscribeToEvents(remotePath string, ch chan worker.MessageEvent) error { + if ch == nil { + return errors.New("channel is nil") + } + ww.subMutex.Lock() + if ww.isTerminated { + ww.subMutex.Unlock() + return errors.New("worker is terminated") + } + ww.subscribers[remotePath] = ch + ww.numberOfSubs++ + //start the worker listener if there are subscribers + if ww.numberOfSubs == 1 { + ctx, cancel := context.WithCancel(context.Background()) + ww.ctx = ctx + ww.cancelContext = cancel + eventChan, err := ww.Listen(ctx) + if err != nil { + ww.subMutex.Unlock() + return err + } + go ww.ListenForEvents(eventChan) + } + ww.subMutex.Unlock() + return nil +} + +func (ww *WasmWebWorker) UnsubscribeToEvents(remotePath string) { + ww.subMutex.Lock() + ch, ok := ww.subscribers[remotePath] + if ok { + close(ch) + delete(ww.subscribers, remotePath) + ww.numberOfSubs-- + //stop the worker listener if there are no subscribers + if ww.numberOfSubs == 0 { + ww.cancelContext() + } + } + ww.subMutex.Unlock() +} + +func (ww *WasmWebWorker) ListenForEvents(eventChan <-chan worker.MessageEvent) { + for { + select { + case <-ww.ctx.Done(): + return + case event, ok := <-eventChan: + if !ok { + return + } + //get remote path from the event + data, err := event.Data() + // if above throws an error, pass it to all the subscribers + if err != nil { + ww.removeAllSubscribers() + return + } + remotePathObject, err := data.Get("remotePath") + if err != nil { + ww.removeAllSubscribers() + return + } + remotePath, _ := remotePathObject.String() + if remotePath == "" { + ww.removeAllSubscribers() + return + } + ww.subMutex.Lock() + ch, ok := ww.subscribers[remotePath] + if ok { + ch <- event + } + ww.subMutex.Unlock() + } + } +} + +func (ww *WasmWebWorker) removeAllSubscribers() { + ww.subMutex.Lock() + for path, ch := range ww.subscribers { + close(ch) + delete(ww.subscribers, path) + ww.numberOfSubs-- + } + ww.cancelContext() + ww.subMutex.Unlock() +} + +func (ww *WasmWebWorker) Start() error { + workerJS, err := buildWorkerJS(ww.Args, ww.Env, ww.Path) + if err != nil { + return err + } + + if ww.Name == "" { + ww.Name = uuid.New().String() + } + + wk, err := worker.NewFromScript(workerJS, worker.Options{Name: ww.Name}) + if err != nil { + return err + } + + ww.worker = wk + + return nil +} + +// PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers. +func (ww *WasmWebWorker) PostMessage(data safejs.Value, transfers []safejs.Value) error { + return ww.worker.PostMessage(data, transfers) +} + +// Terminate immediately terminates the Worker. +func (ww *WasmWebWorker) Terminate() { + ww.worker.Terminate() +} + +// Listen sends message events on a channel for events fired by self.postMessage() calls inside the Worker's global scope. +// Stops the listener and closes the channel when ctx is canceled. +func (ww *WasmWebWorker) Listen(ctx context.Context) (<-chan worker.MessageEvent, error) { + return ww.worker.Listen(ctx) +} + +func SetZauthServer(zauthServer string) { + gZauthServer = zauthServer +} + +type PostWorker interface { + PostMessage(data safejs.Value, transferables []safejs.Value) error +} + +func PostMessage(w PostWorker, msgType string, data map[string]string) error { + msgTypeUint8Array := js.Global().Get("Uint8Array").New(len(msgType)) + js.CopyBytesToJS(msgTypeUint8Array, []byte(msgType)) + + obj := js.Global().Get("Object").New() + obj.Set("msgType", msgTypeUint8Array) + + for k, v := range data { + if k == "msgType" { + return errors.New("msgType is key word reserved") + } + + dataUint8Array := js.Global().Get("Uint8Array").New(len(v)) + js.CopyBytesToJS(dataUint8Array, []byte(v)) + obj.Set(k, dataUint8Array) + } + + return w.PostMessage(safejs.Safe(obj), nil) +} + +func GetMsgType(event worker.MessageEvent) (string, *safejs.Value, error) { + data, err := event.Data() + if err != nil { + return "", nil, err + } + + mt, err := data.Get("msgType") + if err != nil { + return "", nil, err + } + msgTypeLen, err := mt.Length() + if err != nil { + return "", nil, err + } + + mstType := make([]byte, msgTypeLen) + safejs.CopyBytesToGo(mstType, mt) + + return string(mstType), &data, nil +} + +func SetMsgType(data *js.Value, msgType string) { + msgTypeUint8Array := js.Global().Get("Uint8Array").New(len(msgType)) + js.CopyBytesToJS(msgTypeUint8Array, []byte(msgType)) + data.Set("msgType", msgTypeUint8Array) +} + +func ParseEventDataField(data *safejs.Value, field string) (string, error) { + fieldUint8Array, err := data.Get(field) + if err != nil { + return "", err + } + fieldLen, err := fieldUint8Array.Length() + if err != nil { + return "", err + } + + fieldData := make([]byte, fieldLen) + safejs.CopyBytesToGo(fieldData, fieldUint8Array) + + return string(fieldData), nil +} + +func PostMessageToAllWorkers(msgType string, data map[string]string) error { + for id, worker := range workers { + fmt.Println("post message to worker", id) + err := PostMessage(worker, msgType, data) + if err != nil { + return fmt.Errorf("failed to post message to worker: %s, err: %v", id, err) + } + } + + return nil +} diff --git a/wasmsdk/jsbridge/zcnworker.js.tpl b/wasmsdk/jsbridge/zcnworker.js.tpl new file mode 100644 index 000000000..d082ff1d9 --- /dev/null +++ b/wasmsdk/jsbridge/zcnworker.js.tpl @@ -0,0 +1,101 @@ +importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.22.5/misc/wasm/wasm_exec.js','https://cdn.jsdelivr.net/gh/herumi/bls-wasm@v1.1.1/browser/bls.js'); + +const go = new Go(); +go.argv = {{.ArgsToJS}} +go.env = {{.EnvToJS}} +const bls = self.bls +bls.init(bls.BN254).then(()=>{}) + +async function getWasmModule() { + const cache = await caches.open('wasm-cache'); + let response = await cache.match("{{.CachePath}}"); + if(!response?.ok) { + response = await fetch("{{.Path}}").then(res => res).catch(err => err); + if (!response?.ok) { + response = await fetch("{{.FallbackPath}}").then(res => res).catch(err => err); + } + if (!response.ok) { + throw new Error(`Failed to fetch WASM: ${response.statusText}`); + } + } + const bytes = await response.arrayBuffer(); + return WebAssembly.instantiate(bytes, go.importObject); +} + +getWasmModule().then(result => { + go.run(result.instance); +}).catch(error => { + console.error("Failed to load WASM:", error); +}); + +function hexStringToByte(str) { + if (!str) return new Uint8Array() + + const a = [] + for (let i = 0, len = str.length; i < len; i += 2) { + a.push(parseInt(str.substr(i, 2), 16)) + } + + return new Uint8Array(a) + } + +self.__zcn_worker_wasm__ = { + sign: async (hash, secretKey) => { + if (!secretKey){ + const errMsg = 'err: wasm blsSign function requires a secret key' + console.warn(errMsg) + throw new Error(errMsg) + } + const bytes = hexStringToByte(hash) + const sk = bls.deserializeHexStrToSecretKey(secretKey) + const sig = sk.sign(bytes) + + if (!sig) { + const errMsg = 'err: wasm blsSign function failed to sign transaction' + console.warn(errMsg) + throw new Error(errMsg) + } + + return sig.serializeToHexStr() + }, + initProxyKeys: initProxyKeys, + verify: blsVerify, + verifyWith: blsVerifyWith, + addSignature: blsAddSignature +} + +async function initProxyKeys(publicKey, privateKey) { + const pubKey = bls.deserializeHexStrToPublicKey(publicKey) + const privKey = bls.deserializeHexStrToSecretKey(privateKey) + bls.publicKey = pubKey + bls.secretKey = privKey +} + +async function blsVerify(signature, hash) { + const bytes = hexStringToByte(hash) + const sig = bls.deserializeHexStrToSignature(signature) + return jsProxy.publicKey.verify(sig, bytes) +} + +async function blsVerifyWith(pk, signature, hash) { + const publicKey = bls.deserializeHexStrToPublicKey(pk) + const bytes = hexStringToByte(hash) + const sig = bls.deserializeHexStrToSignature(signature) + return publicKey.verify(sig, bytes) +} + +async function blsAddSignature(secretKey, signature, hash) { + const privateKey = bls.deserializeHexStrToSecretKey(secretKey) + const sig = bls.deserializeHexStrToSignature(signature) + var sig2 = privateKey.sign(hexStringToByte(hash)) + if (!sig2) { + const errMsg = + 'err: wasm blsAddSignature function failed to sign transaction' + console.warn(errMsg) + throw new Error(errMsg) + } + + sig.add(sig2) + + return sig.serializeToHexStr() +} From 2ee8e2836628981e3305175d37d727f234214dfc Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 18:07:10 +0530 Subject: [PATCH 074/107] fix --- go.mod | 75 ++++------------- go.sum | 139 -------------------------------- wasmsdk/demo/main.go | 11 +-- wasmsdk/jsbridge/file_reader.go | 2 +- wasmsdk/jsbridge/file_writer.go | 2 +- 5 files changed, 22 insertions(+), 207 deletions(-) diff --git a/go.mod b/go.mod index 49206cca3..f2244324e 100644 --- a/go.mod +++ b/go.mod @@ -5,131 +5,87 @@ go 1.22.5 require ( github.com/0chain/common v1.18.3 github.com/0chain/errors v1.0.3 - github.com/Luzifer/go-openssl/v3 v3.1.0 - github.com/btcsuite/btcd v0.23.4 - github.com/dgraph-io/badger/v3 v3.2103.5 - github.com/didip/tollbooth v4.0.2+incompatible + github.com/Luzifer/go-openssl/v3 v3.1.0 // indirect + github.com/btcsuite/btcd v0.23.4 // indirect github.com/ethereum/go-ethereum v1.10.26 github.com/google/uuid v1.3.0 - github.com/gorilla/handlers v1.5.1 - github.com/gorilla/mux v1.8.0 + github.com/gorilla/mux v1.8.0 // indirect github.com/h2non/filetype v1.1.4-0.20231228185113-6469358c2bcb - github.com/hashicorp/go-retryablehttp v0.7.2 + github.com/hashicorp/go-retryablehttp v0.7.2 // indirect github.com/hashicorp/golang-lru/v2 v2.0.1 - github.com/herumi/bls-go-binary v1.31.0 + github.com/herumi/bls-go-binary v1.31.0 // indirect github.com/hitenjain14/fasthttp v0.0.0-20240916135632-f9303a91736c github.com/influxdata/influxdb v1.8.3 github.com/klauspost/reedsolomon v1.11.8 github.com/lithammer/shortuuid/v3 v3.0.7 - github.com/machinebox/graphql v0.2.2 - github.com/magma/augmented-networks/accounting/protos v0.1.1 + github.com/machinebox/graphql v0.2.2 // indirect github.com/mitchellh/go-homedir v1.1.0 github.com/mitchellh/mapstructure v1.5.0 github.com/pkg/errors v0.9.1 - github.com/shopspring/decimal v1.3.1 - github.com/spf13/viper v1.15.0 + github.com/shopspring/decimal v1.3.1 // indirect + github.com/spf13/viper v1.15.0 // indirect github.com/stretchr/testify v1.9.0 - github.com/tyler-smith/go-bip39 v1.1.0 + github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/uptrace/bunrouter v1.0.20 go.dedis.ch/kyber/v3 v3.1.0 go.uber.org/zap v1.24.0 golang.org/x/crypto v0.21.0 - golang.org/x/image v0.14.0 + golang.org/x/image v0.14.0 // indirect golang.org/x/sync v0.7.0 - google.golang.org/grpc v1.53.0 gopkg.in/cheggaaa/pb.v1 v1.0.28 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - gopkg.in/yaml.v2 v2.4.0 - gopkg.in/yaml.v3 v3.0.1 + gopkg.in/yaml.v3 v3.0.1 // indirect ) require ( github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe github.com/hack-pad/go-webworkers v0.1.0 - github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 - github.com/ybbus/jsonrpc/v3 v3.1.5 ) require ( - github.com/VictoriaMetrics/fastcache v1.6.0 // indirect github.com/andybalholm/brotli v1.0.5 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 // indirect - github.com/cespare/xxhash v1.1.0 // indirect - github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect - github.com/dgraph-io/ristretto v0.1.1 // indirect - github.com/dustin/go-humanize v1.0.1 // indirect - github.com/edsrzf/mmap-go v1.0.0 // indirect - github.com/felixge/httpsnoop v1.0.3 // indirect - github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang-jwt/jwt/v4 v4.3.0 // indirect - github.com/golang/glog v1.0.0 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect - github.com/google/flatbuffers v22.9.29+incompatible // indirect github.com/gorilla/websocket v1.5.0 // indirect - github.com/hashicorp/go-bexpr v0.1.10 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect github.com/hashicorp/hcl v1.0.0 // indirect - github.com/holiman/bloomfilter/v2 v2.0.3 // indirect - github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c // indirect - github.com/huin/goupnp v1.0.3 // indirect - github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/magiconair/properties v1.8.7 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect - github.com/mitchellh/pointerstructure v1.2.0 // indirect - github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/tsdb v0.7.1 // indirect github.com/rivo/uniseg v0.4.3 // indirect github.com/rjeczalik/notify v0.9.1 // indirect - github.com/rs/cors v1.7.0 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/status-im/keycard-go v0.2.0 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/subosito/gotenv v1.4.2 // indirect - github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect github.com/tinylib/msgp v1.1.6 // indirect github.com/tklauser/go-sysconf v0.3.11 // indirect github.com/tklauser/numcpus v0.6.0 // indirect - github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa // indirect github.com/valyala/fasthttp v1.51.0 // indirect - github.com/x448/float16 v0.8.4 // indirect - github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + github.com/ybbus/jsonrpc/v3 v3.1.5 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect - go.opencensus.io v0.24.0 // indirect golang.org/x/sys v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect - google.golang.org/protobuf v1.33.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect ) require ( - github.com/btcsuite/btcd/btcutil v1.1.3 + github.com/btcsuite/btcd/btcutil v1.1.3 // indirect github.com/hack-pad/safejs v0.1.1 github.com/klauspost/compress v1.17.0 // indirect github.com/klauspost/cpuid/v2 v2.2.4 // indirect @@ -137,9 +93,6 @@ require ( github.com/yusufpapurcu/wmi v1.2.2 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.9.0 // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/time v0.3.0 // indirect - google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect ) //replace github.com/ethereum/go-ethereum => github.com/certifaction/go-ethereum v1.10.3-wasm diff --git a/go.sum b/go.sum index 64aea6774..4d462e736 100644 --- a/go.sum +++ b/go.sum @@ -44,22 +44,13 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd h1:zeLdGO7e5Ovd4w/g/sHvg+0+Zu0gI7mhpznSsGbB3lI= -github.com/0chain/gosdk_common v0.0.0-20250108074831-524b0ec9b7cd/go.mod h1:A6zAa6S8jWML2razteUYtk9aINjHW4u8MjFKITgIdp4= -github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606 h1:/pEJYnH04BoG5UJsQ+k74F/rJOtehXOgMVbB44h1gAY= -github.com/0chain/gosdk_common v0.0.0-20250116114303-c44047234606/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= -github.com/0chain/gosdk_common v0.0.0-20250116160841-eeec3c6a9fcd h1:LbZTG/mIwxmR1mcS5oNsDh0hsnrRLNt0u/6/mqg8V/A= -github.com/0chain/gosdk_common v0.0.0-20250116160841-eeec3c6a9fcd/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe h1:opO2O58fZh2Ca1rdHMNRCkSTys95AOnpCd3WUapgeFU= github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= -github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/Luzifer/go-openssl/v3 v3.1.0 h1:QqKqo6kYXGGUsvtUoCpRZm8lHw+jDfhbzr36gVj+/gw= github.com/Luzifer/go-openssl/v3 v3.1.0/go.mod h1:liy3FXuuS8hfDlYh1T+l78AwQ/NjZflJz0NDvjKhwDs= -github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o= github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw= @@ -67,19 +58,14 @@ github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBA github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= -github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/apache/arrow/go/arrow v0.0.0-20191024131854-af6fa24be0db/go.mod h1:VTxUBvSJ3s3eHAg65PNgrsn5BtqCRPdmyXh6rAfdxN0= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -114,7 +100,6 @@ github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= @@ -124,22 +109,6 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= -github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= -github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= -github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v1.1.2 h1:CUh2IPtR4swHlEj48Rhfzw6l/d0qA31fItcIszQVIsA= -github.com/cockroachdb/pebble v1.1.2/go.mod h1:4exszw1r40423ZsmkG/09AFEG83I0uDgfujJdbL6kYU= -github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= -github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= -github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= @@ -155,20 +124,8 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeC github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= -github.com/dgraph-io/badger/v3 v3.2103.5 h1:ylPa6qzbjYRQMU6jokoj4wzcaweHylt//CH0AKt0akg= -github.com/dgraph-io/badger/v3 v3.2103.5/go.mod h1:4MPiseMeDQ3FNCYwRbbcBOGJLf5jsE0PPFzRiKjtcdw= -github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= -github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8/go.mod h1:VMaSuZ+SZcx/wljOQKvp5srsbCiKDEb6K2wC4+PiBmQ= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/didip/tollbooth v4.0.2+incompatible h1:fVSa33JzSz0hoh2NxpwZtksAzAgd7zjmGO20HCZtF4M= -github.com/didip/tollbooth v4.0.2+incompatible/go.mod h1:A9b0665CE6l1KmzpDws2++elm/CsuWBMa5Jv4WY0PEY= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= @@ -182,9 +139,6 @@ github.com/ethereum/go-ethereum v1.10.26 h1:i/7d9RBBwiXCEuyduBQzJw/mKmnvzsN14jqB github.com/ethereum/go-ethereum v1.10.26/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= -github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= @@ -194,24 +148,16 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= -github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= -github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0 h1:wDJmvq38kDhkVxi50ni9ykkdUr1PKgqKOoi01fa0Mdk= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -221,20 +167,14 @@ github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.3.0 h1:kHL1vqdqWNfATmA0FNMdmZNMyZI1U6O31X4rlIPoBog= github.com/golang-jwt/jwt/v4 v4.3.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= @@ -256,20 +196,13 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= -github.com/google/flatbuffers v1.12.1/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= -github.com/google/flatbuffers v22.9.29+incompatible h1:3UBb679lq3V/O9rgzoJmnkP1jJzmC9OdFzITUBkLU/A= -github.com/google/flatbuffers v22.9.29+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -278,9 +211,7 @@ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= @@ -305,8 +236,6 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= -github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= @@ -345,7 +274,6 @@ github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c/go.mod h1:SC8Ryt github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huin/goupnp v1.0.3 h1:N8No57ls+MnjlB+JPiCVSOyy/ot7MJTqlo7rn+NYSqQ= github.com/huin/goupnp v1.0.3/go.mod h1:ZxNlw5WqJj6wSsRK5+YfflQGXYfccj5VgQsMNixHM7Y= -github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -372,11 +300,9 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef/go.mod h1:Ct9fl0F6iIOGgxJ5npU/IUOhOhqlVrGjyIZc8/MagT0= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM= github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= @@ -401,35 +327,26 @@ github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJV github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= github.com/machinebox/graphql v0.2.2 h1:dWKpJligYKhYKO5A2gvNhkJdQMNZeChZYyBbrZkBZfo= github.com/machinebox/graphql v0.2.2/go.mod h1:F+kbVMHuwrQ5tYgU9JXlnskM8nOaFxCAEolaQybkjWA= -github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= -github.com/magma/augmented-networks/accounting/protos v0.1.1 h1:eTl3BC7s/PmYvh/scQSHxlqgt1BYvnOArU0vzPSjVAU= -github.com/magma/augmented-networks/accounting/protos v0.1.1/go.mod h1:Hpfg8aAxldUN7qlVtR5xwlAf8pcetFm8DWwRKZsh2J4= github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A= @@ -438,27 +355,20 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae/go.mod h1:qAyveg+e4CE+eKJXWVjKXM4ck2QobLqTDytGJbLLhJg= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/opentracing/opentracing-go v1.0.3-0.20180606204148-bd9c31933947/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= -github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/paulbellamy/ratecounter v0.2.0/go.mod h1:Hfx1hDpSGoqxkVVpBi/IlYD7kChlfo5C6hzIHwPqfFE= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= github.com/peterh/liner v1.0.1-0.20180619022028-8c1271fcf47f/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= @@ -477,22 +387,13 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.12.0 h1:C+UIj/QWtmqY13Arb8kwMt5j34/0Z2iKamrJ+ryC0Gg= -github.com/prometheus/client_golang v1.12.0/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a h1:CmF68hwI0XsOQ5UwlBopMi2Ow4Pbg32akc4KIVCOm+Y= -github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= -github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= -github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= -github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= -github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/remeh/sizedwaitgroup v1.0.0 h1:VNGGFwNo/R5+MJBf6yrsr110p0m4/OX4S3DCy7Kyl5E= @@ -508,7 +409,6 @@ github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZV github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= @@ -522,23 +422,17 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= -github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.15.0 h1:js3yy885G8xwJa6iOISGFwd+qlUo5AvyXb7CiihdtiU= github.com/spf13/viper v1.15.0/go.mod h1:fFcTBJxvhhzSJiZy8n+PeW6t8l+KeT/uTARa0jHOQLA= github.com/status-im/keycard-go v0.2.0 h1:QDLFswOQu1r5jsycloeQh3bVU8n/NatHHaZobtDnDzA= @@ -573,7 +467,6 @@ github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYm github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/uptrace/bunrouter v1.0.20 h1:jNvYNcJxF+lSYBQAaQjnE6I11Zs0m+3M5Ek7fq/Tp4c= github.com/uptrace/bunrouter v1.0.20/go.mod h1:TwT7Bc0ztF2Z2q/ZzMuSVkcb/Ig/d3MQeP2cxn3e1hI= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa h1:5SqCsI/2Qya2bCzK15ozrqo2sZxkh0FHynJZOTVoV6Q= @@ -583,10 +476,7 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= -github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= -github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= github.com/ybbus/jsonrpc/v3 v3.1.5 h1:0cC/QzS8OCuXYqqDbYnKKhsEe+IZLrNlDx8KPCieeW0= @@ -612,8 +502,6 @@ go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= -go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= -go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= @@ -631,7 +519,6 @@ go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -655,8 +542,6 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= -golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -717,12 +602,9 @@ golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -742,15 +624,12 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190124100055-b90733256f2e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -790,13 +669,10 @@ golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -857,7 +733,6 @@ golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= @@ -867,15 +742,12 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= -golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.0.0-20181121035319-3f7ecaa7e8ca/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.6.0/go.mod h1:9mxDZsDKxgMAuccQkewq682L+0eCu4dCN2yonUJTCLU= @@ -946,8 +818,6 @@ google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= -google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -964,8 +834,6 @@ google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= -google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -976,10 +844,6 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -996,15 +860,12 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 6c899cdd7..f1ba5a7d0 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -7,15 +7,13 @@ import ( "net/http" "sync" - "github.com/0chain/gosdk/core/common" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zcncore" "github.com/uptrace/bunrouter" ) func main() { - zcncore.InitSignatureScheme("bls0chain") - ctx, cf := context.WithCancel(context.Background()) router := bunrouter.New() @@ -36,7 +34,10 @@ func main() { } w.WriteHeader(http.StatusOK) - w.Write([]byte(wallet)) + _, err = w.Write([]byte(wallet)) + if err != nil { + return err + } return nil }) diff --git a/wasmsdk/jsbridge/file_reader.go b/wasmsdk/jsbridge/file_reader.go index 17b27a1e7..21b783917 100644 --- a/wasmsdk/jsbridge/file_reader.go +++ b/wasmsdk/jsbridge/file_reader.go @@ -8,7 +8,7 @@ import ( "io" "syscall/js" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/valyala/bytebufferpool" ) diff --git a/wasmsdk/jsbridge/file_writer.go b/wasmsdk/jsbridge/file_writer.go index 81b69a0c6..3cb1cfa85 100644 --- a/wasmsdk/jsbridge/file_writer.go +++ b/wasmsdk/jsbridge/file_writer.go @@ -8,7 +8,7 @@ import ( "io/fs" "syscall/js" - "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk_common/core/common" "github.com/valyala/bytebufferpool" ) From bae7a6e0657a7e52775baa57ea39bc11e3645650 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 18:11:31 +0530 Subject: [PATCH 075/107] revert --- wasmsdk/allocation.go | 2 +- wasmsdk/auth_txn.go | 2 +- wasmsdk/blobber.go | 2 +- wasmsdk/cache.go | 2 +- wasmsdk/common.go | 2 +- wasmsdk/ethwallet.go | 1 + wasmsdk/player_stream.go | 2 +- wasmsdk/proxy.go | 2 +- wasmsdk/wallet.go | 2 +- zboxcore/sdk/chunked_upload_process_js.go | 2 +- 10 files changed, 10 insertions(+), 9 deletions(-) diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 9787d8a32..4e4713d03 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -13,9 +13,9 @@ import ( "sync" "syscall/js" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) const TOKEN_UNIT int64 = 1e10 diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 42bac292a..3c2955cf6 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -7,8 +7,8 @@ import ( "fmt" "syscall/js" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zcncore" ) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 99c3b0280..f67e1bee1 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -23,10 +23,10 @@ import ( "github.com/0chain/gosdk_common/core/sys" "github.com/hack-pad/safejs" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" diff --git a/wasmsdk/cache.go b/wasmsdk/cache.go index 9e0d8c9e1..7d24ecd02 100644 --- a/wasmsdk/cache.go +++ b/wasmsdk/cache.go @@ -8,9 +8,9 @@ import ( "errors" "time" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" lru "github.com/hashicorp/golang-lru/v2" ) diff --git a/wasmsdk/common.go b/wasmsdk/common.go index a5f22744c..7c9f4f8ac 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -7,8 +7,8 @@ import ( "errors" "syscall/js" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) // PrintError is to print to stderr diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index 6a9b8e696..9c629b37f 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -22,6 +22,7 @@ func strToInt64(s string) int64 { } func int64ToStr(x int64) string { + gosdk_ return strconv.FormatInt(x, 10) } diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index fa81be29d..8af595d97 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -11,9 +11,9 @@ import ( "sync" "time" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zboxcore/marker" ) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 5cc0b15c9..5f30f8a1f 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -14,11 +14,11 @@ import ( "time" "github.com/0chain/gosdk/core/version" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zcncore" "github.com/hack-pad/safejs" diff --git a/wasmsdk/wallet.go b/wasmsdk/wallet.go index edbaaf52f..8c69d9779 100644 --- a/wasmsdk/wallet.go +++ b/wasmsdk/wallet.go @@ -10,9 +10,9 @@ import ( "os" "strconv" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" ) func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error { diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index afb7220ec..c450bf1f6 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -18,9 +18,9 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" + "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/wasmsdk/jsbridge" "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" From 0f7477d7155d1c4451f423e8fe86e6a572beccee Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 18:16:45 +0530 Subject: [PATCH 076/107] lint fix --- wasmsdk/ethwallet.go | 1 - 1 file changed, 1 deletion(-) diff --git a/wasmsdk/ethwallet.go b/wasmsdk/ethwallet.go index 9c629b37f..6a9b8e696 100644 --- a/wasmsdk/ethwallet.go +++ b/wasmsdk/ethwallet.go @@ -22,7 +22,6 @@ func strToInt64(s string) int64 { } func int64ToStr(x int64) string { - gosdk_ return strconv.FormatInt(x, 10) } From e49091c140ccdec57652907af5cb69665e3d1a6b Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 18:52:28 +0530 Subject: [PATCH 077/107] version update --- core/version/version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/version/version.go b/core/version/version.go index fa0af25cc..9213a1e29 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,4 +2,4 @@ package version -const VERSIONSTR = "v1.17.11-269-g7fd90660" +const VERSIONSTR = "v1.16.3-10-g66360b13" From 59f3dd8fab77d4ab0b8eec6332702db1151c9a8b Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 19:03:20 +0530 Subject: [PATCH 078/107] gosdk to common --- go.mod | 2 ++ go.sum | 40 +++++++++++++++++++++++++++++++++++++++ mobilesdk/zbox/m3u8.go | 2 +- mobilesdk/zbox/storage.go | 4 ++-- wasmsdk/blobber.go | 2 +- 5 files changed, 46 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index f2244324e..7844728c4 100644 --- a/go.mod +++ b/go.mod @@ -52,6 +52,7 @@ require ( github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect @@ -76,6 +77,7 @@ require ( github.com/tklauser/go-sysconf v0.3.11 // indirect github.com/tklauser/numcpus v0.6.0 // indirect github.com/valyala/fasthttp v1.51.0 // indirect + github.com/x448/float16 v0.8.4 // indirect github.com/ybbus/jsonrpc/v3 v3.1.5 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect golang.org/x/sys v0.18.0 // indirect diff --git a/go.sum b/go.sum index 4d462e736..949138ae9 100644 --- a/go.sum +++ b/go.sum @@ -49,6 +49,8 @@ github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe/go.mod h1:5Mtn github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= +github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/Luzifer/go-openssl/v3 v3.1.0 h1:QqKqo6kYXGGUsvtUoCpRZm8lHw+jDfhbzr36gVj+/gw= github.com/Luzifer/go-openssl/v3 v3.1.0/go.mod h1:liy3FXuuS8hfDlYh1T+l78AwQ/NjZflJz0NDvjKhwDs= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -66,6 +68,8 @@ github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLj github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -109,6 +113,18 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= +github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/pebble v1.1.2 h1:CUh2IPtR4swHlEj48Rhfzw6l/d0qA31fItcIszQVIsA= +github.com/cockroachdb/pebble v1.1.2/go.mod h1:4exszw1r40423ZsmkG/09AFEG83I0uDgfujJdbL6kYU= +github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= +github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= @@ -148,8 +164,12 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= +github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= +github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= @@ -167,6 +187,8 @@ github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.3.0 h1:kHL1vqdqWNfATmA0FNMdmZNMyZI1U6O31X4rlIPoBog= github.com/golang-jwt/jwt/v4 v4.3.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= @@ -196,6 +218,8 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= @@ -343,6 +367,8 @@ github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= +github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= @@ -387,13 +413,21 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.12.0 h1:C+UIj/QWtmqY13Arb8kwMt5j34/0Z2iKamrJ+ryC0Gg= +github.com/prometheus/client_golang v1.12.0/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a h1:CmF68hwI0XsOQ5UwlBopMi2Ow4Pbg32akc4KIVCOm+Y= +github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= +github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= +github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= +github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/remeh/sizedwaitgroup v1.0.0 h1:VNGGFwNo/R5+MJBf6yrsr110p0m4/OX4S3DCy7Kyl5E= @@ -476,6 +510,8 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= @@ -542,6 +578,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -844,6 +882,8 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/mobilesdk/zbox/m3u8.go b/mobilesdk/zbox/m3u8.go index bbf5a3c5f..0c7ffa3e1 100644 --- a/mobilesdk/zbox/m3u8.go +++ b/mobilesdk/zbox/m3u8.go @@ -7,7 +7,7 @@ import ( "strconv" "time" - "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk_common/zboxcore/logger" ) // #EXTM3U diff --git a/mobilesdk/zbox/storage.go b/mobilesdk/zbox/storage.go index fd3342342..595e78a3f 100644 --- a/mobilesdk/zbox/storage.go +++ b/mobilesdk/zbox/storage.go @@ -6,10 +6,10 @@ import ( "strings" "time" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/zboxcore/fileref" + "github.com/0chain/gosdk_common/zboxcore/logger" ) type fileResp struct { diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index f67e1bee1..fa47423ae 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -24,9 +24,9 @@ import ( "github.com/hack-pad/safejs" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/hack-pad/go-webworkers/worker" From eb3184b7035486c3a8315d45843e007c36e36fdf Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 20:49:50 +0530 Subject: [PATCH 079/107] common update --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 7844728c4..ddbceb063 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe + github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631 github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 949138ae9..442107551 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe h1:opO2O58fZh2Ca1rdHMNRCkSTys95AOnpCd3WUapgeFU= -github.com/0chain/gosdk_common v0.0.0-20250116161245-a631a8c4c9fe/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631 h1:UGvlsDCcYL8G+GNweLzmWKPcpLG7F1VKQwORugtbTNw= +github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= From 088847b96261365a1bb9ea7d82d6b04c839d433c Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 21:12:10 +0530 Subject: [PATCH 080/107] dumy --- mobilesdk/sdk/sdk.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index fde7cedc6..56ba39a0a 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -24,7 +24,7 @@ import ( "github.com/0chain/gosdk/mobilesdk/zbox" "github.com/0chain/gosdk/mobilesdk/zboxapi" - "github.com/0chain/gosdk_common/zcncore" + "github.com/0chain/gosdk/zcncore" ) var nonce = int64(0) From f2d815f69e779af13b8a5069b7de62616f4d47fc Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 17 Jan 2025 21:16:40 +0530 Subject: [PATCH 081/107] dummy --- mobilesdk/sdk/sdk.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 56ba39a0a..fde7cedc6 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -24,7 +24,7 @@ import ( "github.com/0chain/gosdk/mobilesdk/zbox" "github.com/0chain/gosdk/mobilesdk/zboxapi" - "github.com/0chain/gosdk/zcncore" + "github.com/0chain/gosdk_common/zcncore" ) var nonce = int64(0) From 9b4ae2c4e3135de9c10dde2c1d5342a65c964b23 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 21 Jan 2025 15:02:58 +0530 Subject: [PATCH 082/107] core changes --- mobilesdk/sdk/sdk.go | 23 +- zboxcore/sdk/allocation.go | 36 +-- zboxcore/sdk/allocation_file_delete_test.go | 18 +- zboxcore/sdk/allocation_file_test.go | 57 ++-- zboxcore/sdk/allocation_test.go | 177 ++++++------- zboxcore/sdk/blobber_operations.go | 96 +------ zboxcore/sdk/blockdownloadworker.go | 6 +- zboxcore/sdk/chunked_upload.go | 6 +- zboxcore/sdk/chunked_upload_bench_test.go | 1 + zboxcore/sdk/chunked_upload_blobber.go | 8 +- zboxcore/sdk/chunked_upload_form_builder.go | 2 +- zboxcore/sdk/chunked_upload_process_js.go | 12 +- zboxcore/sdk/commitworker.go | 4 +- zboxcore/sdk/common.go | 12 +- zboxcore/sdk/copyworker.go | 12 +- zboxcore/sdk/copyworker_test.go | 39 +-- zboxcore/sdk/deleteworker.go | 14 +- zboxcore/sdk/deleteworker_test.go | 29 +- zboxcore/sdk/dirworker.go | 10 +- zboxcore/sdk/downloadworker.go | 17 +- zboxcore/sdk/filemetaworker.go | 4 +- zboxcore/sdk/filemetaworker_test.go | 25 +- zboxcore/sdk/filerefsworker.go | 11 +- zboxcore/sdk/filestatsworker.go | 4 +- zboxcore/sdk/filestatsworker_test.go | 27 +- zboxcore/sdk/listworker.go | 10 +- zboxcore/sdk/listworker_test.go | 26 +- zboxcore/sdk/moveworker.go | 10 +- zboxcore/sdk/multi_operation_worker.go | 10 +- zboxcore/sdk/networkworker.go | 131 --------- zboxcore/sdk/playlist.go | 14 +- zboxcore/sdk/reader.go | 1 + zboxcore/sdk/renameworker.go | 12 +- zboxcore/sdk/renameworker_test.go | 40 +-- zboxcore/sdk/rollback.go | 38 ++- zboxcore/sdk/sdk.go | 277 ++++---------------- zboxcore/sdk/sharerequest.go | 1 + zboxcore/sdk/sync.go | 5 +- zboxcore/sdk/writemarker_mutex.go | 7 +- zboxcore/sdk/writemarker_mutex_test.go | 15 +- zboxcore/zboxutil/http.go | 3 +- 41 files changed, 456 insertions(+), 794 deletions(-) delete mode 100644 zboxcore/sdk/networkworker.go diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index fde7cedc6..9e3de1ad1 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -17,9 +17,9 @@ import ( "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/conf" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zboxcore/client" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk/mobilesdk/zbox" @@ -126,11 +126,18 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { l.Logger.Info(configObj.ChainID) l.Logger.Info(configObj.SignatureScheme) l.Logger.Info(configObj.PreferredBlobbers) - if err = client.InitSDK(clientJson, - configObj.BlockWorker, - configObj.ChainID, - configObj.SignatureScheme, - 0, false, true); err != nil { + params := client.InitSdkOptions{ + WalletJSON: clientJson, + BlockWorker: configObj.BlockWorker, + ChainID: configObj.ChainID, + SignatureScheme: configObj.SignatureScheme, + Nonce: int64(0), + AddWallet: true, + ZboxHost: configObj.ZboxHost, + ZboxAppType: configObj.ZboxAppType, + } + + if err = client.InitSDKWithWebApp(params); err != nil { l.Logger.Error(err) return nil, err } @@ -365,12 +372,12 @@ func (s *StorageSDK) GetVersion() string { // - extend: extend allocation // - allocationID: allocation ID // - lock: Number of tokens to lock to the allocation after the update -func (s *StorageSDK) UpdateAllocation(size int64, extend bool, allocationID string, lock uint64) (hash string, err error) { +func (s *StorageSDK) UpdateAllocation(size, authRoundExpiry int64, extend bool, allocationID string, lock uint64) (hash string, err error) { if lock > math.MaxInt64 { return "", errors.Errorf("int64 overflow in lock") } - hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, "", "", "", false, &sdk.FileOptionsParameters{}) + hash, _, err = sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, lock, "", "", "", "", "", false, &sdk.FileOptionsParameters{}, "") return hash, err } diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 90de34e8a..1c9692bf5 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math" "mime/multipart" "net/http" @@ -25,10 +24,12 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/pathutil" "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -364,16 +365,12 @@ func (a *Allocation) SetCheckStatus(checkStatus bool) { } func getPriceRange(name string) (PriceRange, error) { - conf, err := GetStorageSCConfig() + conf, err := transaction.GetConfig("storage_sc_config") if err != nil { return PriceRange{}, err } f := conf.Fields[name] - fStr, ok := f.(string) - if !ok { - return PriceRange{}, fmt.Errorf("type is wrong") - } - mrp, err := strconv.ParseFloat(fStr, 64) + mrp, err := strconv.ParseFloat(f, 64) if err != nil { return PriceRange{}, err } @@ -401,7 +398,7 @@ func (a *Allocation) GetBlobberStats() map[string]*BlobberAllocationStats { wg.Add(numList) rspCh := make(chan *BlobberAllocationStats, numList) for _, blobber := range a.Blobbers { - go getAllocationDataFromBlobber(blobber, a.ID, a.Tx, rspCh, wg) + go getAllocationDataFromBlobber(blobber, a.ID, a.Tx, rspCh, wg, a.Owner) } wg.Wait() result := make(map[string]*BlobberAllocationStats, len(a.Blobbers)) @@ -445,7 +442,7 @@ func (a *Allocation) InitAllocation() { } func (a *Allocation) isInitialized() bool { - return a.initialized && sdkInitialized + return a.initialized && client.IsSDKInitialized() } func (a *Allocation) startWorker(ctx context.Context) { @@ -861,7 +858,7 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { go func(blobber *blockchain.StorageNode) { defer wg.Done() - wr, err := GetWritemarker(a.ID, a.Tx, a.sig, blobber.ID, blobber.Baseurl) + wr, err := GetWritemarker(a.ID, a.Tx, a.sig, blobber.ID, blobber.Baseurl, a.Owner) if err != nil { atomic.AddInt32(&errCnt, 1) logger.Logger.Error("error during getWritemarke", zap.Error(err)) @@ -870,6 +867,7 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { markerChan <- nil } else { markerChan <- &RollbackBlobber{ + ClientId: a.Owner, blobber: blobber, lvm: wr, commitResult: &CommitResult{}, @@ -924,7 +922,7 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { } if prevVersion > latestVersion { - prevVersion, latestVersion = latestVersion, prevVersion + prevVersion, latestVersion = latestVersion, prevVersion //nolint:ineffassign,staticcheck } // TODO: Check if allocation can be repaired @@ -965,6 +963,7 @@ func (a *Allocation) RepairRequired(remotepath string) (zboxutil.Uint128, zboxut } listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} + listReq.ClientId = a.Owner listReq.allocationID = a.ID listReq.allocationTx = a.Tx listReq.sig = a.sig @@ -1575,6 +1574,7 @@ func (a *Allocation) ListDirFromAuthTicket(authTicket string, lookupHash string, } listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} + listReq.ClientId = a.Owner listReq.allocationID = a.ID listReq.allocationTx = a.Tx listReq.sig = a.sig @@ -1615,6 +1615,7 @@ func (a *Allocation) ListDir(path string, opts ...ListRequestOptions) (*ListResu return nil, errors.New("invalid_path", "Path should be valid and absolute") } listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} + listReq.ClientId = a.Owner listReq.allocationID = a.ID listReq.allocationTx = a.Tx listReq.sig = a.sig @@ -1643,6 +1644,7 @@ func (a *Allocation) getRefs(path, pathHash, authToken, offsetPath, updatedDate, } oTreeReq := &ObjectTreeRequest{ + ClientId: a.Owner, allocationID: a.ID, allocationTx: a.Tx, sig: a.sig, @@ -1872,6 +1874,7 @@ func (a *Allocation) GetRecentlyAddedRefs(page int, fromDate int64, pageLimit in offset := int64(page-1) * int64(pageLimit) req := &RecentlyAddedRefRequest{ + ClientId: a.Owner, allocationID: a.ID, allocationTx: a.Tx, sig: a.sig, @@ -1900,6 +1903,7 @@ func (a *Allocation) GetFileMeta(path string) (*ConsolidatedFileMeta, error) { result := &ConsolidatedFileMeta{} listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} + listReq.ClientId = a.Owner listReq.allocationID = a.ID listReq.allocationTx = a.Tx listReq.sig = a.sig @@ -2020,6 +2024,7 @@ func (a *Allocation) GetFileMetaFromAuthTicket(authTicket string, lookupHash str } listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} + listReq.ClientId = a.Owner listReq.allocationID = a.ID listReq.allocationTx = a.Tx listReq.sig = a.sig @@ -2202,7 +2207,7 @@ func (a *Allocation) RevokeShare(path string, refereeClientID string) error { query.Add("path", path) query.Add("refereeClientID", refereeClientID) - httpreq, err := zboxutil.NewRevokeShareRequest(baseUrl, a.ID, a.Tx, a.sig, query) + httpreq, err := zboxutil.NewRevokeShareRequest(baseUrl, a.ID, a.Tx, a.sig, query, a.Owner) if err != nil { return err } @@ -2217,7 +2222,7 @@ func (a *Allocation) RevokeShare(path string, refereeClientID string) error { } defer resp.Body.Close() - respbody, err := ioutil.ReadAll(resp.Body) + respbody, err := io.ReadAll(resp.Body) if err != nil { l.Logger.Error("Error: Resp ", err) return err @@ -2295,6 +2300,7 @@ func (a *Allocation) GetAuthTicket(path, filename string, } shareReq := &ShareRequest{ + ClientId: a.Owner, expirationSeconds: expiration, allocationID: a.ID, allocationTx: a.Tx, @@ -2365,7 +2371,7 @@ func (a *Allocation) UploadAuthTicketToBlobber(authTicket string, clientEncPubKe if err := formWriter.Close(); err != nil { return err } - httpreq, err := zboxutil.NewShareRequest(url, a.ID, a.Tx, a.sig, body) + httpreq, err := zboxutil.NewShareRequest(url, a.ID, a.Tx, a.sig, body, a.Owner) if err != nil { return err } @@ -2381,7 +2387,7 @@ func (a *Allocation) UploadAuthTicketToBlobber(authTicket string, clientEncPubKe } defer resp.Body.Close() - respbody, err := ioutil.ReadAll(resp.Body) + respbody, err := io.ReadAll(resp.Body) if err != nil { l.Logger.Error("Error: Resp ", err) return err diff --git a/zboxcore/sdk/allocation_file_delete_test.go b/zboxcore/sdk/allocation_file_delete_test.go index 3ec084d71..122cf266a 100644 --- a/zboxcore/sdk/allocation_file_delete_test.go +++ b/zboxcore/sdk/allocation_file_delete_test.go @@ -8,10 +8,10 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -29,11 +29,10 @@ func TestAllocation_DeleteFile(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) zboxutil.Client = &mockClient resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { @@ -51,9 +50,10 @@ func TestAllocation_DeleteFile(t *testing.T) { DataShards: 2, ParityShards: 2, FileOptions: 63, + Owner: mockClientId, } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ @@ -89,11 +89,10 @@ func TestAllocation_deleteFile(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) zboxutil.Client = &mockClient resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { @@ -168,9 +167,10 @@ func TestAllocation_deleteFile(t *testing.T) { DataShards: 2, ParityShards: 2, FileOptions: 63, + Owner: mockClientId, } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ ID: tt.name + mockBlobberId + strconv.Itoa(i), diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index c5934a3c3..691a3288f 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "net/http" "os" "strconv" @@ -15,6 +14,7 @@ import ( "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/pathutil" + "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/hitenjain14/fasthttp" "github.com/0chain/gosdk_common/core/client" @@ -31,7 +31,12 @@ func setupHttpResponses( numBlobbers, numCorrect int, isUpdate bool) { walletJSON := `{"client_id":"00d2d56d0d573329fe61b8252a4b1715f93fac15176e5d90c413bc92a42e498b","client_key":"000b47144eb0366c3039bca10bc6df3ac289d8823de14ffc08cfdfe83f03e4079ab94bdc3932e7e9bc053f38834c7da63ce6f9c6e540d93cf0c52ba4149f2280","keys":[{"public_key":"000b47144eb0366c3039bca10bc6df3ac289d8823de14ffc08cfdfe83f03e4079ab94bdc3932e7e9bc053f38834c7da63ce6f9c6e540d93cf0c52ba4149f2280","private_key":"77a7faf0dcc1865a475963fee7ce71ca6dc6a20198209eb75d9fc1dc9df41f0f"}],"mnemonics":"mistake alone lumber swamp tape device flight oppose room combine useful typical deal lion device hope glad once million pudding artist brush sing vicious","version":"1.0","date_created":"2024-03-11T20:06:33+05:30","nonce":0}` - client.PopulateClient(walletJSON, "bls0chain") //nolint:errcheck + wallet := zcncrypto.Wallet{} + err := json.Unmarshal([]byte(walletJSON), &wallet) + require.NoError(t, err) + + client.SetWallet(wallet) + client.SetSignatureScheme("bls0chain") for i := 0; i < numBlobbers; i++ { metaBlobberBase := t.Name() + "/" + mockBlobberUrl + strconv.Itoa(i) + zboxutil.FILE_META_ENDPOINT @@ -53,7 +58,7 @@ func setupHttpResponses( } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader(fileMetaInput)), + Body: io.NopCloser(bytes.NewReader(fileMetaInput)), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -66,7 +71,7 @@ func setupHttpResponses( } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader(refsInput)), + Body: io.NopCloser(bytes.NewReader(refsInput)), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -121,7 +126,7 @@ func setupHttpResponses( } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"status":2}`))), + Body: io.NopCloser(bytes.NewReader([]byte(`{"status":2}`))), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -136,7 +141,7 @@ func setupHttpResponses( }(), Body: func() io.ReadCloser { s := `{"meta_data":{"chunk_size":0,"created_at":0,"hash":"","lookup_hash":"","name":"/","num_of_blocks":0,"path":"/","path_hash":"","size":0,"type":"d","updated_at":0},"Ref":{"ID":0,"Type":"d","AllocationID":"` + allocID + `","LookupHash":"","Name":"/","Path":"/","Hash":"","NumBlocks":0,"PathHash":"","ParentPath":"","PathLevel":1,"CustomMeta":"","ContentHash":"","Size":0,"MerkleRoot":"","ActualFileSize":0,"ActualFileHash":"","MimeType":"","WriteMarker":"","ThumbnailSize":0,"ThumbnailHash":"","ActualThumbnailSize":0,"ActualThumbnailHash":"","EncryptedKey":"","Children":null,"OnCloud":false,"CreatedAt":0,"UpdatedAt":0,"ChunkSize":0},"list":[{"meta_data":{"chunk_size":0,"created_at":0,"hash":"","lookup_hash":"","name":"1.txt","num_of_blocks":0,"path":"/1.txt","path_hash":"","size":0,"type":"f","updated_at":0},"Ref":{"ID":0,"Type":"f","AllocationID":"` + allocID + `","LookupHash":"","Name":"1.txt","Path":"/1.txt","Hash":"","NumBlocks":0,"PathHash":"","ParentPath":"/","PathLevel":1,"CustomMeta":"","ContentHash":"","Size":0,"MerkleRoot":"","ActualFileSize":0,"ActualFileHash":"","MimeType":"","WriteMarker":"","ThumbnailSize":0,"ThumbnailHash":"","ActualThumbnailSize":0,"ActualThumbnailHash":"","EncryptedKey":"","Children":null,"OnCloud":false,"CreatedAt":0,"UpdatedAt":0,"ChunkSize":0}}],"latest_write_marker":null}` - return ioutil.NopCloser(bytes.NewReader([]byte(s))) + return io.NopCloser(bytes.NewReader([]byte(s))) }(), }, nil) @@ -152,7 +157,7 @@ func setupHttpResponses( }(), Body: func() io.ReadCloser { s := `{"latest_write_marker":null,"prev_write_marker":null}` - return ioutil.NopCloser(bytes.NewReader([]byte(s))) + return io.NopCloser(bytes.NewReader([]byte(s))) }(), }, nil) @@ -166,7 +171,7 @@ func setupHttpResponses( } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -179,7 +184,7 @@ func setupHttpResponses( } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -210,6 +215,7 @@ func TestAllocation_UpdateFile(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -279,6 +285,7 @@ func TestAllocation_UploadFile(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -317,6 +324,7 @@ func TestAllocation_UpdateFileWithThumbnail(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -396,6 +404,7 @@ func TestAllocation_UploadFileWithThumbnail(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -431,6 +440,7 @@ func TestAllocation_EncryptAndUpdateFile(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -502,6 +512,7 @@ func TestAllocation_EncryptAndUploadFile(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -550,6 +561,7 @@ func TestAllocation_EncryptAndUpdateFileWithThumbnail(t *testing.T) { ParityShards: 2, DataShards: 2, Size: 2 * GB, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -626,6 +638,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { DataShards: 2, Size: 2 * GB, ctx: context.TODO(), + Owner: mockClientId, } setupMockAllocation(t, a) @@ -672,11 +685,10 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // resty.CreateClient = createClient // }() -// client := zclient.GetClient() -// client.Wallet = &zcncrypto.Wallet{ +// client.SetWallet(zcncrypto.Wallet{ // ClientID: mockClientId, // ClientKey: mockClientKey, -// } +// }) // // setupHttpResponses := func(t *testing.T, testName string, numBlobbers, numCorrect int) { // // require.True(t, numBlobbers >= numCorrect) @@ -699,7 +711,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // // }, // // }) // // require.NoError(t, err) -// // return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// // return io.NopCloser(bytes.NewReader([]byte(jsonFR))) // // }(frName, hash), // // }, nil) // // } @@ -726,7 +738,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // }, // }) // require.NoError(t, err) -// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// return io.NopCloser(bytes.NewReader([]byte(jsonFR))) // }(frName, hash), // } @@ -746,7 +758,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // Hash: mockChunkHash, // }) // require.NoError(t, err) -// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// return io.NopCloser(bytes.NewReader([]byte(jsonFR))) // }(frName, hash), // }, nil) @@ -757,7 +769,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // StatusCode: http.StatusOK, // Body: func() io.ReadCloser { // s := `{"latest_write_marker":null,"prev_write_marker":null}` -// return ioutil.NopCloser(bytes.NewReader([]byte(s))) +// return io.NopCloser(bytes.NewReader([]byte(s))) // }(), // }, nil) @@ -766,7 +778,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // return strings.HasPrefix(req.URL.String(), urlRollback) // })).Return(&http.Response{ // StatusCode: http.StatusOK, -// Body: ioutil.NopCloser(bytes.NewReader(nil)), +// Body: io.NopCloser(bytes.NewReader(nil)), // }, nil) // urlFilePath := "http://TestAllocation_RepairFile" + testName + mockBlobberUrl + strconv.Itoa(i) + "/v1/file/referencepath" @@ -784,7 +796,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // LatestWM: nil, // }) // require.NoError(t, err) -// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// return io.NopCloser(bytes.NewReader([]byte(jsonFR))) // }(frName, hash), // }, nil) @@ -796,7 +808,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // Body: func(fileRefName, hash string) io.ReadCloser { // jsonFR, err := json.Marshal(&ReferencePathResult{}) // require.NoError(t, err) -// return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) +// return io.NopCloser(bytes.NewReader([]byte(jsonFR))) // }(frName, hash), // }, nil) @@ -811,7 +823,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // Status: WMLockStatusOK, // } // respBuf, _ := json.Marshal(resp) -// return ioutil.NopCloser(bytes.NewReader(respBuf)) +// return io.NopCloser(bytes.NewReader(respBuf)) // }(), // }, nil) @@ -823,7 +835,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // StatusCode: http.StatusOK, // Body: func() io.ReadCloser { // respBuf, _ := json.Marshal("connection_id") -// return ioutil.NopCloser(bytes.NewReader(respBuf)) +// return io.NopCloser(bytes.NewReader(respBuf)) // }(), // }, nil) // } @@ -880,6 +892,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // ParityShards: tt.numBlobbers / 2, // DataShards: tt.numBlobbers / 2, // Size: 2 * GB, +// Owner: mockClientId, // } // a.downloadChan = make(chan *DownloadRequest, 10) // a.repairChan = make(chan *RepairRequest, 1) @@ -887,7 +900,7 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { // a.downloadProgressMap = make(map[string]*DownloadRequest) // a.mutex = &sync.Mutex{} // a.initialized = true -// sdkInitialized = true +// client.SetSdkInitialized(true) = true // for i := 0; i < tt.numBlobbers; i++ { // a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ // ID: mockBlobberId + strconv.Itoa(i), diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index 3df48631e..b7f6cfe0e 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -7,7 +7,6 @@ import ( "encoding/json" "io" "io/fs" - "io/ioutil" "log" "net/http" "os" @@ -23,12 +22,12 @@ import ( "golang.org/x/crypto/sha3" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -63,7 +62,7 @@ func setupMockGetFileMetaResponse( strings.HasPrefix(req.URL.String(), url) })).Return(&http.Response{ StatusCode: statusCode, - Body: ioutil.NopCloser(bytes.NewReader(body)), + Body: io.NopCloser(bytes.NewReader(body)), }, nil).Once() } } @@ -140,7 +139,7 @@ func setupMockWriteLockRequest(a *Allocation, mockClient *mocks.HttpClient) { func setupMockFile(t *testing.T, path string) (teardown func(t *testing.T)) { _, err := os.Create(path) require.Nil(t, err) - err = ioutil.WriteFile(path, []byte("mockActualHash"), os.ModePerm) + err = os.WriteFile(path, []byte("mockActualHash"), os.ModePerm) require.Nil(t, err) return func(t *testing.T) { os.Remove(path) @@ -158,7 +157,7 @@ func setupMockRollback(a *Allocation, mockClient *mocks.HttpClient) { StatusCode: http.StatusOK, Body: func() io.ReadCloser { s := `{"latest_write_marker":null,"prev_write_marker":null}` - return ioutil.NopCloser(bytes.NewReader([]byte(s))) + return io.NopCloser(bytes.NewReader([]byte(s))) }(), }, nil) @@ -168,7 +167,7 @@ func setupMockRollback(a *Allocation, mockClient *mocks.HttpClient) { return strings.Contains(req.URL.String(), newUrl) })).Return(&http.Response{ StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, nil) } @@ -216,7 +215,7 @@ func TestGetMinMaxWriteReadSuccess(t *testing.T) { ssc.ParityShards = 4 ssc.initialized = true - sdkInitialized = true + client.SetSdkInitialized(true) require.NotNil(t, ssc.BlobberDetails) t.Run("Success minR, minW", func(t *testing.T) { @@ -264,7 +263,7 @@ func TestGetMaxMinStorageCostSuccess(t *testing.T) { ssc.ParityShards = 2 ssc.initialized = true - sdkInitialized = true + client.SetSdkInitialized(true) t.Run("Storage cost", func(t *testing.T) { cost, err := ssc.GetMaxStorageCost(100 * GB) @@ -400,11 +399,10 @@ func TestAllocation_GetBlobberStats(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) tests := []struct { name string @@ -422,7 +420,7 @@ func TestAllocation_GetBlobberStats(t *testing.T) { Tx: mockAllocationTxId, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), StatusCode: http.StatusOK, }, nil) @@ -484,9 +482,9 @@ func TestAllocation_isInitialized(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - originalSDKInitialized := sdkInitialized - defer func() { sdkInitialized = originalSDKInitialized }() - sdkInitialized = tt.sdkInitialized + originalSDKInitialized := client.IsSDKInitialized() + defer func() { client.SetSdkInitialized(originalSDKInitialized) }() + client.SetSdkInitialized(tt.sdkInitialized) a := &Allocation{initialized: tt.allocationInitialized} got := a.isInitialized() require := require.New(t) @@ -517,7 +515,7 @@ func TestAllocation_isInitialized(t *testing.T) { // client := zclient.GetClient() // client.Wallet = &zcncrypto.Wallet{ -// ClientID: mockClientId, +// Id: mockClientId, // ClientKey: mockClientKey, // } @@ -525,7 +523,7 @@ func TestAllocation_isInitialized(t *testing.T) { // return strings.HasPrefix(req.URL.Path, "TestAllocation_CreateDir") // })).Return(&http.Response{ // StatusCode: http.StatusOK, -// Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), +// Body: io.NopCloser(bytes.NewReader([]byte(""))), // }, nil) // for i := 0; i < numBlobbers; i++ { @@ -546,11 +544,10 @@ func TestAllocation_RepairRequired(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) tests := []struct { name string @@ -575,7 +572,7 @@ func TestAllocation_RepairRequired(t *testing.T) { StatusCode: http.StatusOK, Body: func() io.ReadCloser { respString := `{"file_meta_hash":"` + mockActualHash + `"}` - return ioutil.NopCloser(bytes.NewReader([]byte(respString))) + return io.NopCloser(bytes.NewReader([]byte(respString))) }(), }, nil) } @@ -616,7 +613,7 @@ func TestAllocation_RepairRequired(t *testing.T) { StatusCode: http.StatusOK, Body: func(hash string) io.ReadCloser { respString := `{"file_meta_hash":"` + hash + `"}` - return ioutil.NopCloser(bytes.NewReader([]byte(respString))) + return io.NopCloser(bytes.NewReader([]byte(respString))) }(hash), }, nil) } @@ -639,7 +636,7 @@ func TestAllocation_RepairRequired(t *testing.T) { return strings.HasPrefix(req.URL.Path, url) })).Return(&http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) } return nil @@ -660,7 +657,7 @@ func TestAllocation_RepairRequired(t *testing.T) { FileOptions: 63, } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) if tt.setup != nil { if teardown := tt.setup(t, tt.name, a); teardown != nil { defer teardown(t) @@ -694,11 +691,10 @@ func TestAllocation_DownloadFileToFileHandler(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { fileHandler sys.File @@ -731,7 +727,7 @@ func TestAllocation_DownloadFileToFileHandler(t *testing.T) { ActualFileHash: mockActualHash, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) } @@ -776,11 +772,10 @@ func TestAllocation_DownloadFile(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) a := &Allocation{ @@ -806,7 +801,7 @@ func TestAllocation_DownloadFile(t *testing.T) { ActualFileHash: mockActualHash, }) require.NoError(err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) } @@ -824,11 +819,10 @@ func TestAllocation_DownloadFileByBlock(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) a := &Allocation{ @@ -879,11 +873,10 @@ func TestAllocation_downloadFile(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { localPath, remotePath, contentMode string @@ -958,7 +951,7 @@ func TestAllocation_downloadFile(t *testing.T) { ActualFileHash: mockActualHash, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) } @@ -978,7 +971,7 @@ func TestAllocation_downloadFile(t *testing.T) { a.downloadProgressMap = make(map[string]*DownloadRequest) a.mutex = &sync.Mutex{} a.initialized = true - sdkInitialized = true + client.SetSdkInitialized(true) setupMockAllocation(t, a) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ @@ -1019,11 +1012,10 @@ func TestAllocation_GetRefs(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) functionName := "TestAllocation_GetRefs" t.Run("Test_Get_Refs_Returns_Slice_Of_Length_0_When_File_Not_Present", func(t *testing.T) { a := &Allocation{ @@ -1032,7 +1024,7 @@ func TestAllocation_GetRefs(t *testing.T) { } testCaseName := "Test_Get_Refs_Returns_Slice_Of_Length_0_When_File_Not_Present" a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ ID: testCaseName + mockBlobberId + strconv.Itoa(i), @@ -1064,11 +1056,10 @@ func TestAllocation_GetFileMeta(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { path string @@ -1132,7 +1123,7 @@ func TestAllocation_GetFileMeta(t *testing.T) { FileOptions: 63, } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ ID: tt.name + mockBlobberId + strconv.Itoa(i), @@ -1173,7 +1164,7 @@ func TestAllocation_GetAuthTicketForShare(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), } zboxutil.Client = &mockClient @@ -1181,18 +1172,17 @@ func TestAllocation_GetAuthTicketForShare(t *testing.T) { mockClient.On("Do", mock.Anything).Return(&httpResponse, nil) } - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) a := &Allocation{DataShards: 1, ParityShards: 1, FileOptions: 63} a.InitAllocation() for i := 0; i < numberBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{}) } - sdkInitialized = true + client.SetSdkInitialized(true) at, err := a.GetAuthTicketForShare("/1.txt", "1.txt", fileref.FILE, "") require.NotEmptyf(at, "unexpected empty auth ticket") require.NoErrorf(err, "unexpected error: %v", err) @@ -1227,7 +1217,7 @@ func TestAllocation_GetAuthTicket(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), } for i := 0; i < numBlobbers; i++ { @@ -1258,7 +1248,7 @@ func TestAllocation_GetAuthTicket(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), } for i := 0; i < numBlobbers; i++ { @@ -1309,7 +1299,7 @@ func TestAllocation_GetAuthTicket(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), } for i := 0; i < numBlobbers; i++ { @@ -1349,7 +1339,7 @@ func TestAllocation_GetAuthTicket(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), } for i := 0; i < numBlobbers; i++ { @@ -1383,11 +1373,10 @@ func TestAllocation_GetAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) a := &Allocation{ @@ -1396,7 +1385,7 @@ func TestAllocation_GetAuthTicket(t *testing.T) { FileOptions: 63, } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ @@ -1459,7 +1448,7 @@ func TestAllocation_CancelDownload(t *testing.T) { require := require.New(t) a := &Allocation{FileOptions: 63} a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) if tt.setup != nil { if teardown := tt.setup(t, a); teardown != nil { defer teardown(t) @@ -1593,11 +1582,10 @@ func TestAllocation_ListDirFromAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) a := &Allocation{ ID: mockAllocationId, Tx: mockAllocationTxId, @@ -1616,7 +1604,7 @@ func TestAllocation_ListDirFromAuthTicket(t *testing.T) { setupMockGetFileInfoResponse(t, &mockClient) a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) if len(a.Blobbers) == 0 { for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{}) @@ -1647,11 +1635,10 @@ func TestAllocation_downloadFromAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) a := &Allocation{ ID: mockAllocationId, @@ -1873,11 +1860,10 @@ func TestAllocation_listDir(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) a := &Allocation{ @@ -1891,7 +1877,7 @@ func TestAllocation_listDir(t *testing.T) { tt.parameters.expectedResult.deleteMask = zboxutil.NewUint128(1).Lsh(uint64(a.DataShards + a.ParityShards)).Sub64(1) } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ ID: tt.name + mockBlobberId + strconv.Itoa(i), @@ -2007,11 +1993,10 @@ func TestAllocation_GetFileMetaFromAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) a := &Allocation{ ID: mockAllocationId, @@ -2021,7 +2006,7 @@ func TestAllocation_GetFileMetaFromAuthTicket(t *testing.T) { FileOptions: 63, } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) a.initialized = true require := require.New(t) @@ -2056,11 +2041,10 @@ func TestAllocation_DownloadToFileHandlerFromAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) @@ -2092,11 +2076,10 @@ func TestAllocation_DownloadThumbnailFromAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) @@ -2135,11 +2118,10 @@ func TestAllocation_DownloadFromAuthTicket(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) @@ -2172,11 +2154,10 @@ func TestAllocation_DownloadFromAuthTicketByBlocks(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) require := require.New(t) @@ -2208,11 +2189,10 @@ func TestAllocation_StartRepair(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { localPath, pathToRepair string @@ -2338,7 +2318,7 @@ func setupMockAllocation(t *testing.T, a *Allocation) { if a.DataShards != 0 { a.fullconsensus, a.consensusThreshold = a.getConsensuses() } - sdkInitialized = true + client.SetSdkInitialized(true) go func() { for { @@ -2381,7 +2361,7 @@ func setupMockGetFileInfoResponse(t *testing.T, mockClient *mocks.HttpClient) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), } for i := 0; i < numBlobbers; i++ { @@ -2393,11 +2373,10 @@ func getMockAuthTicket(t *testing.T) string { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) a := &Allocation{ ID: mockAllocationId, Tx: mockAllocationTxId, @@ -2407,7 +2386,7 @@ func getMockAuthTicket(t *testing.T) string { } a.InitAllocation() - sdkInitialized = true + client.SetSdkInitialized(true) for i := 0; i < numBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ ID: strconv.Itoa(i), @@ -2426,7 +2405,7 @@ func getMockAuthTicket(t *testing.T) string { httpResponse := &http.Response{ StatusCode: http.StatusOK, Body: func() io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader(jsonFR)) + return io.NopCloser(bytes.NewReader(jsonFR)) }(), } diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 032089cb6..2c28979f9 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -10,8 +10,8 @@ import ( "math" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/zboxcore/client" ) // CreateAllocationForOwner creates a new allocation with the given options (txn: `storagesc.new_allocation_request`). @@ -50,7 +50,7 @@ func CreateAllocationForOwner( return "", 0, nil, errors.New("failed_get_allocation_blobbers", "failed to get blobbers for allocation: "+err.Error()) } - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", 0, nil, sdkNotInitialized } @@ -74,11 +74,11 @@ func CreateAllocationForOwner( // // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } - recipientPublicKey := client.GetClientPublicKey() + recipientPublicKey := client.PublicKey() var input = map[string]interface{}{ "recipient_public_key": recipientPublicKey, @@ -126,7 +126,7 @@ func UpdateAllocation( return "", 0, errors.New("invalid_lock", "int64 overflow on lock value") } - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -136,7 +136,7 @@ func UpdateAllocation( } updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = client.GetClientID() + updateAllocationRequest["owner_id"] = client.Id() updateAllocationRequest["owner_public_key"] = "" updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size @@ -175,7 +175,7 @@ func GetUpdateAllocTicket(allocationID, userID, operationType string, roundExpir // - value: value to lock // - fee: transaction fee func StakePoolLock(providerType ProviderType, providerID string, value, fee uint64) (hash string, nonce int64, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -211,7 +211,7 @@ func StakePoolLock(providerType ProviderType, providerID string, value, fee uint return "", 0, errors.Newf("stake_pool_lock", "unsupported provider type: %v", providerType) } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(scAddress, sn, value, fee) + hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(scAddress, sn, value, fee, true) return } @@ -225,7 +225,7 @@ func StakePoolLock(providerType ProviderType, providerID string, value, fee uint // - providerID: provider ID // - fee: transaction fee func StakePoolUnlock(providerType ProviderType, providerID, clientID string, fee uint64) (unstake int64, nonce int64, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return 0, 0, sdkNotInitialized } @@ -263,7 +263,7 @@ func StakePoolUnlock(providerType ProviderType, providerID, clientID string, fee } var out string - if _, out, nonce, _, err = smartContractTxnValueFeeWithRetry(scAddress, sn, 0, fee); err != nil { + if _, out, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(scAddress, sn, 0, fee, true); err != nil { return // an error } @@ -275,37 +275,6 @@ func StakePoolUnlock(providerType ProviderType, providerID, clientID string, fee return spuu.Amount, nonce, nil } -// 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 - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_READ_POOL_LOCK, - InputArgs: nil, - } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, tokens, fee) - return -} - -// 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 - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_READ_POOL_UNLOCK, - InputArgs: nil, - } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, 0, fee) - return -} - // // write pool // @@ -315,7 +284,7 @@ func ReadPoolUnlock(fee uint64) (hash string, nonce int64, err error) { // - tokens: number of tokens to lock // - fee: transaction fee func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -331,7 +300,7 @@ func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64 InputArgs: &req, } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, tokens, fee) + hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, tokens, fee, true) return } @@ -339,7 +308,7 @@ func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64 // - allocID: allocation ID // - fee: transaction fee func WritePoolUnlock(allocID string, fee uint64) (hash string, nonce int64, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -354,43 +323,6 @@ func WritePoolUnlock(allocID string, fee uint64) (hash string, nonce int64, err Name: transaction.STORAGESC_WRITE_POOL_UNLOCK, InputArgs: &req, } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, 0, fee) + hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, 0, fee, true) return } - -func smartContractTxn(scAddress string, sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - return smartContractTxnValue(scAddress, sn, 0) -} - -func StorageSmartContractTxn(sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return storageSmartContractTxnValue(sn, 0) -} - -func storageSmartContractTxn(sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return storageSmartContractTxnValue(sn, 0) -} - -func smartContractTxnValue(scAddress string, sn transaction.SmartContractTxnData, value uint64) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return smartContractTxnValueFeeWithRetry(scAddress, sn, value, client.TxnFee()) -} - -func storageSmartContractTxnValue(sn transaction.SmartContractTxnData, value uint64) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - // Fee is set during sdk initialization. - return smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, value, client.TxnFee()) -} - -func smartContractTxnValueFeeWithRetry(scAddress string, sn transaction.SmartContractTxnData, - value, fee uint64) (hash, out string, nonce int64, t *transaction.Transaction, err error) { - - // Fee is set during sdk initialization. - return transaction.SmartContractTxnValueFeeWithRetry(scAddress, sn, value, fee, true) -} diff --git a/zboxcore/sdk/blockdownloadworker.go b/zboxcore/sdk/blockdownloadworker.go index e7663c2d5..dae2e30ec 100644 --- a/zboxcore/sdk/blockdownloadworker.go +++ b/zboxcore/sdk/blockdownloadworker.go @@ -10,9 +10,9 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" zlogger "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/marker" @@ -180,7 +180,7 @@ func (req *BlockDownloadRequest) downloadBlobberBlock(fastClient *fasthttp.Clien var rspData downloadBlock if statuscode != http.StatusOK { - zlogger.Logger.Error(fmt.Sprintf("downloadBlobberBlock FAIL - blobberID: %v, clientID: %v, blockNum: %d, retry: %d, response: %v", req.blobber.ID, client.GetClientID(), header.BlockNum, retry, string(respBuf))) + zlogger.Logger.Error(fmt.Sprintf("downloadBlobberBlock FAIL - blobberID: %v, clientID: %v, blockNum: %d, retry: %d, response: %v", req.blobber.ID, client.Id(), header.BlockNum, retry, string(respBuf))) if err = json.Unmarshal(respBuf, &rspData); err == nil { return errors.New("download_error", fmt.Sprintf("Response status: %d, Error: %v,", statuscode, rspData.err)) } @@ -219,7 +219,7 @@ func (req *BlockDownloadRequest) downloadBlobberBlock(fastClient *fasthttp.Clien rspData.BlockChunks = splitData(dR.Data, req.chunkSize) } - zlogger.Logger.Debug(fmt.Sprintf("downloadBlobberBlock 200 OK: blobberID: %v, clientID: %v, blockNum: %d", req.blobber.ID, client.GetClientID(), header.BlockNum)) + zlogger.Logger.Debug(fmt.Sprintf("downloadBlobberBlock 200 OK: blobberID: %v, clientID: %v, blockNum: %d", req.blobber.ID, client.Id(), header.BlockNum)) req.result <- &rspData return nil diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index bd52e8b39..82d73d30e 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -18,12 +18,12 @@ import ( thrown "github.com/0chain/errors" "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" coreEncryption "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/util" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/encryption" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -256,7 +256,7 @@ func CreateChunkedUpload( } - su.writeMarkerMutex, err = CreateWriteMarkerMutex(client.GetClient(), su.allocationObj) + su.writeMarkerMutex, err = CreateWriteMarkerMutex(su.allocationObj) if err != nil { return nil, err } @@ -383,7 +383,7 @@ func (su *ChunkedUpload) createEncscheme() encryption.EncryptionScheme { return nil } } else { - mnemonic := client.GetClient().Mnemonic + mnemonic := client.Mnemonic() if mnemonic == "" { return nil } diff --git a/zboxcore/sdk/chunked_upload_bench_test.go b/zboxcore/sdk/chunked_upload_bench_test.go index 156234f12..dd41d218c 100644 --- a/zboxcore/sdk/chunked_upload_bench_test.go +++ b/zboxcore/sdk/chunked_upload_bench_test.go @@ -89,6 +89,7 @@ func BenchmarkChunkedUpload(b *testing.B) { DataShards: 2, ParityShards: 1, ctx: context.TODO(), + Owner: mockClientId, } a.fullconsensus, a.consensusThreshold = a.getConsensuses() for i := 0; i < (a.DataShards + a.ParityShards); i++ { diff --git a/zboxcore/sdk/chunked_upload_blobber.go b/zboxcore/sdk/chunked_upload_blobber.go index fb6f5e817..7ef361d19 100644 --- a/zboxcore/sdk/chunked_upload_blobber.go +++ b/zboxcore/sdk/chunked_upload_blobber.go @@ -16,8 +16,8 @@ import ( thrown "github.com/0chain/errors" "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/constants" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/marker" @@ -80,7 +80,7 @@ func (sb *ChunkedUploadBlobber) sendUploadRequest( var req *fasthttp.Request for i := 0; i < 3; i++ { req, err = zboxutil.NewFastUploadRequest( - sb.blobber.Baseurl, su.allocationObj.ID, su.allocationObj.Tx, dataBuffers[ind].Bytes(), su.httpMethod) + sb.blobber.Baseurl, su.allocationObj.ID, su.allocationObj.Tx, dataBuffers[ind].Bytes(), su.httpMethod, su.allocationObj.Owner) if err != nil { return err } @@ -202,7 +202,7 @@ func (sb *ChunkedUploadBlobber) processCommit(ctx context.Context, su *ChunkedUp wm.BlobberID = sb.blobber.ID wm.Timestamp = timestamp - wm.ClientID = client.GetClientID() + wm.ClientID = client.Id(su.allocationObj.Owner) err = wm.Sign() if err != nil { logger.Logger.Error("Signing writemarker failed: ", err) @@ -328,7 +328,7 @@ func (sb *ChunkedUploadBlobber) processWriteMarker( } var lR ReferencePathResult - req, err := zboxutil.NewReferencePathRequest(sb.blobber.Baseurl, su.allocationObj.ID, su.allocationObj.Tx, su.allocationObj.sig, paths) + req, err := zboxutil.NewReferencePathRequest(sb.blobber.Baseurl, su.allocationObj.ID, su.allocationObj.Tx, su.allocationObj.sig, paths, su.allocationObj.Owner) if err != nil || len(paths) == 0 { logger.Logger.Error("Creating ref path req", err) return nil, nil, 0, nil, err diff --git a/zboxcore/sdk/chunked_upload_form_builder.go b/zboxcore/sdk/chunked_upload_form_builder.go index 643364104..fc3fa38de 100644 --- a/zboxcore/sdk/chunked_upload_form_builder.go +++ b/zboxcore/sdk/chunked_upload_form_builder.go @@ -7,7 +7,7 @@ import ( "io" "mime/multipart" - "github.com/0chain/gosdk_common/zboxcore/client" + "github.com/0chain/gosdk_common/core/client" "golang.org/x/crypto/sha3" ) diff --git a/zboxcore/sdk/chunked_upload_process_js.go b/zboxcore/sdk/chunked_upload_process_js.go index c450bf1f6..68885efa5 100644 --- a/zboxcore/sdk/chunked_upload_process_js.go +++ b/zboxcore/sdk/chunked_upload_process_js.go @@ -40,6 +40,7 @@ type workerProcess struct { } type ChunkedUploadFormInfo struct { + ClientId string ConnectionID string ChunkSize int64 ChunkStartIndex int @@ -102,6 +103,7 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, ) formInfo := ChunkedUploadFormInfo{ + ClientId: su.allocationObj.Owner, ConnectionID: su.progress.ConnectionID, ChunkSize: su.chunkSize, ChunkStartIndex: chunkStartIndex, @@ -471,13 +473,13 @@ func ProcessEventData(data safejs.Value) { } go func(blobberData blobberData, remotePath string, wg *sync.WaitGroup) { if formInfo.IsFinal && len(blobberData.dataBuffers) > 1 { - err = sendUploadRequest(blobberData.dataBuffers[:len(blobberData.dataBuffers)-1], blobberData.contentSlice[:len(blobberData.contentSlice)-1], blobberURL, formInfo.AllocationID, formInfo.AllocationTx, formInfo.HttpMethod) + err = sendUploadRequest(blobberData.dataBuffers[:len(blobberData.dataBuffers)-1], blobberData.contentSlice[:len(blobberData.contentSlice)-1], blobberURL, formInfo.AllocationID, formInfo.AllocationTx, formInfo.HttpMethod, formInfo.ClientId) if err != nil { selfPostMessage(false, true, err.Error(), remotePath, formInfo.ChunkEndIndex, nil) return } wg.Wait() - err = sendUploadRequest(blobberData.dataBuffers[len(blobberData.dataBuffers)-1:], blobberData.contentSlice[len(blobberData.contentSlice)-1:], blobberURL, formInfo.AllocationID, formInfo.AllocationTx, formInfo.HttpMethod) + err = sendUploadRequest(blobberData.dataBuffers[len(blobberData.dataBuffers)-1:], blobberData.contentSlice[len(blobberData.contentSlice)-1:], blobberURL, formInfo.AllocationID, formInfo.AllocationTx, formInfo.HttpMethod, formInfo.ClientId) if err != nil { selfPostMessage(false, true, err.Error(), remotePath, formInfo.ChunkEndIndex, nil) return @@ -488,7 +490,7 @@ func ProcessEventData(data safejs.Value) { } else { defer wg.Done() } - err = sendUploadRequest(blobberData.dataBuffers, blobberData.contentSlice, blobberURL, formInfo.AllocationID, formInfo.AllocationTx, formInfo.HttpMethod) + err = sendUploadRequest(blobberData.dataBuffers, blobberData.contentSlice, blobberURL, formInfo.AllocationID, formInfo.AllocationTx, formInfo.HttpMethod, formInfo.ClientId) if err != nil { selfPostMessage(false, formInfo.IsFinal, err.Error(), remotePath, formInfo.ChunkEndIndex, nil) return @@ -600,7 +602,7 @@ func parseEventData(data safejs.Value) (*FileMeta, *ChunkedUploadFormInfo, [][]b return fileMeta, formInfo, fileShards, thumbnailChunkData, nil } -func sendUploadRequest(dataBuffers []*bytes.Buffer, contentSlice []string, blobberURL, allocationID, allocationTx, httpMethod string) (err error) { +func sendUploadRequest(dataBuffers []*bytes.Buffer, contentSlice []string, blobberURL, allocationID, allocationTx, httpMethod string, clientId ...string) (err error) { eg, _ := errgroup.WithContext(context.TODO()) for dataInd := 0; dataInd < len(dataBuffers); dataInd++ { ind := dataInd @@ -611,7 +613,7 @@ func sendUploadRequest(dataBuffers []*bytes.Buffer, contentSlice []string, blobb var req *fasthttp.Request for i := 0; i < 3; i++ { req, err = zboxutil.NewFastUploadRequest( - blobberURL, allocationID, allocationTx, dataBuffers[ind].Bytes(), httpMethod) + blobberURL, allocationID, allocationTx, dataBuffers[ind].Bytes(), httpMethod, clientId...) if err != nil { return err } diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index a882caca5..cdd4f5af9 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "strconv" @@ -50,6 +49,7 @@ func SuccessCommitResult() *CommitResult { const MARKER_VERSION = "v2" type CommitRequest struct { + ClientId string changes []allocationchange.AllocationChange blobber *blockchain.StorageNode allocationID string @@ -242,7 +242,7 @@ func (commitreq *CommitRequest) calculateHashRequest(ctx context.Context, paths if resp.StatusCode != http.StatusOK { l.Logger.Error("Calculate hash response : ", resp.StatusCode) } - resp_body, err := ioutil.ReadAll(resp.Body) + resp_body, err := io.ReadAll(resp.Body) if err != nil { l.Logger.Error("Calculate hash: Resp", err) return err diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 4bcf6df6a..29407459f 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "path" "strconv" @@ -22,7 +22,7 @@ import ( const alreadyExists = "file already exists" -func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx string, remoteFilePath, sig string, blobber *blockchain.StorageNode) (fileref.RefEntity, error) { +func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx string, remoteFilePath, sig string, blobber *blockchain.StorageNode, clientId ...string) (fileref.RefEntity, error) { httpreq, err := zboxutil.NewObjectTreeRequest(blobber.Baseurl, allocationID, allocationTx, sig, remoteFilePath) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating object tree request", err) @@ -39,7 +39,7 @@ func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx st if resp.StatusCode != http.StatusOK { l.Logger.Error("Object tree response : ", resp.StatusCode) } - resp_body, err := ioutil.ReadAll(resp.Body) + resp_body, err := io.ReadAll(resp.Body) if err != nil { l.Logger.Error("Object tree: Resp", err) return err @@ -65,9 +65,9 @@ func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx st return lR.GetRefFromObjectTree(allocationID) } -func getAllocationDataFromBlobber(blobber *blockchain.StorageNode, allocationId string, allocationTx string, respCh chan<- *BlobberAllocationStats, wg *sync.WaitGroup) { +func getAllocationDataFromBlobber(blobber *blockchain.StorageNode, allocationId string, allocationTx string, respCh chan<- *BlobberAllocationStats, wg *sync.WaitGroup, clientId ...string) { defer wg.Done() - httpreq, err := zboxutil.NewAllocationRequest(blobber.Baseurl, allocationId, allocationTx) + httpreq, err := zboxutil.NewAllocationRequest(blobber.Baseurl, allocationId, allocationTx, clientId...) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating allocation request", err) return @@ -84,7 +84,7 @@ func getAllocationDataFromBlobber(blobber *blockchain.StorageNode, allocationId if resp.StatusCode != http.StatusOK { l.Logger.Error("Get allocation response : ", resp.StatusCode) } - resp_body, err := ioutil.ReadAll(resp.Body) + resp_body, err := io.ReadAll(resp.Body) if err != nil { l.Logger.Error("Get allocation: Resp", err) return err diff --git a/zboxcore/sdk/copyworker.go b/zboxcore/sdk/copyworker.go index 3730fc906..ffb9aa7bb 100644 --- a/zboxcore/sdk/copyworker.go +++ b/zboxcore/sdk/copyworker.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "mime/multipart" "net/http" "path" @@ -18,7 +18,6 @@ import ( "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -49,7 +48,7 @@ type CopyRequest struct { const objAlreadyExists = "Object Already exists" func (req *CopyRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNode) (fileref.RefEntity, error) { - return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.sig, req.remotefilepath, blobber) + return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.sig, req.remotefilepath, blobber, req.allocationObj.Owner) } func (req *CopyRequest) getFileMetaFromBlobber(pos int) (fileRef *fileref.FileRef, err error) { @@ -118,7 +117,7 @@ func (req *CopyRequest) copyBlobberObject( cncl context.CancelFunc ) - httpreq, err = zboxutil.NewCopyRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body) + httpreq, err = zboxutil.NewCopyRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body, req.allocationObj.Owner) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating rename request", err) return @@ -138,7 +137,7 @@ func (req *CopyRequest) copyBlobberObject( if resp.Body != nil { defer resp.Body.Close() } - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { logger.Logger.Error("Error: Resp ", err) return @@ -275,7 +274,7 @@ func (req *CopyRequest) ProcessCopy() error { req.Consensus.consensusThresh, req.Consensus.consensus)) } - writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), req.allocationObj) + writeMarkerMutex, err := CreateWriteMarkerMutex(req.allocationObj) if err != nil { return fmt.Errorf("Copy failed: %s", err.Error()) } @@ -324,6 +323,7 @@ func (req *CopyRequest) ProcessCopy() error { newChange.Operation = constants.FileOperationCopy newChange.Size = 0 commitReq := &CommitRequest{ + ClientId: req.allocationObj.Owner, allocationID: req.allocationID, allocationTx: req.allocationTx, sig: req.sig, diff --git a/zboxcore/sdk/copyworker_test.go b/zboxcore/sdk/copyworker_test.go index d27c2a00f..243536fc0 100644 --- a/zboxcore/sdk/copyworker_test.go +++ b/zboxcore/sdk/copyworker_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -15,12 +14,12 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/dev" devMock "github.com/0chain/gosdk_common/dev/mock" "github.com/0chain/gosdk_common/sdks/blobber" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -43,11 +42,10 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { referencePathToRetrieve fileref.ReferencePath @@ -75,7 +73,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { return strings.HasPrefix(req.URL.Path, testName) })).Return(&http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) }, wantErr: true, @@ -101,7 +99,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -112,7 +110,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { req.Header.Get("X-App-Client-Key") == mockClientKey })).Return(&http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) }, wantErr: true, @@ -148,7 +146,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -167,7 +165,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { } expected, ok := p.requestFields[part.FormName()] require.True(t, ok) - actual, err := ioutil.ReadAll(part) + actual, err := io.ReadAll(part) require.NoError(t, err) require.EqualValues(t, expected, string(actual)) } @@ -183,7 +181,7 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) }, @@ -211,6 +209,9 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { maskMU: &sync.Mutex{}, ctx: context.TODO(), connectionID: mockConnectionId, + allocationObj: &Allocation{ + Owner: mockClientId, + }, } req.blobbers = append(req.blobbers, &blockchain.StorageNode{ Baseurl: tt.name, @@ -249,11 +250,10 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) zboxutil.Client = &mockClient @@ -276,7 +276,7 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -291,7 +291,7 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -305,7 +305,7 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"status":2}`))), + Body: io.NopCloser(bytes.NewReader([]byte(`{"status":2}`))), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -319,7 +319,7 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -442,6 +442,7 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { Tx: "TestCopyRequest_ProcessCopy", DataShards: numBlobbers, FileOptions: 63, + Owner: mockClientId, } a.InitAllocation() @@ -489,7 +490,7 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { maskMU: &sync.Mutex{}, connectionID: mockConnectionId, } - sig, err := zclient.Sign(mockAllocationTxId) + sig, err := client.Sign(mockAllocationTxId) require.NoError(err) req.sig = sig req.ctx, req.ctxCncl = context.WithCancel(context.TODO()) diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index bfe185b3d..c7d98a265 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -20,7 +19,6 @@ import ( "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -65,7 +63,7 @@ func (req *DeleteRequest) deleteBlobberFile( query.Add("connection_id", req.connectionID) query.Add("path", req.remotefilepath) - httpreq, err := zboxutil.NewDeleteRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, query) + httpreq, err := zboxutil.NewDeleteRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, query, req.allocationObj.Owner) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating delete request", err) return err @@ -107,7 +105,7 @@ func (req *DeleteRequest) deleteBlobberFile( return } if resp.StatusCode == http.StatusBadRequest { - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { logger.Logger.Error("Failed to read response body", err) } @@ -138,7 +136,7 @@ func (req *DeleteRequest) deleteBlobberFile( return } - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { l.Logger.Error(blobber.Baseurl, "Response: ", string(respBody)) return @@ -175,7 +173,7 @@ func (req *DeleteRequest) getObjectTreeFromBlobber(pos uint64) ( fRefEntity, err = getObjectTreeFromBlobber( req.ctx, req.allocationID, req.allocationTx, req.sig, - req.remotefilepath, req.blobbers[pos]) + req.remotefilepath, req.blobbers[pos], req.allocationObj.Owner) return } @@ -188,6 +186,7 @@ func (req *DeleteRequest) getFileMetaFromBlobber(pos uint64) (fileRef *fileref.F } }() listReq := &ListRequest{ + ClientId: req.allocationObj.Owner, allocationID: req.allocationID, allocationTx: req.allocationTx, blobbers: req.blobbers, @@ -279,7 +278,7 @@ func (req *DeleteRequest) ProcessDelete() (err error) { req.consensus.consensusThresh, req.consensus.getConsensus())) } - writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), req.allocationObj) + writeMarkerMutex, err := CreateWriteMarkerMutex(req.allocationObj) if err != nil { return fmt.Errorf("Delete failed: %s", err.Error()) } @@ -307,6 +306,7 @@ func (req *DeleteRequest) ProcessDelete() (err error) { newChange.Operation = constants.FileOperationDelete newChange.Size = newChange.FileMetaRef.GetSize() commitReq := &CommitRequest{ + ClientId: req.allocationObj.Owner, allocationID: req.allocationID, allocationTx: req.allocationTx, sig: req.sig, diff --git a/zboxcore/sdk/deleteworker_test.go b/zboxcore/sdk/deleteworker_test.go index 32cf119f0..c6d861c9c 100644 --- a/zboxcore/sdk/deleteworker_test.go +++ b/zboxcore/sdk/deleteworker_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "net/http" "strconv" "strings" @@ -14,10 +13,10 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -40,11 +39,10 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) var wg sync.WaitGroup @@ -81,7 +79,7 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil} } @@ -96,7 +94,7 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { for _, c := range mockClient.ExpectedCalls { c.ReturnArguments = mock.Arguments{&http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(strings.NewReader("")), + Body: io.NopCloser(strings.NewReader("")), }, nil} } }) @@ -131,7 +129,7 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -151,7 +149,7 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) }, @@ -179,6 +177,9 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { ctx: context.TODO(), connectionID: mockConnectionId, wg: func() *sync.WaitGroup { wg.Add(1); return &wg }(), + allocationObj: &Allocation{ + Owner: mockClientId, + }, } req.blobbers = append(req.blobbers, &blockchain.StorageNode{ Baseurl: tt.name, @@ -214,11 +215,10 @@ func TestDeleteRequest_ProcessDelete(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) zboxutil.Client = &mockClient resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { @@ -245,7 +245,7 @@ func TestDeleteRequest_ProcessDelete(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -258,7 +258,7 @@ func TestDeleteRequest_ProcessDelete(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) } @@ -380,6 +380,7 @@ func TestDeleteRequest_ProcessDelete(t *testing.T) { a := &Allocation{ DataShards: numBlobbers, + Owner: mockClientId, } for i := 0; i < tt.numBlobbers; i++ { diff --git a/zboxcore/sdk/dirworker.go b/zboxcore/sdk/dirworker.go index 32c4fcf9d..dc28fc09b 100644 --- a/zboxcore/sdk/dirworker.go +++ b/zboxcore/sdk/dirworker.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "mime/multipart" "net/http" "path" @@ -17,7 +17,6 @@ import ( "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/util" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -86,7 +85,7 @@ func (req *DirRequest) ProcessDir(a *Allocation) error { return errors.New("consensus_not_met", "directory creation failed due to consensus not met") } - writeMarkerMU, err := CreateWriteMarkerMutex(client.GetClient(), a) + writeMarkerMU, err := CreateWriteMarkerMutex(a) if err != nil { return fmt.Errorf("directory creation failed. Err: %s", err.Error()) } @@ -187,7 +186,7 @@ func (req *DirRequest) createDirInBlobber(blobber *blockchain.StorageNode, pos u } formWriter.Close() - httpreq, err := zboxutil.NewCreateDirRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body) + httpreq, err := zboxutil.NewCreateDirRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body, req.allocationObj.Owner) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating dir request", err) return err, false @@ -237,7 +236,7 @@ func (req *DirRequest) createDirInBlobber(blobber *blockchain.StorageNode, pos u return } - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { l.Logger.Error(err) return @@ -289,6 +288,7 @@ type DirOperation struct { func (dirOp *DirOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { refs := make([]fileref.RefEntity, len(allocObj.Blobbers)) dR := &DirRequest{ + allocationObj: allocObj, allocationID: allocObj.ID, allocationTx: allocObj.Tx, connectionID: connectionID, diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index c0033aa2a..fe4242628 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -9,7 +9,6 @@ import ( "fmt" "hash" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -20,10 +19,10 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/encryption" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -67,6 +66,7 @@ func WithFileCallback(cb func()) DownloadRequestOption { } type DownloadRequest struct { + ClientId string allocationID string allocationTx string sig string @@ -823,8 +823,8 @@ func (req *DownloadRequest) attemptSubmitReadMarker(blobber *blockchain.StorageN lockBlobberReadCtr(req.allocationID, blobber.ID) defer unlockBlobberReadCtr(req.allocationID, blobber.ID) rm := &marker.ReadMarker{ - ClientID: client.GetClientID(), - ClientPublicKey: client.GetClientPublicKey(), + ClientID: client.Id(req.ClientId), + ClientPublicKey: client.PublicKey(), BlobberID: blobber.ID, AllocationID: req.allocationID, OwnerID: req.allocOwnerID, @@ -841,7 +841,7 @@ func (req *DownloadRequest) attemptSubmitReadMarker(blobber *blockchain.StorageN if err != nil { return fmt.Errorf("error marshaling read marker: %w", err) } - httpreq, err := zboxutil.NewRedeemRequest(blobber.Baseurl, req.allocationID, req.allocationTx) + httpreq, err := zboxutil.NewRedeemRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.allocOwnerID) if err != nil { return fmt.Errorf("error creating download request: %w", err) } @@ -890,7 +890,7 @@ func (req *DownloadRequest) attemptSubmitReadMarker(blobber *blockchain.StorageN } func (req *DownloadRequest) handleReadMarkerError(resp *http.Response, blobber *blockchain.StorageNode, rm *marker.ReadMarker) error { - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { return err } @@ -963,9 +963,9 @@ func (req *DownloadRequest) initEC() error { // initEncryption will initialize encScheme with client's keys func (req *DownloadRequest) initEncryption() (err error) { req.encScheme = encryption.NewEncryptionScheme() - mnemonic := client.GetClient().Mnemonic + mnemonic := client.Mnemonic() if mnemonic != "" { - _, err = req.encScheme.Initialize(client.GetClient().Mnemonic) + _, err = req.encScheme.Initialize(client.Mnemonic()) if err != nil { return err } @@ -1113,6 +1113,7 @@ func GetFileRefFromBlobber(allocationID, blobberId, remotePath string) (fRef *fi func (req *DownloadRequest) getFileRef() (fRef *fileref.FileRef, err error) { listReq := &ListRequest{ + ClientId: req.ClientId, remotefilepath: req.remotefilepath, remotefilepathhash: req.remotefilepathhash, allocationID: req.allocationID, diff --git a/zboxcore/sdk/filemetaworker.go b/zboxcore/sdk/filemetaworker.go index 3ff148ff1..f2859a537 100644 --- a/zboxcore/sdk/filemetaworker.go +++ b/zboxcore/sdk/filemetaworker.go @@ -76,7 +76,7 @@ func (req *ListRequest) getFileMetaInfoFromBlobber(blobber *blockchain.StorageNo } formWriter.Close() - httpreq, err := zboxutil.NewFileMetaRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body) + httpreq, err := zboxutil.NewFileMetaRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body, req.ClientId) if err != nil { l.Logger.Error("File meta info request error: ", err.Error()) return @@ -141,7 +141,7 @@ func (req *ListRequest) getFileMetaByNameInfoFromBlobber(blobber *blockchain.Sto } } formWriter.Close() - httpreq, err := zboxutil.NewFileMetaRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body) + httpreq, err := zboxutil.NewFileMetaRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body, req.ClientId) if err != nil { l.Logger.Error("File meta info request error: ", err.Error()) return diff --git a/zboxcore/sdk/filemetaworker_test.go b/zboxcore/sdk/filemetaworker_test.go index 4a03106f8..02c168c7f 100644 --- a/zboxcore/sdk/filemetaworker_test.go +++ b/zboxcore/sdk/filemetaworker_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -17,9 +16,9 @@ import ( "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/marker" "github.com/0chain/gosdk_common/zboxcore/mocks" @@ -41,11 +40,10 @@ func TestListRequest_getFileMetaInfoFromBlobber(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { fileRefToRetrieve fileref.FileRef @@ -70,7 +68,7 @@ func TestListRequest_getFileMetaInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, "Test_Http_Error") })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), StatusCode: p.respStatusCode, }, errors.New("", mockErrorMessage)) }, @@ -86,7 +84,7 @@ func TestListRequest_getFileMetaInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, "Test_Badly_Formatted") })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), StatusCode: p.respStatusCode, }, nil) }, @@ -130,7 +128,7 @@ func TestListRequest_getFileMetaInfoFromBlobber(t *testing.T) { } expected, ok := p.requestFields[part.FormName()] require.True(t, ok) - actual, err := ioutil.ReadAll(part) + actual, err := io.ReadAll(part) require.NoError(t, err) require.EqualValues(t, expected, string(actual)) } @@ -147,7 +145,7 @@ func TestListRequest_getFileMetaInfoFromBlobber(t *testing.T) { Body: func(p parameters) io.ReadCloser { jsonFR, err := json.Marshal(p.fileRefToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(p), }, nil) }, @@ -162,6 +160,7 @@ func TestListRequest_getFileMetaInfoFromBlobber(t *testing.T) { Baseurl: tt.name, } req := &ListRequest{ + ClientId: mockClientId, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, ctx: context.TODO(), @@ -203,11 +202,10 @@ func TestListRequest_getFileConsensusFromBlobbers(t *testing.T) { const mockClientId = "mock client id" const mockClientKey = "mock client key" - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) setupHttpResponses := func(t *testing.T, name string, numBlobbers, numCorrect int) { require.True(t, numBlobbers >= numCorrect) @@ -230,7 +228,7 @@ func TestListRequest_getFileConsensusFromBlobbers(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(frName, hash), }, nil) } @@ -273,6 +271,7 @@ func TestListRequest_getFileConsensusFromBlobbers(t *testing.T) { t.Run(tt.name, func(t *testing.T) { tt.setup(t, tt.name, tt.numBlobbers, tt.numCorrect) req := &ListRequest{ + ClientId: mockClientId, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, ctx: context.TODO(), diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index d0f1be1cd..b8b7a195a 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -5,7 +5,7 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" + "io" "math" "math/rand" "net/http" @@ -30,6 +30,7 @@ type ObjectTreeResult struct { const INVALID_PATH = "invalid_path" type ObjectTreeRequest struct { + ClientId string allocationID string allocationTx string sig string @@ -239,6 +240,7 @@ func (o *ObjectTreeRequest) getFileRefs(bUrl string, respChan chan *oTreeRespons o.refType, o.level, o.pageLimit, + o.ClientId, ) if err != nil { oTR.err = err @@ -252,7 +254,7 @@ func (o *ObjectTreeRequest) getFileRefs(bUrl string, respChan chan *oTreeRespons return err } defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { l.Logger.Error(err) return err @@ -332,6 +334,7 @@ type SimilarField struct { type RecentlyAddedRefRequest struct { ctx context.Context + ClientId string allocationID string allocationTx string sig string @@ -411,7 +414,7 @@ func (r *RecentlyAddedRefRequest) GetRecentlyAddedRefs() (*RecentlyAddedRefResul func (r *RecentlyAddedRefRequest) getRecentlyAddedRefs(resp *RecentlyAddedRefResponse, bUrl string) { defer r.wg.Done() - req, err := zboxutil.NewRecentlyAddedRefsRequest(bUrl, r.allocationID, r.allocationTx, r.sig, r.fromDate, r.offset, r.pageLimit) + req, err := zboxutil.NewRecentlyAddedRefsRequest(bUrl, r.allocationID, r.allocationTx, r.sig, r.fromDate, r.offset, r.pageLimit, r.ClientId) if err != nil { resp.err = err return @@ -425,7 +428,7 @@ func (r *RecentlyAddedRefRequest) getRecentlyAddedRefs(resp *RecentlyAddedRefRes return err } defer hResp.Body.Close() - body, err := ioutil.ReadAll(hResp.Body) + body, err := io.ReadAll(hResp.Body) if err != nil { l.Logger.Error(err) return err diff --git a/zboxcore/sdk/filestatsworker.go b/zboxcore/sdk/filestatsworker.go index b3659e95d..af2e3d243 100644 --- a/zboxcore/sdk/filestatsworker.go +++ b/zboxcore/sdk/filestatsworker.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "encoding/json" - "io/ioutil" + "io" "mime/multipart" "net/http" "strings" @@ -84,7 +84,7 @@ func (req *ListRequest) getFileStatsInfoFromBlobber(blobber *blockchain.StorageN return err } defer resp.Body.Close() - resp_body, err := ioutil.ReadAll(resp.Body) + resp_body, err := io.ReadAll(resp.Body) if err != nil { return errors.Wrap(err, "Error: Resp") } diff --git a/zboxcore/sdk/filestatsworker_test.go b/zboxcore/sdk/filestatsworker_test.go index dc7113c5d..abca728cf 100644 --- a/zboxcore/sdk/filestatsworker_test.go +++ b/zboxcore/sdk/filestatsworker_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -14,10 +13,10 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -41,11 +40,10 @@ func TestListRequest_getFileStatsInfoFromBlobber(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - var client = zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { fileStatsHttpResp FileStats @@ -71,7 +69,7 @@ func TestListRequest_getFileStatsInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, "Test_Http_Error") })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), StatusCode: p.respStatusCode, }, errors.New("", mockErrorMessage)) }, @@ -87,7 +85,7 @@ func TestListRequest_getFileStatsInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, "Test_Badly_Formatted") })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), StatusCode: p.respStatusCode, }, nil) }, @@ -122,11 +120,11 @@ func TestListRequest_getFileStatsInfoFromBlobber(t *testing.T) { require.NoError(t, err) expected, ok := p.requestFields[part.FormName()] require.True(t, ok) - actual, err := ioutil.ReadAll(part) + actual, err := io.ReadAll(part) require.NoError(t, err) require.EqualValues(t, expected, string(actual)) - sign, _ := zclient.Sign(encryption.Hash(mockAllocationTxId)) + sign, _ := client.Sign(encryption.Hash(mockAllocationTxId)) return req.URL.Path == "Test_Success"+zboxutil.FILE_STATS_ENDPOINT+mockAllocationTxId && req.Method == "POST" && req.Header.Get("X-App-Client-ID") == mockClientId && @@ -138,7 +136,7 @@ func TestListRequest_getFileStatsInfoFromBlobber(t *testing.T) { Body: func(p parameters) io.ReadCloser { jsonFR, err := json.Marshal(p.fileStatsHttpResp) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(p), }, nil).Once() }, @@ -152,6 +150,7 @@ func TestListRequest_getFileStatsInfoFromBlobber(t *testing.T) { Baseurl: tt.name, } req := &ListRequest{ + ClientId: mockClientId, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, remotefilepath: mockRemoteFilePath, @@ -184,11 +183,10 @@ func TestListRequest_getFileStatsFromBlobbers(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) setupHttpResponses := func(t *testing.T, name string, numBlobbers, numCorrect int) { for i := 0; i < numBlobbers; i++ { @@ -203,7 +201,7 @@ func TestListRequest_getFileStatsFromBlobbers(t *testing.T) { Name: fileStatsName, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(frName), }, nil) } @@ -249,6 +247,7 @@ func TestListRequest_getFileStatsFromBlobbers(t *testing.T) { t.Run(tt.name, func(t *testing.T) { tt.setup(t, tt.name, tt.numBlobbers, tt.numCorrect) req := &ListRequest{ + ClientId: mockClientId, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, ctx: context.TODO(), diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index 9942a9a50..b7dfcfb37 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "math/rand" "net/http" "strings" @@ -23,6 +23,7 @@ import ( const CHUNK_SIZE = 64 * 1024 type ListRequest struct { + ClientId string allocationID string allocationTx string sig string @@ -49,6 +50,7 @@ type listResponse struct { // ListResult a wrapper around the result of directory listing command. // It can represent a file or a directory. type ListResult struct { + ClientId string `json:"client_id"` Name string `json:"name"` Path string `json:"path,omitempty"` Type string `json:"type"` @@ -125,7 +127,7 @@ func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, if req.forRepair { req.listOnly = true } - httpreq, err := zboxutil.NewListRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.remotefilepath, req.remotefilepathhash, string(authTokenBytes), req.listOnly, req.offset, req.pageLimit) + httpreq, err := zboxutil.NewListRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.remotefilepath, req.remotefilepathhash, string(authTokenBytes), req.listOnly, req.offset, req.pageLimit, req.ClientId) if err != nil { l.Logger.Error("List info request error: ", err.Error()) return @@ -139,7 +141,7 @@ func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, return err } defer resp.Body.Close() - resp_body, err := ioutil.ReadAll(resp.Body) + resp_body, err := io.ReadAll(resp.Body) if err != nil { return errors.Wrap(err, "Error: Resp") } @@ -226,6 +228,7 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { return nil, err } result := &ListResult{ + ClientId: req.ClientId, deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), } selected := make(map[string]*ListResult) @@ -296,6 +299,7 @@ func (lr *ListResult) populateChildren(children []fileref.RefEntity, childResult var childResult *ListResult if _, ok := childResultMap[actualHash]; !ok { childResult = &ListResult{ + ClientId: lr.ClientId, Name: child.GetName(), Path: child.GetPath(), Type: child.GetType(), diff --git a/zboxcore/sdk/listworker_test.go b/zboxcore/sdk/listworker_test.go index b6c5bf1b0..fbe2bb1ba 100644 --- a/zboxcore/sdk/listworker_test.go +++ b/zboxcore/sdk/listworker_test.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strconv" "strings" @@ -14,9 +13,9 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/marker" "github.com/0chain/gosdk_common/zboxcore/mocks" @@ -40,11 +39,10 @@ func TestListRequest_getListInfoFromBlobber(t *testing.T) { ) var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { listHttpResp listResponse ListResult fileref.ListResult @@ -79,7 +77,7 @@ func TestListRequest_getListInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, name) })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), StatusCode: p.respStatusCode, }, errors.New("", mockErrorMessage)) }, @@ -96,7 +94,7 @@ func TestListRequest_getListInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, name) })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte(mockErrorMessage))), + Body: io.NopCloser(bytes.NewReader([]byte(mockErrorMessage))), StatusCode: p.respStatusCode, }, nil) }, @@ -113,7 +111,7 @@ func TestListRequest_getListInfoFromBlobber(t *testing.T) { mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, name) })).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewReader([]byte("this is not json format"))), + Body: io.NopCloser(bytes.NewReader([]byte("this is not json format"))), StatusCode: p.respStatusCode, }, nil) }, @@ -163,7 +161,7 @@ func TestListRequest_getListInfoFromBlobber(t *testing.T) { Body: func(p parameters) io.ReadCloser { jsonFR, err := json.Marshal(p.ListResult) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(p), }, nil).Once() }, @@ -178,6 +176,7 @@ func TestListRequest_getListInfoFromBlobber(t *testing.T) { Baseurl: tt.name, } req := &ListRequest{ + ClientId: mockClientId, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, ctx: context.TODO(), @@ -214,11 +213,10 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { var mockClient = mocks.HttpClient{} zboxutil.Client = &mockClient - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) setupHttpResponses := func(t *testing.T, name string, numBlobbers int) { for i := 0; i < numBlobbers; i++ { @@ -237,7 +235,7 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { }) fmt.Println("returned", string(jsonFR)) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) } @@ -281,6 +279,7 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { tt.setup(t, tt.name, tt.numBlobbers) } req := &ListRequest{ + ClientId: mockClientId, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, ctx: context.TODO(), @@ -299,6 +298,7 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { } got, _ := req.GetListFromBlobbers() expectedResult := &ListResult{ + ClientId: mockClientId, Type: mockType, Size: 0, deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 03bba421c..5c9e8bdc6 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "mime/multipart" "net/http" "strings" @@ -17,7 +17,6 @@ import ( "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -110,7 +109,7 @@ func (req *MoveRequest) moveBlobberObject( cncl context.CancelFunc ) - httpreq, err = zboxutil.NewMoveRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body) + httpreq, err = zboxutil.NewMoveRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body, req.allocationObj.Owner) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating rename request", err) return @@ -130,7 +129,7 @@ func (req *MoveRequest) moveBlobberObject( if resp.Body != nil { defer resp.Body.Close() } - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { logger.Logger.Error("Error: Resp ", err) return @@ -285,7 +284,7 @@ func (req *MoveRequest) ProcessMove() error { req.Consensus.consensusThresh, req.Consensus.consensus)) } - writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), req.allocationObj) + writeMarkerMutex, err := CreateWriteMarkerMutex(req.allocationObj) if err != nil { return fmt.Errorf("Move failed: %s", err.Error()) } @@ -332,6 +331,7 @@ func (req *MoveRequest) ProcessMove() error { moveChange.Operation = constants.FileOperationMove moveChange.Size = 0 commitReq := &CommitRequest{ + ClientId: req.allocationObj.Owner, allocationID: req.allocationID, allocationTx: req.allocationTx, sig: req.sig, diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index ab77e7e84..5f8158bb4 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "mime/multipart" "net/http" "sync" @@ -15,7 +15,6 @@ import ( "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -96,7 +95,7 @@ func (mo *MultiOperation) createConnectionObj(blobberIdx int) (err error) { formWriter.Close() var httpreq *http.Request - httpreq, err = zboxutil.NewConnectionRequest(blobber.Baseurl, mo.allocationObj.ID, mo.allocationObj.Tx, mo.allocationObj.sig, body) + httpreq, err = zboxutil.NewConnectionRequest(blobber.Baseurl, mo.allocationObj.ID, mo.allocationObj.Tx, mo.allocationObj.sig, body, mo.allocationObj.Owner) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating new connection request", err) return @@ -118,7 +117,7 @@ func (mo *MultiOperation) createConnectionObj(blobberIdx int) (err error) { defer resp.Body.Close() } var respBody []byte - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { logger.Logger.Error("Error: Resp ", err) return @@ -227,7 +226,7 @@ func (mo *MultiOperation) Process() error { // blobber 2 and so on. start := time.Now() - writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), mo.allocationObj) + writeMarkerMutex, err := CreateWriteMarkerMutex(mo.allocationObj) if err != nil { return fmt.Errorf("Operation failed: %s", err.Error()) } @@ -304,6 +303,7 @@ func (mo *MultiOperation) Process() error { for i := mo.operationMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) commitReq := &CommitRequest{ + ClientId: mo.allocationObj.Owner, allocationID: mo.allocationObj.ID, allocationTx: mo.allocationObj.Tx, sig: mo.allocationObj.sig, diff --git a/zboxcore/sdk/networkworker.go b/zboxcore/sdk/networkworker.go deleted file mode 100644 index 6fec75c52..000000000 --- a/zboxcore/sdk/networkworker.go +++ /dev/null @@ -1,131 +0,0 @@ -package sdk - -import ( - "context" - "encoding/json" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "time" - - "github.com/0chain/gosdk_common/core/client" - l "github.com/0chain/gosdk_common/zboxcore/logger" - "go.uber.org/zap" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" -) - -const NETWORK_ENDPOINT = "/network" - -type Network struct { - Miners []string `json:"miners"` - Sharders []string `json:"sharders"` -} - -func UpdateNetworkDetailsWorker(ctx context.Context) { - ticker := time.NewTicker(time.Duration(networkWorkerTimerInHours) * time.Hour) - for { - select { - case <-ctx.Done(): - l.Logger.Info("Network stopped by user") - return - case <-ticker.C: - err := UpdateNetworkDetails() - if err != nil { - l.Logger.Error("Update network detail worker fail", zap.Error(err)) - return - } - l.Logger.Info("Successfully updated network details") - return - } - } -} - -func UpdateNetworkDetails() error { - networkDetails, err := GetNetworkDetails() - if err != nil { - l.Logger.Error("Failed to update network details ", zap.Error(err)) - return err - } - - shouldUpdate := UpdateRequired(networkDetails) - if shouldUpdate { - forceUpdateNetworkDetails(networkDetails) - } - return nil -} - -func InitNetworkDetails() error { - networkDetails, err := GetNetworkDetails() - if err != nil { - l.Logger.Error("Failed to update network details ", zap.Error(err)) - return err - } - forceUpdateNetworkDetails(networkDetails) - return nil -} - -func forceUpdateNetworkDetails(networkDetails *Network) { - sdkInitialized = false - blockchain.SetMiners(networkDetails.Miners) - blockchain.SetSharders(networkDetails.Sharders) - client.InitCache(blockchain.Sharders) - conf.InitChainNetwork(&conf.Network{ - Sharders: networkDetails.Sharders, - Miners: networkDetails.Miners, - }) - sdkInitialized = true -} - -func UpdateRequired(networkDetails *Network) bool { - miners := blockchain.GetMiners() - sharders := blockchain.GetAllSharders() - if len(miners) == 0 || len(sharders) == 0 { - return true - } - - minerSame := reflect.DeepEqual(miners, networkDetails.Miners) - sharderSame := reflect.DeepEqual(sharders, networkDetails.Sharders) - - if minerSame && sharderSame { - return false - } - return true -} - -func GetNetworkDetails() (*Network, error) { - req, ctx, cncl, err := zboxutil.NewHTTPRequest(http.MethodGet, blockchain.GetBlockWorker()+NETWORK_ENDPOINT, nil) - if err != nil { - return nil, errors.New("get_network_details_error", "Unable to create new http request with error "+err.Error()) - } - - var networkResponse Network - err = zboxutil.HttpDo(ctx, cncl, req, func(resp *http.Response, err error) error { - if err != nil { - l.Logger.Error("Get network error : ", err) - return err - } - - defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return errors.Wrap(err, "Error reading response : ") - } - - l.Logger.Debug("Get network result:", string(respBody)) - if resp.StatusCode == http.StatusOK { - err = json.Unmarshal(respBody, &networkResponse) - if err != nil { - return errors.Wrap(err, "Error unmarshaling response :") - } - return nil - } - return errors.New(strconv.Itoa(resp.StatusCode), "Get network details status not OK") - - }) - return &networkResponse, err -} diff --git a/zboxcore/sdk/playlist.go b/zboxcore/sdk/playlist.go index edb8fd9c2..768e68a61 100644 --- a/zboxcore/sdk/playlist.go +++ b/zboxcore/sdk/playlist.go @@ -7,10 +7,10 @@ import ( "net/url" "strings" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -65,11 +65,11 @@ func getPlaylistFromBlobbers(ctx context.Context, alloc *Allocation, query strin opts = append(opts, resty.WithRetry(resty.DefaultRetry)) opts = append(opts, resty.WithRequestInterceptor(func(req *http.Request) error { - req.Header.Set("X-App-Client-ID", client.GetClientID()) - req.Header.Set("X-App-Client-Key", client.GetClientPublicKey()) + req.Header.Set("X-App-Client-ID", client.Id()) + req.Header.Set("X-App-Client-Key", client.PublicKey()) hash := encryption.Hash(alloc.ID) - sign, err := sys.Sign(hash, client.GetClient().SignatureScheme, client.GetClientSysKeys()) + sign, err := sys.Sign(hash, client.SignatureScheme(), client.GetClientSysKeys()) if err != nil { return err } @@ -146,11 +146,11 @@ func getPlaylistFileFromBlobbers(ctx context.Context, alloc *Allocation, query s opts = append(opts, resty.WithRetry(resty.DefaultRetry)) opts = append(opts, resty.WithRequestInterceptor(func(req *http.Request) error { - req.Header.Set("X-App-Client-ID", client.GetClientID()) - req.Header.Set("X-App-Client-Key", client.GetClientPublicKey()) + req.Header.Set("X-App-Client-ID", client.Id()) + req.Header.Set("X-App-Client-Key", client.PublicKey()) hash := encryption.Hash(alloc.ID) - sign, err := sys.Sign(hash, client.GetClient().SignatureScheme, client.GetClientSysKeys()) + sign, err := sys.Sign(hash, client.SignatureScheme(), client.GetClientSysKeys()) if err != nil { return err } diff --git a/zboxcore/sdk/reader.go b/zboxcore/sdk/reader.go index 943d6df97..c68d40bc7 100644 --- a/zboxcore/sdk/reader.go +++ b/zboxcore/sdk/reader.go @@ -168,6 +168,7 @@ func GetDStorageFileReader(alloc *Allocation, ref *ORef, sdo *StreamDownloadOpti sd := &StreamDownload{ DownloadRequest: &DownloadRequest{ + ClientId: alloc.Owner, allocationID: alloc.ID, allocationTx: alloc.Tx, allocOwnerID: alloc.Owner, diff --git a/zboxcore/sdk/renameworker.go b/zboxcore/sdk/renameworker.go index cbff56cd4..7254b9132 100644 --- a/zboxcore/sdk/renameworker.go +++ b/zboxcore/sdk/renameworker.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "mime/multipart" "net/http" "path" @@ -18,7 +18,6 @@ import ( "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -47,7 +46,7 @@ type RenameRequest struct { } func (req *RenameRequest) getObjectTreeFromBlobber(blobber *blockchain.StorageNode) (fileref.RefEntity, error) { - return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.sig, req.remotefilepath, blobber) + return getObjectTreeFromBlobber(req.ctx, req.allocationID, req.allocationTx, req.sig, req.remotefilepath, blobber, req.allocationObj.Owner) } func (req *RenameRequest) getFileMetaFromBlobber(pos int) (fileRef *fileref.FileRef, err error) { @@ -110,7 +109,7 @@ func (req *RenameRequest) renameBlobberObject( formWriter.Close() var httpreq *http.Request - httpreq, err = zboxutil.NewRenameRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body) + httpreq, err = zboxutil.NewRenameRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.sig, body, req.allocationObj.Owner) if err != nil { l.Logger.Error(blobber.Baseurl, "Error creating rename request", err) return @@ -130,7 +129,7 @@ func (req *RenameRequest) renameBlobberObject( defer resp.Body.Close() } var respBody []byte - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { logger.Logger.Error("Error: Resp ", err) return @@ -286,7 +285,7 @@ func (req *RenameRequest) ProcessRename() error { req.consensus.consensusThresh, req.consensus.getConsensus())) } - writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), req.allocationObj) + writeMarkerMutex, err := CreateWriteMarkerMutex(req.allocationObj) if err != nil { return fmt.Errorf("rename failed: %s", err.Error()) } @@ -336,6 +335,7 @@ func (req *RenameRequest) ProcessRename() error { newChange.Size = 0 commitReq := &CommitRequest{ + ClientId: req.allocationObj.Owner, allocationID: req.allocationID, allocationTx: req.allocationTx, sig: req.sig, diff --git a/zboxcore/sdk/renameworker_test.go b/zboxcore/sdk/renameworker_test.go index 7deb124bf..3956ca3dc 100644 --- a/zboxcore/sdk/renameworker_test.go +++ b/zboxcore/sdk/renameworker_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -15,12 +14,12 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/dev" devMock "github.com/0chain/gosdk_common/dev/mock" "github.com/0chain/gosdk_common/sdks/blobber" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -48,11 +47,10 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { zboxutil.Client = rawClient }() - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) type parameters struct { referencePathToRetrieve fileref.ReferencePath @@ -80,7 +78,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { return strings.HasPrefix(req.URL.Path, testName) })).Return(&http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) }, wantErr: true, @@ -104,7 +102,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { StatusCode: http.StatusOK, Body: func() io.ReadCloser { jsonFR := `{"latest_write_marker":null,"prev_write_marker":null}` - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -118,7 +116,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -129,7 +127,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { req.Header.Get("X-App-Client-Key") == mockClientKey })).Return(&http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) }, wantErr: true, @@ -176,7 +174,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -195,7 +193,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { } expected, ok := p.requestFields[part.FormName()] require.True(t, ok) - actual, err := ioutil.ReadAll(part) + actual, err := io.ReadAll(part) require.NoError(t, err) require.EqualValues(t, expected, string(actual)) } @@ -211,7 +209,7 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { Body: func() io.ReadCloser { jsonFR, err := json.Marshal(p.referencePathToRetrieve) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) }, @@ -227,6 +225,9 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { require := require.New(t) tt.setup(t, tt.name, tt.parameters) req := &RenameRequest{ + allocationObj: &Allocation{ + Owner: mockClientId, + }, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, remotefilepath: mockRemoteFilePath, @@ -279,11 +280,10 @@ func TestRenameRequest_ProcessRename(t *testing.T) { zboxutil.Client = rawClient }() - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ + client.SetWallet(zcncrypto.Wallet{ ClientID: mockClientId, ClientKey: mockClientKey, - } + }) setupHttpResponses := func(t *testing.T, testName string, numBlobbers int, numCorrect int, req *RenameRequest) { @@ -301,7 +301,7 @@ func TestRenameRequest_ProcessRename(t *testing.T) { }, }) require.NoError(t, err) - return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) + return io.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), }, nil) @@ -316,7 +316,7 @@ func TestRenameRequest_ProcessRename(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) if i < numCorrect { @@ -331,7 +331,7 @@ func TestRenameRequest_ProcessRename(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"status":2}`))), + Body: io.NopCloser(bytes.NewReader([]byte(`{"status":2}`))), }, nil) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -345,7 +345,7 @@ func TestRenameRequest_ProcessRename(t *testing.T) { } return http.StatusBadRequest }(), - Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), + Body: io.NopCloser(bytes.NewReader([]byte(""))), }, nil) } @@ -463,6 +463,7 @@ func TestRenameRequest_ProcessRename(t *testing.T) { a := &Allocation{ Tx: "TestRenameRequest_ProcessRename", DataShards: numBlobbers, + Owner: mockClientId, } setupMockAllocation(t, a) @@ -494,6 +495,7 @@ func TestRenameRequest_ProcessRename(t *testing.T) { setupMockRollback(a, &mockClient) req := &RenameRequest{ + allocationObj: a, blobbers: a.Blobbers, allocationID: mockAllocationId, diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index f90de5d33..9d464a6b8 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -18,8 +18,8 @@ import ( "github.com/0chain/common/core/common" thrown "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/marker" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -51,6 +51,7 @@ var ( ) type RollbackBlobber struct { + ClientId string blobber *blockchain.StorageNode commitResult *CommitResult lvm *LatestVersionMarker @@ -62,11 +63,11 @@ type BlobberStatus struct { Status string } -func GetWritemarker(allocID, allocTx, sig, id, baseUrl string) (*LatestVersionMarker, error) { +func GetWritemarker(allocID, allocTx, sig, id, baseUrl string, clientId ...string) (*LatestVersionMarker, error) { var lvm LatestVersionMarker - req, err := zboxutil.NewWritemarkerRequest(baseUrl, allocID, allocTx, sig) + req, err := zboxutil.NewWritemarkerRequest(baseUrl, allocID, allocTx, sig, clientId...) if err != nil { return nil, err } @@ -103,7 +104,7 @@ func GetWritemarker(allocID, allocTx, sig, id, baseUrl string) (*LatestVersionMa return nil, err } if lvm.VersionMarker != nil && lvm.VersionMarker.Version != 0 { - err = lvm.VersionMarker.VerifySignature(client.GetClientPublicKey()) + err = lvm.VersionMarker.VerifySignature(client.PublicKey()) if err != nil { return nil, fmt.Errorf("signature verification failed for latest writemarker: %s", err.Error()) } @@ -120,7 +121,7 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error return nil } vm := &marker.VersionMarker{ - ClientID: client.GetClientID(), + ClientID: client.Id(), BlobberID: rb.lvm.VersionMarker.BlobberID, AllocationID: rb.lvm.VersionMarker.AllocationID, Version: rb.lvm.VersionMarker.Version - 1, @@ -140,11 +141,23 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error return err } connID := zboxutil.NewConnectionId() - formWriter.WriteField("version_marker", string(vmData)) - formWriter.WriteField("connection_id", connID) - formWriter.Close() - req, err := zboxutil.NewRollbackRequest(rb.blobber.Baseurl, vm.AllocationID, tx, body) + err = formWriter.WriteField("write_marker", string(vmData)) + if err != nil { + return err + } + + err = formWriter.WriteField("connection_id", connID) + if err != nil { + return err + } + + err = formWriter.Close() + if err != nil { + return err + } + + req, err := zboxutil.NewRollbackRequest(rb.blobber.Baseurl, vm.AllocationID, tx, body, vm.ClientID) if err != nil { l.Logger.Error("Creating rollback request failed: ", err) return err @@ -228,7 +241,7 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error } - return thrown.New("rolback_error", fmt.Sprint("Rollback failed")) + return thrown.New("rolback_error", "Rollback failed") } // CheckAllocStatus checks the status of the allocation @@ -250,7 +263,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { ID: blobber.ID, Status: "available", } - lvm, err := GetWritemarker(a.ID, a.Tx, a.sig, blobber.ID, blobber.Baseurl) + lvm, err := GetWritemarker(a.ID, a.Tx, a.sig, blobber.ID, blobber.Baseurl, a.Owner) if err != nil { atomic.AddInt32(&errCnt, 1) markerError = err @@ -261,6 +274,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { markerChan <- nil } else { markerChan <- &RollbackBlobber{ + ClientId: a.Owner, blobber: blobber, lvm: lvm, commitResult: &CommitResult{}, @@ -374,7 +388,7 @@ func (a *Allocation) RollbackWithMask(mask zboxutil.Uint128) { go func(blobber *blockchain.StorageNode) { defer wg.Done() - wr, err := GetWritemarker(a.ID, a.Tx, a.sig, blobber.ID, blobber.Baseurl) + wr, err := GetWritemarker(a.ID, a.Tx, a.sig, blobber.ID, blobber.Baseurl, a.Owner) if err != nil { l.Logger.Error("error during getWritemarker", zap.Error(err)) } diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 6f96ed9d3..8d4367e03 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1,29 +1,24 @@ package sdk import ( - "context" "encoding/base64" "encoding/json" "fmt" - "io/ioutil" + "io" "math" "net/http" "strconv" "github.com/0chain/common/core/currency" "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/conf" - "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/core/screstapi" "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" - enc "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/zboxcore/blockchain" - zboxclient "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/encryption" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/marker" @@ -55,8 +50,7 @@ type StatusCallback interface { var ( numBlockDownloads = 100 - sdkInitialized = false - networkWorkerTimerInHours = 1 + networkWorkerTimerInHours = 1 //nolint:unused singleClientMode = false shouldVerifyHash = true ) @@ -101,153 +95,11 @@ 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, - nonce int64, - fee ...uint64) error { - err := zboxclient.PopulateClient(walletJSON, signatureScheme) - if err != nil { - return err - } - - blockchain.SetChainID(chainID) - blockchain.SetBlockWorker(blockWorker) - - err = InitNetworkDetails() - if err != nil { - return err - } - - zboxclient.SetClientNonce(nonce) - if len(fee) > 0 { - client.SetTxnFee(fee[0]) - } - - go UpdateNetworkDetailsWorker(context.Background()) - sdkInitialized = true - return nil -} - -// GetNetwork retrieves the network details -func GetNetwork() *Network { - return &Network{ - Miners: blockchain.GetMiners(), - Sharders: blockchain.GetAllSharders(), - } -} - -// SetMaxTxnQuery set the maximum number of transactions to query -func SetMaxTxnQuery(num int) { - blockchain.SetMaxTxnQuery(num) - - cfg, _ := conf.GetClientConfig() - if cfg != nil { - cfg.MaxTxnQuery = num - } - -} - -// SetQuerySleepTime set the sleep time between queries -func SetQuerySleepTime(time int) { - blockchain.SetQuerySleepTime(time) - - cfg, _ := conf.GetClientConfig() - if cfg != nil { - cfg.QuerySleepTime = time - } - -} - -// 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) - client.InitCache(blockchain.Sharders) -} - -// 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 - } - hash, _, nonce, _, err = storageSmartContractTxn(transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_CREATE_READ_POOL, - }) - return -} - type BackPool struct { ID string `json:"id"` Balance common.Balance `json:"balance"` } -// -// read pool -// - -type ReadPool struct { - Balance common.Balance `json:"balance"` -} - -// 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 - } - - if clientID == "" { - clientID = zboxclient.GetClientID() - } - - var b []byte - b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getReadPoolStat", - map[string]string{"client_id": clientID}) - if err != nil { - return nil, errors.Wrap(err, "error requesting read pool info") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - info = new(ReadPool) - if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "error decoding response:") - } - - return -} - // // stake pool // @@ -301,7 +153,7 @@ type StakePoolInfo struct { // - providerType: provider type // - providerID: provider ID func GetStakePoolInfo(providerType ProviderType, providerID string) (info *StakePoolInfo, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } @@ -334,11 +186,11 @@ type StakePoolUserInfo struct { // - offset: offset // - limit: limit func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUserInfo, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } if clientID == "" { - clientID = zboxclient.GetClientID() + clientID = client.Id() } var b []byte @@ -395,7 +247,7 @@ type ChallengePoolInfo struct { // GetChallengePoolInfo retrieve challenge pool info for given allocation. // - allocID: allocation ID func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } @@ -419,7 +271,7 @@ func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { // GetMptData retrieves mpt key data. func GetMptData(key string) ([]byte, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } @@ -436,38 +288,6 @@ func GetMptData(key string) ([]byte, error) { return b, nil } -// -// storage SC configurations and blobbers -// - -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 - } - - var b []byte - b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/storage-config", nil) - if err != nil { - return nil, errors.Wrap(err, "error requesting storage SC configs:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - conf = new(InputMap) - conf.Fields = make(map[string]interface{}) - if err = json.Unmarshal(b, conf); err != nil { - return nil, errors.Wrap(err, "rror decoding response:") - } - - return -} - // Blobber type represents blobber information. type Blobber struct { // ID of the blobber @@ -645,7 +465,7 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe // - 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 { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } @@ -679,7 +499,7 @@ func GetBlobbers(active, stakable bool) (bs []*Blobber, err error) { // GetBlobber retrieve blobber by id. // - blobberID: the id of blobber func GetBlobber(blobberID string) (blob *Blobber, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } var b []byte @@ -703,7 +523,7 @@ func GetBlobber(blobberID string) (blob *Blobber, err error) { // GetValidator retrieve validator instance by id. // - validatorID: the id of validator func GetValidator(validatorID string) (validator *Validator, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } var b []byte @@ -727,7 +547,7 @@ func GetValidator(validatorID string) (validator *Validator, err error) { // GetValidators returns list of validators. // - stakable: if true then only stakable validators are returned func GetValidators(stakable bool) (validators []*Validator, err error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } var b []byte @@ -751,11 +571,11 @@ func GetValidators(stakable bool) (validators []*Validator, err error) { // GetClientEncryptedPublicKey - get the client's public key func GetClientEncryptedPublicKey() (string, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", sdkNotInitialized } encScheme := encryption.NewEncryptionScheme() - _, err := encScheme.Initialize(client.GetClient().Mnemonic) + _, err := encScheme.Initialize(client.Wallet().Mnemonic) if err != nil { return "", err } @@ -768,7 +588,7 @@ func GetClientEncryptedPublicKey() (string, error) { // // returns the allocation instance and error if any func GetAllocationFromAuthTicket(authTicket string) (*Allocation, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } sEnc, err := base64.StdEncoding.DecodeString(authTicket) @@ -789,7 +609,7 @@ func GetAllocationFromAuthTicket(authTicket string) (*Allocation, error) { // // returns the allocation instance and error if any func GetAllocation(allocationID string) (*Allocation, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } params := make(map[string]string) @@ -803,17 +623,7 @@ func GetAllocation(allocationID string) (*Allocation, error) { if err != nil { return nil, errors.New("allocation_decode_error", "Error decoding the allocation: "+err.Error()+" "+string(allocationBytes)) } - hashdata := allocationObj.Tx - sig, ok := zboxutil.SignCache.Get(hashdata) - if !ok { - sig, err = client.Sign(enc.Hash(hashdata)) - zboxutil.SignCache.Add(hashdata, sig) - if err != nil { - return nil, err - } - } - allocationObj.sig = sig allocationObj.numBlockDownloads = numBlockDownloads allocationObj.InitAllocation() return allocationObj, nil @@ -871,7 +681,7 @@ func SetNumBlockDownloads(num int) { // // returns the list of allocations and error if any func GetAllocations() ([]*Allocation, error) { - return GetAllocationsForClient(zboxclient.GetClientID()) + return GetAllocationsForClient(client.Id()) } func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, error) { @@ -897,7 +707,7 @@ func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, // // returns the list of allocations and error if any func GetAllocationsForClient(clientID string) ([]*Allocation, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return nil, sdkNotInitialized } limit, offset := 20, 0 @@ -968,8 +778,8 @@ type CreateAllocationOptions struct { func CreateAllocationWith(options CreateAllocationOptions) ( string, int64, *transaction.Transaction, error) { - return CreateAllocationForOwner(zboxclient.GetClientID(), - zboxclient.GetClientPublicKey(), options.DataShards, options.ParityShards, + return CreateAllocationForOwner(client.Id(), + client.PublicKey(), options.DataShards, options.ParityShards, options.Size, options.ReadPrice, options.WritePrice, options.Lock, options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams) } @@ -1143,7 +953,7 @@ func GetFreeAllocationBlobbers(request map[string]interface{}) ([]string, error) // // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1169,7 +979,7 @@ func AddFreeStorageAssigner(name, publicKey string, individualLimit, totalLimit // // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } var sn = transaction.SmartContractTxnData{ @@ -1186,7 +996,7 @@ func FinalizeAllocation(allocID string) (hash string, nonce int64, err error) { // // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } var sn = transaction.SmartContractTxnData{ @@ -1212,7 +1022,7 @@ const ( // - 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1238,7 +1048,7 @@ func KillProvider(providerId string, providerType ProviderType) (string, int64, // - 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1265,7 +1075,7 @@ func ShutdownProvider(providerType ProviderType, providerID string) (string, int // - 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1293,7 +1103,7 @@ func CollectRewards(providerId string, providerType ProviderType) (string, int64 return "", 0, fmt.Errorf("collect rewards provider type %v not implimented", providerType) } - hash, _, n, _, err := smartContractTxn(scAddress, sn) + hash, _, n, _, err := transaction.SmartContractTxn(scAddress, sn, true) return hash, n, err } @@ -1305,7 +1115,7 @@ func CollectRewards(providerId string, providerType ProviderType) (string, int64 // // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1338,7 +1148,7 @@ func TransferAllocation(allocationId, newOwner, newOwnerPublicKey string) (strin // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } var sn = transaction.SmartContractTxnData{ @@ -1352,7 +1162,7 @@ func UpdateBlobberSettings(blob *UpdateBlobber) (resp string, nonce int64, err e // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1367,7 +1177,7 @@ func UpdateValidatorSettings(v *UpdateValidator) (resp string, nonce int64, err // 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 { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1380,7 +1190,7 @@ func ResetBlobberStats(rbs *ResetBlobberStatsDto) (string, int64, error) { } func ResetAllocationStats(allocationId string) (string, int64, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized } @@ -1393,7 +1203,7 @@ func ResetAllocationStats(allocationId string) (string, int64, error) { } func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { - if !sdkInitialized { + if !client.IsSDKInitialized() { return "", sdkNotInitialized } var fabricConfig struct { @@ -1441,7 +1251,7 @@ func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { return err } defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { return errors.Wrap(err, "Error reading response :") } @@ -1500,7 +1310,7 @@ func GetUpdateAllocationMinLock( addBlobberId, removeBlobberId string) (int64, error) { updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = zboxclient.GetClientID() + updateAllocationRequest["owner_id"] = client.Id() updateAllocationRequest["owner_public_key"] = "" updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size @@ -1576,3 +1386,22 @@ func updateMaskBit(mask uint16, index uint8, value bool) uint16 { return mask & ^uint16(1< http.StatusBadRequest { blockchain.Sharders.Fail(sharder) From 7775b2fa57063b324ccc71bc7e2e04738855a683 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 21 Jan 2025 21:22:52 +0530 Subject: [PATCH 083/107] updated changes --- go.mod | 2 +- go.sum | 2 + winsdk/sdk.go | 1 + zboxcore/sdk/blobber_operations.go | 2 +- zboxcore/sdk/blobber_operations_mobile.go | 402 ---------------------- zboxcore/sdk/sdk.go | 39 ++- 6 files changed, 43 insertions(+), 405 deletions(-) delete mode 100644 zboxcore/sdk/blobber_operations_mobile.go diff --git a/go.mod b/go.mod index ddbceb063..bd5b95fb4 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631 + github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 442107551..53077de04 100644 --- a/go.sum +++ b/go.sum @@ -46,6 +46,8 @@ github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631 h1:UGvlsDCcYL8G+GNweLzmWKPcpLG7F1VKQwORugtbTNw= github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e h1:TskvG+KrEWp4obrELJk1QRX3tjnsr1mlBapeb1fV2cU= +github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 8a79398cc..db20bfe73 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -161,6 +161,7 @@ func InitWallet(clientJson *C.char) *C.char { l.Logger.Error(err) return WithJSON(false, err) } + client.SetWallet(false, w) l.Logger.Info("InitWallet success") zboxApiClient.SetWallet(client.Wallet().ClientID, client.Wallet().Keys[0].PrivateKey, client.Wallet().ClientKey) diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 2c28979f9..b567b5c34 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -33,7 +33,7 @@ func CreateAllocationForOwner( owner, ownerpublickey string, datashards, parityshards int, size int64, readPrice, writePrice PriceRange, - lock uint64, preferredBlobberIds, blobberAuthTickets []string, thirdPartyExtendable, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, + lock uint64, preferredBlobberIds, blobberAuthTickets []string, thirdPartyExtendable, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, authRoundExpiry int64, ) (hash string, nonce int64, txn *transaction.Transaction, err error) { if lock > math.MaxInt64 { diff --git a/zboxcore/sdk/blobber_operations_mobile.go b/zboxcore/sdk/blobber_operations_mobile.go deleted file mode 100644 index e2d22fd62..000000000 --- a/zboxcore/sdk/blobber_operations_mobile.go +++ /dev/null @@ -1,402 +0,0 @@ -//go:build mobile -// +build mobile - -package sdk - -import ( - "encoding/json" - "math" - "strconv" - "strings" - - "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/zboxcore/client" -) - -// 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, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, -) (hash string, nonce int64, txn *transaction.Transaction, err error) { - - if lock > math.MaxInt64 { - return "", 0, nil, errors.New("invalid_lock", "int64 overflow on lock value") - } - - if datashards < 1 || parityshards < 1 { - return "", 0, nil, errors.New("allocation_validation_failed", "atleast 1 data and 1 parity shards are required") - } - - allocationRequest, err := getNewAllocationBlobbers( - datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds, blobberAuthTickets, force) - if err != nil { - return "", 0, nil, errors.New("failed_get_allocation_blobbers", "failed to get blobbers for allocation: "+err.Error()) - } - - if !sdkInitialized { - return "", 0, nil, sdkNotInitialized - } - - allocationRequest["owner_id"] = owner - 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, - InputArgs: allocationRequest, - } - hash, _, nonce, txn, err = storageSmartContractTxnValue(sn, strconv.FormatUint(lock, 10)) - return -} - -// 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 string) (string, int64, error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - recipientPublicKey := client.GetClientPublicKey() - - var input = map[string]interface{}{ - "recipient_public_key": recipientPublicKey, - "marker": marker, - } - - blobbers, err := GetFreeAllocationBlobbers(input) - if err != nil { - return "", 0, err - } - - input["blobbers"] = blobbers - - var sn = transaction.SmartContractTxnData{ - Name: transaction.NEW_FREE_ALLOCATION, - InputArgs: input, - } - hash, _, n, _, err := storageSmartContractTxnValue(sn, value) - 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, - allocationID string, - lock uint64, - addBlobberId, addBlobberAuthTicket, removeBlobberId string, - setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, -) (hash string, nonce int64, err error) { - - if lock > math.MaxInt64 { - return "", 0, errors.New("invalid_lock", "int64 overflow on lock value") - } - - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - alloc, err := GetAllocation(allocationID) - if err != nil { - return "", 0, allocationNotFound - } - - updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = client.GetClientID() - updateAllocationRequest["owner_public_key"] = "" - updateAllocationRequest["id"] = allocationID - updateAllocationRequest["size"] = size - updateAllocationRequest["extend"] = extend - updateAllocationRequest["add_blobber_id"] = addBlobberId - updateAllocationRequest["add_blobber_auth_ticket"] = addBlobberAuthTicket - updateAllocationRequest["remove_blobber_id"] = removeBlobberId - updateAllocationRequest["set_third_party_extendable"] = setThirdPartyExtendable - updateAllocationRequest["file_options_changed"], updateAllocationRequest["file_options"] = calculateAllocationFileOptions(alloc.FileOptions, fileOptionsParams) - - sn := transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_UPDATE_ALLOCATION, - InputArgs: updateAllocationRequest, - } - hash, _, nonce, _, err = storageSmartContractTxnValue(sn, strconv.FormatUint(lock, 10)) - return -} - -// 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 string) (hash string, nonce int64, err error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - if providerType == 0 { - return "", 0, errors.New("stake_pool_lock", "provider is required") - } - - if providerID == "" { - return "", 0, errors.New("stake_pool_lock", "provider_id is required") - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerID, - } - - var sn = transaction.SmartContractTxnData{ - InputArgs: &spr, - } - - var scAddress string - switch providerType { - case ProviderBlobber, ProviderValidator: - scAddress = STORAGE_SCADDRESS - sn.Name = transaction.STORAGESC_STAKE_POOL_LOCK - case ProviderMiner, ProviderSharder: - scAddress = MINERSC_SCADDRESS - sn.Name = transaction.MINERSC_LOCK - case ProviderAuthorizer: - scAddress = ZCNSC_SCADDRESS - sn.Name = transaction.ZCNSC_LOCK - default: - return "", 0, errors.Newf("stake_pool_lock", "unsupported provider type: %v", providerType) - } - - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(scAddress, sn, value, fee) - return -} - -// StakePoolUnlock unlocks a stake pool tokens. If tokens can't be unlocked due -// to opened offers, then it returns time where the tokens can be unlocked, -// marking the pool as 'want to unlock' to avoid its usage in offers in the -// 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 string) (unstake int64, nonce int64, err error) { - if !sdkInitialized { - return 0, 0, sdkNotInitialized - } - - if providerType == 0 { - return 0, 0, errors.New("stake_pool_lock", "provider is required") - } - - if providerID == "" { - return 0, 0, errors.New("stake_pool_lock", "provider_id is required") - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerID, - } - - var sn = transaction.SmartContractTxnData{ - InputArgs: &spr, - } - - var scAddress string - switch providerType { - case ProviderBlobber, ProviderValidator: - scAddress = STORAGE_SCADDRESS - sn.Name = transaction.STORAGESC_STAKE_POOL_UNLOCK - case ProviderMiner, ProviderSharder: - scAddress = MINERSC_SCADDRESS - sn.Name = transaction.MINERSC_UNLOCK - case ProviderAuthorizer: - scAddress = ZCNSC_SCADDRESS - sn.Name = transaction.ZCNSC_UNLOCK - default: - return 0, 0, errors.Newf("stake_pool_unlock", "unsupported provider type: %v", providerType) - } - - var out string - if _, out, nonce, _, err = smartContractTxnValueFeeWithRetry(scAddress, sn, "0", fee); err != nil { - return // an error - } - - var spuu stakePoolLock - if err = json.Unmarshal([]byte(out), &spuu); err != nil { - return - } - - return spuu.Amount, nonce, nil -} - -// 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 string) (hash string, nonce int64, err error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_READ_POOL_LOCK, - InputArgs: nil, - } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, tokens, fee) - return -} - -// ReadPoolUnlock unlocks tokens in expired read pool -// - fee: transaction fee -func ReadPoolUnlock(fee string) (hash string, nonce int64, err error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_READ_POOL_UNLOCK, - InputArgs: nil, - } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, "0", fee) - return -} - -// -// write pool -// - -// 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 string) (hash string, nonce int64, err error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - type lockRequest struct { - AllocationID string `json:"allocation_id"` - } - - var req lockRequest - req.AllocationID = allocID - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_WRITE_POOL_LOCK, - InputArgs: &req, - } - - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, tokens, fee) - return -} - -// WritePoolUnlock unlocks ALL tokens of a write pool. Needs to be cancelled first. -// - allocID: allocation ID -// - fee: transaction fee -func WritePoolUnlock(allocID string, fee string) (hash string, nonce int64, err error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - type unlockRequest struct { - AllocationID string `json:"allocation_id"` - } - - var req unlockRequest - req.AllocationID = allocID - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_WRITE_POOL_UNLOCK, - InputArgs: &req, - } - hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, "0", fee) - return -} - -func smartContractTxn(scAddress string, sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - return smartContractTxnValue(scAddress, sn, "0") -} - -func StorageSmartContractTxn(sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return storageSmartContractTxnValue(sn, "0") -} - -func storageSmartContractTxn(sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return storageSmartContractTxnValue(sn, "0") -} - -func smartContractTxnValue(scAddress string, sn transaction.SmartContractTxnData, value string) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return smartContractTxnValueFeeWithRetry(scAddress, sn, value, strconv.FormatUint(client.TxnFee(), 10)) -} - -func storageSmartContractTxnValue(sn transaction.SmartContractTxnData, value string) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - // Fee is set during sdk initialization. - return smartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, value, strconv.FormatUint(client.TxnFee(), 10)) -} - -func smartContractTxnValueFeeWithRetry(scAddress string, sn transaction.SmartContractTxnData, - value, fee string) (hash, out string, nonce int64, t *transaction.Transaction, err error) { - hash, out, nonce, t, err = smartContractTxnValueFee(scAddress, sn, value, fee) - - if err != nil && strings.Contains(err.Error(), "invalid transaction nonce") { - return smartContractTxnValueFee(scAddress, sn, value, fee) - } - - return -} - -func smartContractTxnValueFee(scAddress string, sn transaction.SmartContractTxnData, - value, fee string) (hash, out string, nonce int64, t *transaction.Transaction, err error) { - t, err = ExecuteSmartContract(scAddress, sn, value, fee) - if err != nil { - if t != nil { - return "", "", t.TransactionNonce, nil, err - } - - return "", "", 0, nil, err - } - - return t.Hash, t.TransactionOutput, t.TransactionNonce, t, nil -} diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 8d4367e03..795afb802 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -17,6 +17,7 @@ import ( "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/encryption" @@ -95,6 +96,10 @@ func SetLogFile(logFile string, verbose bool) { l.Logger.Info("******* Storage SDK Version: ", version.VERSIONSTR, " *******") } +func GetLogger() *logger.Logger { + return l.Logger +} + type BackPool struct { ID string `json:"id"` Balance common.Balance `json:"balance"` @@ -362,6 +367,8 @@ type UpdateBlobber struct { IsShutdown *bool `json:"is_shutdown,omitempty"` NotAvailable *bool `json:"not_available,omitempty"` IsRestricted *bool `json:"is_restricted,omitempty"` + StorageVersion *int `json:"storage_version,omitempty"` + DelegateWallet *string `json:"delegate_wallet,omitempty"` } // ResetBlobberStatsDto represents blobber stats reset request. @@ -781,7 +788,7 @@ func CreateAllocationWith(options CreateAllocationOptions) ( return CreateAllocationForOwner(client.Id(), client.PublicKey(), options.DataShards, options.ParityShards, options.Size, options.ReadPrice, options.WritePrice, options.Lock, - options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams) + options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams, options.AuthRoundExpiry) } // GetAllocationBlobbers returns a list of blobber ids that can be used for a new allocation. @@ -1189,6 +1196,36 @@ func ResetBlobberStats(rbs *ResetBlobberStatsDto) (string, int64, error) { return hash, n, err } +type StorageNodeIdField struct { + Id string `json:"id"` +} + +func ResetBlobberVersion(snId *StorageNodeIdField) (string, int64, error) { + if !client.IsSDKInitialized() { + return "", 0, sdkNotInitialized + } + + var sn = transaction.SmartContractTxnData{ + Name: transaction.STORAGESC_RESET_BLOBBER_VERSION, + InputArgs: snId, + } + hash, _, n, _, err := storageSmartContractTxn(sn) + return hash, n, err +} + +func InsertKilledProviderID(snId *StorageNodeIdField) (string, int64, error) { + if !client.IsSDKInitialized() { + return "", 0, sdkNotInitialized + } + + var sn = transaction.SmartContractTxnData{ + Name: transaction.STORAGESC_INSERT_KILLED_PROVIDER_ID, + InputArgs: snId, + } + hash, _, n, _, err := storageSmartContractTxn(sn) + return hash, n, err +} + func ResetAllocationStats(allocationId string) (string, int64, error) { if !client.IsSDKInitialized() { return "", 0, sdkNotInitialized From acb0596beb40901dc67d09c8e5515b34ff4674d7 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Wed, 22 Jan 2025 16:33:53 +0530 Subject: [PATCH 084/107] windows build fix --- winsdk/sdk.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/winsdk/sdk.go b/winsdk/sdk.go index db20bfe73..9b40be203 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -161,7 +161,7 @@ func InitWallet(clientJson *C.char) *C.char { l.Logger.Error(err) return WithJSON(false, err) } - client.SetWallet(false, w) + client.SetWallet(w) l.Logger.Info("InitWallet success") zboxApiClient.SetWallet(client.Wallet().ClientID, client.Wallet().Keys[0].PrivateKey, client.Wallet().ClientKey) From 8bd0f079baf6469ba55b3a8148cbeec259b4b2fa Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Wed, 22 Jan 2025 17:04:40 +0530 Subject: [PATCH 085/107] revert changes --- zboxcore/sdk/allocation_file_delete_test.go | 2 +- zboxcore/sdk/allocation_file_test.go | 2 +- zboxcore/sdk/allocation_test.go | 2 +- zboxcore/sdk/copyworker_test.go | 2 +- zboxcore/sdk/deleteworker_test.go | 2 +- zboxcore/sdk/filemetaworker_test.go | 2 +- zboxcore/sdk/filestatsworker_test.go | 2 +- zboxcore/sdk/listworker_test.go | 2 +- zboxcore/sdk/renameworker_test.go | 2 +- zboxcore/sdk/writemarker_mutex_test.go | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/zboxcore/sdk/allocation_file_delete_test.go b/zboxcore/sdk/allocation_file_delete_test.go index 122cf266a..344f9ffd0 100644 --- a/zboxcore/sdk/allocation_file_delete_test.go +++ b/zboxcore/sdk/allocation_file_delete_test.go @@ -8,12 +8,12 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/require" ) diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index 691a3288f..ab3f40e5f 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -17,9 +17,9 @@ import ( "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/hitenjain14/fasthttp" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index b7f6cfe0e..0b991fdf2 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -26,10 +26,10 @@ import ( "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/sys" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/copyworker_test.go b/zboxcore/sdk/copyworker_test.go index 243536fc0..b5b22904e 100644 --- a/zboxcore/sdk/copyworker_test.go +++ b/zboxcore/sdk/copyworker_test.go @@ -14,6 +14,7 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/dev" @@ -21,7 +22,6 @@ import ( "github.com/0chain/gosdk_common/sdks/blobber" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/deleteworker_test.go b/zboxcore/sdk/deleteworker_test.go index c6d861c9c..970e3808d 100644 --- a/zboxcore/sdk/deleteworker_test.go +++ b/zboxcore/sdk/deleteworker_test.go @@ -13,12 +13,12 @@ import ( "time" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/filemetaworker_test.go b/zboxcore/sdk/filemetaworker_test.go index 02c168c7f..d472d6220 100644 --- a/zboxcore/sdk/filemetaworker_test.go +++ b/zboxcore/sdk/filemetaworker_test.go @@ -16,12 +16,12 @@ import ( "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/marker" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/filestatsworker_test.go b/zboxcore/sdk/filestatsworker_test.go index abca728cf..cb1385f91 100644 --- a/zboxcore/sdk/filestatsworker_test.go +++ b/zboxcore/sdk/filestatsworker_test.go @@ -13,12 +13,12 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/listworker_test.go b/zboxcore/sdk/listworker_test.go index fbe2bb1ba..6a2a7c2a3 100644 --- a/zboxcore/sdk/listworker_test.go +++ b/zboxcore/sdk/listworker_test.go @@ -13,12 +13,12 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/marker" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/renameworker_test.go b/zboxcore/sdk/renameworker_test.go index 3956ca3dc..eb17bbcdb 100644 --- a/zboxcore/sdk/renameworker_test.go +++ b/zboxcore/sdk/renameworker_test.go @@ -14,6 +14,7 @@ import ( "testing" "github.com/0chain/errors" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/dev" @@ -21,7 +22,6 @@ import ( "github.com/0chain/gosdk_common/sdks/blobber" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/fileref" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/zboxcore/sdk/writemarker_mutex_test.go b/zboxcore/sdk/writemarker_mutex_test.go index 9c68444eb..64138815e 100644 --- a/zboxcore/sdk/writemarker_mutex_test.go +++ b/zboxcore/sdk/writemarker_mutex_test.go @@ -11,8 +11,8 @@ import ( "testing" "time" + "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/mocks" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" From 92fabe3af5bf42c070444f2c93e7456564ca581f Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 23 Jan 2025 02:04:36 +0530 Subject: [PATCH 086/107] common sdk update version --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index bd5b95fb4..97fdbb2b3 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e + github.com/0chain/gosdk_common v0.0.0-20250122192236-7180658d2e00 github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 53077de04..d067259d1 100644 --- a/go.sum +++ b/go.sum @@ -44,10 +44,10 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631 h1:UGvlsDCcYL8G+GNweLzmWKPcpLG7F1VKQwORugtbTNw= -github.com/0chain/gosdk_common v0.0.0-20250117135422-7c4f2f249631/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e h1:TskvG+KrEWp4obrELJk1QRX3tjnsr1mlBapeb1fV2cU= github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250122192236-7180658d2e00 h1:wXxNBOnZxE1nG+6oKjdK5S58yckasW0W8UW2h70ZZTc= +github.com/0chain/gosdk_common v0.0.0-20250122192236-7180658d2e00/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= From f83199a33d9c876de4bb1227cd70f8cbf7dc9c00 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 23 Jan 2025 17:31:52 +0530 Subject: [PATCH 087/107] refactor --- zboxcore/zboxutil/doc.go | 2 +- zboxcore/zboxutil/http.go | 311 +++++++++++---------------------- zboxcore/zboxutil/http_test.go | 67 ------- zboxcore/zboxutil/transport.go | 24 --- 4 files changed, 104 insertions(+), 300 deletions(-) delete mode 100644 zboxcore/zboxutil/http_test.go delete mode 100644 zboxcore/zboxutil/transport.go diff --git a/zboxcore/zboxutil/doc.go b/zboxcore/zboxutil/doc.go index d3419ee76..2d256e92e 100644 --- a/zboxcore/zboxutil/doc.go +++ b/zboxcore/zboxutil/doc.go @@ -1,2 +1,2 @@ // Utility functions to support the functionality of the SDK. -package zboxutil \ No newline at end of file +package zboxutil diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 4bd976238..36e337d9a 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "fmt" "io" "net" "net/http" @@ -12,35 +11,17 @@ import ( "os" "path" "strconv" - "sync" "time" "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/conf" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/logger" - "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" lru "github.com/hashicorp/golang-lru/v2" "github.com/hashicorp/golang-lru/v2/simplelru" "github.com/hitenjain14/fasthttp" ) -const SC_REST_API_URL = "v1/screst/" - -const MAX_RETRIES = 5 -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 { Do(req *http.Request) (*http.Response, error) } @@ -166,7 +147,7 @@ var envProxy proxyFromEnv func init() { Client = &http.Client{ - Transport: DefaultTransport, + Transport: http.DefaultTransport, } FastHttpClient = &fasthttp.Client{ @@ -213,20 +194,26 @@ func NewHTTPRequest(method string, url string, data []byte) (*http.Request, cont } func setClientInfo(req *http.Request) { - req.Header.Set("X-App-Client-ID", client.GetClientID()) - req.Header.Set("X-App-Client-Key", client.GetClientPublicKey()) + req.Header.Set("X-App-Client-ID", client.Id()) + req.Header.Set("X-App-Client-Key", client.PublicKey()) } -func setClientInfoWithSign(req *http.Request, sig, allocation, baseURL string) error { +func setClientInfoWithSign(req *http.Request, sig, allocation, baseURL string, clients ...string) error { + var clientID string + if len(clients) > 0 { + clientID = clients[0] + } else { + clientID = client.Id() + } setClientInfo(req) req.Header.Set(CLIENT_SIGNATURE_HEADER, sig) hashData := allocation + baseURL - sig2, ok := SignCache.Get(hashData) + sig2, ok := SignCache.Get(hashData + ":" + clientID) if !ok { var err error - sig2, err = client.Sign(encryption.Hash(hashData)) - SignCache.Add(hashData, sig2) + sig2, err = client.Sign(encryption.Hash(hashData), clientID) + SignCache.Add(hashData+":"+clientID, sig2) if err != nil { return err } @@ -235,7 +222,7 @@ func setClientInfoWithSign(req *http.Request, sig, allocation, baseURL string) e return nil } -func NewCommitRequest(baseUrl, allocationID string, allocationTx string, body io.Reader) (*http.Request, error) { +func NewCommitRequest(baseUrl, allocationID string, allocationTx string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, COMMIT_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -252,7 +239,7 @@ func NewCommitRequest(baseUrl, allocationID string, allocationTx string, body io return req, nil } -func NewReferencePathRequest(baseUrl, allocationID string, allocationTx string, sig string, paths []string) (*http.Request, error) { +func NewReferencePathRequest(baseUrl, allocationID string, allocationTx string, sig string, paths []string, clients ...string) (*http.Request, error) { nurl, err := joinUrl(baseUrl, REFERENCE_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -272,7 +259,7 @@ func NewReferencePathRequest(baseUrl, allocationID string, allocationTx string, return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -281,7 +268,35 @@ func NewReferencePathRequest(baseUrl, allocationID string, allocationTx string, return req, nil } -func NewCalculateHashRequest(baseUrl, allocationID string, allocationTx string, paths []string) (*http.Request, error) { +func NewReferencePathRequestV2(baseUrl, allocationID, allocationTx, sig string, paths []string, loadOnly bool, clients ...string) (*http.Request, error) { + nurl, err := joinUrl(baseUrl, REFERENCE_ENDPOINT_V2, allocationTx) + if err != nil { + return nil, err + } + pathBytes, err := json.Marshal(paths) + if err != nil { + return nil, err + } + params := url.Values{} + params.Add("paths", string(pathBytes)) + if loadOnly { + params.Add("load", "true") + } + nurl.RawQuery = params.Encode() // Escape Query Parameters + req, err := http.NewRequest(http.MethodGet, nurl.String(), nil) + if err != nil { + return nil, err + } + + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { + return nil, err + } + + req.Header.Set(ALLOCATION_ID_HEADER, allocationID) + return req, nil +} + +func NewCalculateHashRequest(baseUrl, allocationID string, allocationTx string, paths []string, clients ...string) (*http.Request, error) { nurl, err := joinUrl(baseUrl, CALCULATE_HASH_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -304,7 +319,7 @@ func NewCalculateHashRequest(baseUrl, allocationID string, allocationTx string, return req, nil } -func NewObjectTreeRequest(baseUrl, allocationID string, allocationTx string, sig string, path string) (*http.Request, error) { +func NewObjectTreeRequest(baseUrl, allocationID string, allocationTx string, sig string, path string, clients ...string) (*http.Request, error) { nurl, err := joinUrl(baseUrl, OBJECT_TREE_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -318,7 +333,7 @@ func NewObjectTreeRequest(baseUrl, allocationID string, allocationTx string, sig return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -327,7 +342,7 @@ func NewObjectTreeRequest(baseUrl, allocationID string, allocationTx string, sig return req, nil } -func NewRefsRequest(baseUrl, allocationID, sig, allocationTx, path, pathHash, authToken, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int) (*http.Request, error) { +func NewRefsRequest(baseUrl, allocationID, sig, allocationTx, path, pathHash, authToken, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int, clients ...string) (*http.Request, error) { nUrl, err := joinUrl(baseUrl, REFS_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -351,14 +366,14 @@ func NewRefsRequest(baseUrl, allocationID, sig, allocationTx, path, pathHash, au req.Header.Set(ALLOCATION_ID_HEADER, allocationID) - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } return req, nil } -func NewRecentlyAddedRefsRequest(bUrl, allocID, allocTx, sig string, fromDate, offset int64, pageLimit int) (*http.Request, error) { +func NewRecentlyAddedRefsRequest(bUrl, allocID, allocTx, sig string, fromDate, offset int64, pageLimit int, clients ...string) (*http.Request, error) { nUrl, err := joinUrl(bUrl, RECENT_REFS_ENDPOINT, allocID) if err != nil { return nil, err @@ -377,14 +392,14 @@ func NewRecentlyAddedRefsRequest(bUrl, allocID, allocTx, sig string, fromDate, o req.Header.Set(ALLOCATION_ID_HEADER, allocID) - if err = setClientInfoWithSign(req, sig, allocTx, bUrl); err != nil { + if err = setClientInfoWithSign(req, sig, allocTx, bUrl, clients...); err != nil { return nil, err } return req, nil } -func NewAllocationRequest(baseUrl, allocationID, allocationTx string) (*http.Request, error) { +func NewAllocationRequest(baseUrl, allocationID, allocationTx string, clients ...string) (*http.Request, error) { nurl, err := joinUrl(baseUrl, ALLOCATION_ENDPOINT) if err != nil { return nil, err @@ -402,7 +417,7 @@ func NewAllocationRequest(baseUrl, allocationID, allocationTx string) (*http.Req return req, nil } -func NewCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, COLLABORATOR_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -412,7 +427,7 @@ func NewCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, bod return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -421,7 +436,7 @@ func NewCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, bod return req, nil } -func GetCollaboratorsRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values) (*http.Request, error) { +func GetCollaboratorsRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, COLLABORATOR_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -432,7 +447,7 @@ func GetCollaboratorsRequest(baseUrl, allocationID, allocationTx, sig string, qu return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -441,7 +456,7 @@ func GetCollaboratorsRequest(baseUrl, allocationID, allocationTx, sig string, qu return req, nil } -func DeleteCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values) (*http.Request, error) { +func DeleteCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, COLLABORATOR_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -453,7 +468,7 @@ func DeleteCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -462,7 +477,7 @@ func DeleteCollaboratorRequest(baseUrl, allocationID, allocationTx, sig string, return req, nil } -func NewFileMetaRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewFileMetaRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, FILE_META_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -472,8 +487,7 @@ func NewFileMetaRequest(baseUrl, allocationID, allocationTx, sig string, body io return nil, err } - err = setClientInfoWithSign(req, sig, allocationTx, baseUrl) - if err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -482,7 +496,7 @@ func NewFileMetaRequest(baseUrl, allocationID, allocationTx, sig string, body io return req, nil } -func NewFileStatsRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewFileStatsRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, FILE_STATS_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -492,7 +506,7 @@ func NewFileStatsRequest(baseUrl, allocationID, allocationTx, sig string, body i return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -501,7 +515,7 @@ func NewFileStatsRequest(baseUrl, allocationID, allocationTx, sig string, body i return req, nil } -func NewListRequest(baseUrl, allocationID, allocationTx, path, pathHash, auth_token string, list bool, offset, pageLimit int) (*http.Request, error) { +func NewListRequest(baseUrl, allocationID, allocationTx, path, pathHash, auth_token string, list bool, offset, pageLimit int, clients ...string) (*http.Request, error) { nurl, err := joinUrl(baseUrl, LIST_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -528,7 +542,7 @@ func NewListRequest(baseUrl, allocationID, allocationTx, path, pathHash, auth_to } // NewUploadRequestWithMethod create a http request of upload -func NewUploadRequestWithMethod(baseURL, allocationID, allocationTx, sig string, body io.Reader, method string) (*http.Request, error) { +func NewUploadRequestWithMethod(baseURL, allocationID, allocationTx, sig string, body io.Reader, method string, clients ...string) (*http.Request, error) { u, err := joinUrl(baseURL, UPLOAD_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -543,7 +557,7 @@ func NewUploadRequestWithMethod(baseURL, allocationID, allocationTx, sig string, } // set header: X-App-Client-Signature - if err := setClientInfoWithSign(req, sig, allocationTx, baseURL); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseURL, clients...); err != nil { return nil, err } @@ -553,7 +567,7 @@ func NewUploadRequestWithMethod(baseURL, allocationID, allocationTx, sig string, } func NewWriteMarkerLockRequest( - baseURL, allocationID, allocationTx, sig, connID string) (*http.Request, error) { + baseURL, allocationID, allocationTx, sig, connID string, clients ...string) (*http.Request, error) { u, err := joinUrl(baseURL, WM_LOCK_ENDPOINT, allocationTx) if err != nil { @@ -569,7 +583,7 @@ func NewWriteMarkerLockRequest( return nil, err } - err = setClientInfoWithSign(req, sig, allocationTx, baseURL) + err = setClientInfoWithSign(req, sig, allocationTx, baseURL, clients...) if err != nil { return nil, err } @@ -580,7 +594,7 @@ func NewWriteMarkerLockRequest( } func NewWriteMarkerUnLockRequest( - baseURL, allocationID, allocationTx, sig, connID, requestTime string) (*http.Request, error) { + baseURL, allocationID, allocationTx, sig, connID, requestTime string, clients ...string) (*http.Request, error) { u, err := joinUrl(baseURL, WM_LOCK_ENDPOINT, allocationTx, connID) if err != nil { @@ -592,7 +606,7 @@ func NewWriteMarkerUnLockRequest( return nil, err } - err = setClientInfoWithSign(req, sig, allocationTx, baseURL) + err = setClientInfoWithSign(req, sig, allocationTx, baseURL, clients...) if err != nil { return nil, err } @@ -602,7 +616,7 @@ func NewWriteMarkerUnLockRequest( return req, nil } -func NewFastUploadRequest(baseURL, allocationID string, allocationTx string, body []byte, method string) (*fasthttp.Request, error) { +func NewFastUploadRequest(baseURL, allocationID string, allocationTx string, body []byte, method string, clients ...string) (*fasthttp.Request, error) { u, err := joinUrl(baseURL, UPLOAD_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -615,7 +629,7 @@ func NewFastUploadRequest(baseURL, allocationID string, allocationTx string, bod req.SetBodyRaw(body) // set header: X-App-Client-Signature - if err := setFastClientInfoWithSign(req, allocationTx, baseURL); err != nil { + if err := setFastClientInfoWithSign(req, allocationTx, baseURL, clients...); err != nil { return nil, err } @@ -623,9 +637,9 @@ func NewFastUploadRequest(baseURL, allocationID string, allocationTx string, bod return req, nil } -func setFastClientInfoWithSign(req *fasthttp.Request, allocation, baseURL string) error { - req.Header.Set("X-App-Client-ID", client.GetClientID()) - req.Header.Set("X-App-Client-Key", client.GetClientPublicKey()) +func setFastClientInfoWithSign(req *fasthttp.Request, allocation, baseURL string, clients ...string) error { + req.Header.Set("X-App-Client-ID", client.Id()) + req.Header.Set("X-App-Client-Key", client.PublicKey()) sign, err := client.Sign(encryption.Hash(allocation)) if err != nil { @@ -645,7 +659,7 @@ func setFastClientInfoWithSign(req *fasthttp.Request, allocation, baseURL string return nil } -func NewUploadRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, update bool) (*http.Request, error) { +func NewUploadRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, update bool, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, UPLOAD_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -661,7 +675,7 @@ func NewUploadRequest(baseUrl, allocationID, allocationTx, sig string, body io.R return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -670,7 +684,7 @@ func NewUploadRequest(baseUrl, allocationID, allocationTx, sig string, body io.R return req, nil } -func NewConnectionRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewConnectionRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, CREATE_CONNECTION_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -680,7 +694,7 @@ func NewConnectionRequest(baseUrl, allocationID, allocationTx, sig string, body return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -689,7 +703,7 @@ func NewConnectionRequest(baseUrl, allocationID, allocationTx, sig string, body return req, nil } -func NewRenameRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewRenameRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, RENAME_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -701,7 +715,7 @@ func NewRenameRequest(baseUrl, allocationID, allocationTx, sig string, body io.R return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -710,7 +724,7 @@ func NewRenameRequest(baseUrl, allocationID, allocationTx, sig string, body io.R return req, nil } -func NewCopyRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewCopyRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, COPY_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -721,7 +735,7 @@ func NewCopyRequest(baseUrl, allocationID, allocationTx, sig string, body io.Rea return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -730,7 +744,7 @@ func NewCopyRequest(baseUrl, allocationID, allocationTx, sig string, body io.Rea return req, nil } -func NewMoveRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewMoveRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, MOVE_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -741,7 +755,7 @@ func NewMoveRequest(baseUrl, allocationID, allocationTx, sig string, body io.Rea return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -750,7 +764,7 @@ func NewMoveRequest(baseUrl, allocationID, allocationTx, sig string, body io.Rea return req, nil } -func NewDownloadRequest(baseUrl, allocationID, allocationTx string) (*http.Request, error) { +func NewDownloadRequest(baseUrl, allocationID, allocationTx string, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, DOWNLOAD_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -767,7 +781,7 @@ func NewDownloadRequest(baseUrl, allocationID, allocationTx string) (*http.Reque return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -776,7 +790,7 @@ func NewDownloadRequest(baseUrl, allocationID, allocationTx string) (*http.Reque return req, nil } -func NewFastDownloadRequest(baseUrl, allocationID, allocationTx string) (*fasthttp.Request, error) { +func NewFastDownloadRequest(baseUrl, allocationID, allocationTx string, clients ...string) (*fasthttp.Request, error) { u, err := joinUrl(baseUrl, DOWNLOAD_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -784,16 +798,15 @@ func NewFastDownloadRequest(baseUrl, allocationID, allocationTx string) (*fastht req := fasthttp.AcquireRequest() - if err := setFastClientInfoWithSign(req, allocationTx, baseUrl); err != nil { - return nil, err - } req.SetRequestURI(u.String()) + req.Header.Set("X-App-Client-ID", client.Id()) + req.Header.Set("X-App-Client-Key", client.PublicKey()) req.Header.Set(ALLOCATION_ID_HEADER, allocationID) return req, nil } -func NewRedeemRequest(baseUrl, allocationID, allocationTx string) (*http.Request, error) { +func NewRedeemRequest(baseUrl, allocationID, allocationTx string, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, REDEEM_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -808,7 +821,7 @@ func NewRedeemRequest(baseUrl, allocationID, allocationTx string) (*http.Request return req, nil } -func NewDeleteRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values) (*http.Request, error) { +func NewDeleteRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, UPLOAD_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -820,7 +833,7 @@ func NewDeleteRequest(baseUrl, allocationID, allocationTx, sig string, query *ur return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -829,7 +842,7 @@ func NewDeleteRequest(baseUrl, allocationID, allocationTx, sig string, query *ur return req, nil } -func NewCreateDirRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewCreateDirRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, DIR_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -840,7 +853,7 @@ func NewCreateDirRequest(baseUrl, allocationID, allocationTx, sig string, body i return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -849,7 +862,7 @@ func NewCreateDirRequest(baseUrl, allocationID, allocationTx, sig string, body i return req, nil } -func NewShareRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader) (*http.Request, error) { +func NewShareRequest(baseUrl, allocationID, allocationTx, sig string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, SHARE_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -860,7 +873,7 @@ func NewShareRequest(baseUrl, allocationID, allocationTx, sig string, body io.Re return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -869,7 +882,7 @@ func NewShareRequest(baseUrl, allocationID, allocationTx, sig string, body io.Re return req, nil } -func NewRevokeShareRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values) (*http.Request, error) { +func NewRevokeShareRequest(baseUrl, allocationID, allocationTx, sig string, query *url.Values, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, SHARE_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -880,7 +893,7 @@ func NewRevokeShareRequest(baseUrl, allocationID, allocationTx, sig string, quer return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -889,7 +902,7 @@ func NewRevokeShareRequest(baseUrl, allocationID, allocationTx, sig string, quer return req, nil } -func NewWritemarkerRequest(baseUrl, allocationID, allocationTx, sig string) (*http.Request, error) { +func NewWritemarkerRequest(baseUrl, allocationID, allocationTx, sig string, clients ...string) (*http.Request, error) { nurl, err := joinUrl(baseUrl, LATEST_WRITE_MARKER_ENDPOINT, allocationTx) if err != nil { @@ -901,7 +914,7 @@ func NewWritemarkerRequest(baseUrl, allocationID, allocationTx, sig string) (*ht return nil, err } - if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl); err != nil { + if err := setClientInfoWithSign(req, sig, allocationTx, baseUrl, clients...); err != nil { return nil, err } @@ -910,7 +923,7 @@ func NewWritemarkerRequest(baseUrl, allocationID, allocationTx, sig string) (*ht return req, nil } -func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body io.Reader) (*http.Request, error) { +func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body io.Reader, clients ...string) (*http.Request, error) { u, err := joinUrl(baseUrl, ROLLBACK_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -927,113 +940,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() - responses := make(map[int]int) - mu := &sync.Mutex{} - entityResult := make(map[string][]byte) - var retObj []byte - maxCount := 0 - dominant := 200 - wg := sync.WaitGroup{} - - cfg, err := conf.GetClientConfig() - if err != nil { - return nil, err - } - - for _, sharder := range sharders { - wg.Add(1) - go func(sharder string) { - defer wg.Done() - urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := url.Parse(urlString) - if err != nil { - log.Error(err) - return - } - q := urlObj.Query() - for k, v := range params { - q.Add(k, v) - } - urlObj.RawQuery = q.Encode() - client := &http.Client{Transport: DefaultTransport} - response, err := client.Get(urlObj.String()) - if err != nil { - blockchain.Sharders.Fail(sharder) - return - } - - defer response.Body.Close() - entityBytes, _ := io.ReadAll(response.Body) - mu.Lock() - if response.StatusCode > http.StatusBadRequest { - blockchain.Sharders.Fail(sharder) - } else { - blockchain.Sharders.Success(sharder) - } - responses[response.StatusCode]++ - if responses[response.StatusCode] > maxCount { - maxCount = responses[response.StatusCode] - } - - if isCurrentDominantStatus(response.StatusCode, responses, maxCount) { - dominant = response.StatusCode - retObj = entityBytes - } - - entityResult[sharder] = entityBytes - blockchain.Sharders.Success(sharder) - mu.Unlock() - }(sharder) - } - wg.Wait() - - rate := float32(maxCount*100) / float32(cfg.SharderConsensous) - if rate < consensusThresh { - err = errors.New("consensus_failed", "consensus failed on sharders") - } - - if dominant != 200 { - var objmap map[string]json.RawMessage - err := json.Unmarshal(retObj, &objmap) - if err != nil { - return nil, errors.New("", string(retObj)) - } - - var parsed string - err = json.Unmarshal(objmap["error"], &parsed) - if err != nil || parsed == "" { - return nil, errors.New("", string(retObj)) - } - - return nil, errors.New("", parsed) - } - - if handler != nil { - handler(entityResult, numSharders, err) - } - - if rate > consensusThresh { - return retObj, nil - } - return nil, err -} - func HttpDo(ctx context.Context, cncl context.CancelFunc, req *http.Request, f func(*http.Response, error) error) error { // Run the HTTP request in a goroutine and pass the response to f. c := make(chan error, 1) go func() { var err error - // indefinitely try if io.EOF error occurs. As per some research over google - // it occurs when client http tries to send byte stream in connection that is - // closed by the server for { var resp *http.Response resp, err = Client.Do(req.WithContext(ctx)) @@ -1047,31 +958,15 @@ func HttpDo(ctx context.Context, cncl context.CancelFunc, req *http.Request, f f c <- err }() - // TODO: Check cncl context required in any case - // defer cncl() select { case <-ctx.Done(): - DefaultTransport.CancelRequest(req) //nolint - <-c // Wait for f to return. + <-c // Wait for f to return. // Wait for f to return. return ctx.Err() case err := <-c: return err } } -// isCurrentDominantStatus determines whether the current response status is the dominant status among responses. -// -// The dominant status is where the response status is counted the most. -// On tie-breakers, 200 will be selected if included. -// -// Function assumes runningTotalPerStatus can be accessed safely concurrently. -func isCurrentDominantStatus(respStatus int, currentTotalPerStatus map[int]int, currentMax int) bool { - // mark status as dominant if - // - running total for status is the max and response is 200 or - // - running total for status is the max and count for 200 is lower - return currentTotalPerStatus[respStatus] == currentMax && (respStatus == 200 || currentTotalPerStatus[200] < currentMax) -} - func joinUrl(baseURl string, paths ...string) (*url.URL, error) { u, err := url.Parse(baseURl) if err != nil { diff --git a/zboxcore/zboxutil/http_test.go b/zboxcore/zboxutil/http_test.go deleted file mode 100644 index aa07f08a1..000000000 --- a/zboxcore/zboxutil/http_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package zboxutil - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestIsCurrentDominantStatus(t *testing.T) { - for _, tc := range []struct { - name string - status int - runningTotalPerStatus map[int]int - runningMax int - wantIsDominant bool - }{ - { - name: "first response - 200", - status: 200, - runningTotalPerStatus: map[int]int{200: 1}, - runningMax: 1, - wantIsDominant: true, - }, - { - name: "first response - 500", - status: 500, - runningTotalPerStatus: map[int]int{500: 1}, - runningMax: 1, - wantIsDominant: true, - }, - { - name: "current response - 200 (previous was 500) - tiebreakers", - status: 200, - runningTotalPerStatus: map[int]int{200: 1, 500: 1}, - runningMax: 1, - wantIsDominant: true, - }, - { - name: "current response - 500 (previous was 200) - tiebreakers - should not be dominant", - status: 500, - runningTotalPerStatus: map[int]int{200: 1, 500: 1}, - runningMax: 1, - wantIsDominant: false, - }, - { - name: "current response - 500 (previous were 200, 500)", - status: 500, - runningTotalPerStatus: map[int]int{200: 1, 500: 2}, - runningMax: 2, - wantIsDominant: true, - }, - { - name: "current response - 200 (previous were 400, 404, 500) - tiebreakers", - status: 200, - runningTotalPerStatus: map[int]int{200: 1, 400: 1, 404: 1, 500: 1}, - runningMax: 1, - wantIsDominant: true, - }, - } { - tt := tc - t.Run(tt.name, func(t *testing.T) { - got := isCurrentDominantStatus(tt.status, tt.runningTotalPerStatus, tt.runningMax) - - assert.Equal(t, tt.wantIsDominant, got) - }) - } -} diff --git a/zboxcore/zboxutil/transport.go b/zboxcore/zboxutil/transport.go deleted file mode 100644 index 61fd3c509..000000000 --- a/zboxcore/zboxutil/transport.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !js && !wasm -// +build !js,!wasm - -package zboxutil - -import ( - "net" - "net/http" - "time" -) - -var DefaultTransport = &http.Transport{ - Proxy: envProxy.Proxy, - DialContext: (&net.Dialer{ - Timeout: 3 * time.Minute, - KeepAlive: 45 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 45 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: 25, -} From f467a95abf679a47a124a98ef14f9b9622d5f7c3 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 23 Jan 2025 17:33:20 +0530 Subject: [PATCH 088/107] added v2 enpoint --- zboxcore/zboxutil/http.go | 1 + 1 file changed, 1 insertion(+) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 36e337d9a..61b490ac6 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -53,6 +53,7 @@ const ( MOVE_ENDPOINT = "/v1/file/move/" LIST_ENDPOINT = "/v1/file/list/" REFERENCE_ENDPOINT = "/v1/file/referencepath/" + REFERENCE_ENDPOINT_V2 = "/v2/file/referencepath/" CONNECTION_ENDPOINT = "/v1/connection/details/" COMMIT_ENDPOINT = "/v1/connection/commit/" DOWNLOAD_ENDPOINT = "/v1/file/download/" From 816f38888b14d311610fab75efce441d90d7a3d5 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 23 Jan 2025 23:39:54 +0530 Subject: [PATCH 089/107] delete file --- core/version/doc.go | 1 + zboxcore/client/entity.go | 196 -------------------------------------- 2 files changed, 1 insertion(+), 196 deletions(-) delete mode 100644 zboxcore/client/entity.go diff --git a/core/version/doc.go b/core/version/doc.go index 3c7ff49dc..4be27df03 100644 --- a/core/version/doc.go +++ b/core/version/doc.go @@ -1,3 +1,4 @@ // AUTOGENERATED! Do not use. // Provide current version of the SDK package version + \ No newline at end of file diff --git a/zboxcore/client/entity.go b/zboxcore/client/entity.go deleted file mode 100644 index 91ba522b4..000000000 --- a/zboxcore/client/entity.go +++ /dev/null @@ -1,196 +0,0 @@ -// Methods and types for client and wallet operations. -package client - -import ( - "encoding/json" - "fmt" - - "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/core/zcncrypto" -) - -type SignFunc func(hash string) (string, error) - -// Client represents client information -type Client struct { - *zcncrypto.Wallet - SignatureScheme string - txnFee uint64 -} - -var ( - client *Client - clients []*Client - - // Sign is a function to sign a hash - Sign SignFunc - sigC = make(chan struct{}, 1) -) - -func init() { - client = &Client{ - Wallet: &zcncrypto.Wallet{}, - } - - sigC <- struct{}{} - - sys.Sign = signHash - sys.SignWithAuth = signHash - - // initialize SignFunc as default implementation - Sign = func(hash string) (string, error) { - if client.PeerPublicKey == "" { - return sys.Sign(hash, client.SignatureScheme, GetClientSysKeys()) - } - - // get sign lock - <-sigC - fmt.Println("Sign: with sys.SignWithAuth:", sys.SignWithAuth, "sysKeys:", GetClientSysKeys()) - sig, err := sys.SignWithAuth(hash, client.SignatureScheme, GetClientSysKeys()) - sigC <- struct{}{} - return sig, err - } - - sys.Verify = VerifySignature - sys.VerifyWith = VerifySignatureWith -} - -func SetClient(w *zcncrypto.Wallet, signatureScheme string, txnFee uint64) { - client.Wallet = w - client.SignatureScheme = signatureScheme - client.txnFee = txnFee -} - -// 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 -} - -// SetTxnFee sets general transaction fee -func SetTxnFee(fee uint64) { - client.txnFee = fee -} - -// TxnFee gets general txn fee -func TxnFee() uint64 { - return client.txnFee -} - -// 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) - if err := json.Unmarshal([]byte(clientJson), c); err != nil { - return err - } - c.SignatureScheme = signatureScheme - clients = append(clients, c) - } - 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 -} - -func GetClientPeerPublicKey() string { - return client.PeerPublicKey - -} - -// GetClientPrivateKey returns client private key -func GetClientPrivateKey() string { - for _, kv := range client.Keys { - return kv.PrivateKey - } - - return "" -} - -// GetClientSysKeys convert client.KeyPair to sys.KeyPair -func GetClientSysKeys() []sys.KeyPair { - var keys []sys.KeyPair - if client != nil { - for _, kv := range client.Keys { - keys = append(keys, sys.KeyPair{ - PrivateKey: kv.PrivateKey, - PublicKey: kv.PublicKey, - }) - } - } - - return keys -} - -func signHash(hash string, signatureScheme string, keys []sys.KeyPair) (string, error) { - retSignature := "" - for _, kv := range keys { - ss := zcncrypto.NewSignatureScheme(signatureScheme) - err := ss.SetPrivateKey(kv.PrivateKey) - if err != nil { - return "", err - } - - if len(retSignature) == 0 { - retSignature, err = ss.Sign(hash) - } else { - retSignature, err = ss.Add(retSignature, hash) - } - if err != nil { - return "", err - } - } - 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 { - return false, err - } - - 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) - if err != nil { - return false, err - } - return sch.Verify(signature, hash) -} From 6545972ed7b6544e892749ba5a10dd0013f57291 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 24 Jan 2025 12:59:57 +0530 Subject: [PATCH 090/107] updates --- zboxcore/allocationchange/newfile.go | 2 +- zboxcore/allocationchange/updatefile.go | 2 +- zboxcore/marker/authticket.go | 2 +- zboxcore/marker/deletetoken.go | 2 +- zboxcore/marker/readmarker.go | 2 +- zboxcore/marker/versionmarker.go | 2 +- zboxcore/marker/writemarker.go | 2 +- zboxcore/sdk/commitworker.go | 4 ++-- zboxcore/sdk/sharerequest.go | 4 ++-- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/zboxcore/allocationchange/newfile.go b/zboxcore/allocationchange/newfile.go index 559267e3c..3c9f9e81b 100644 --- a/zboxcore/allocationchange/newfile.go +++ b/zboxcore/allocationchange/newfile.go @@ -7,10 +7,10 @@ import ( "strings" zError "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/pathutil" "github.com/0chain/gosdk_common/core/util" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/google/uuid" diff --git a/zboxcore/allocationchange/updatefile.go b/zboxcore/allocationchange/updatefile.go index eb5ac27df..960b89a42 100644 --- a/zboxcore/allocationchange/updatefile.go +++ b/zboxcore/allocationchange/updatefile.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/pathutil" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" ) diff --git a/zboxcore/marker/authticket.go b/zboxcore/marker/authticket.go index 79fc0ba4f..a5a71fe3b 100644 --- a/zboxcore/marker/authticket.go +++ b/zboxcore/marker/authticket.go @@ -3,8 +3,8 @@ package marker import ( "fmt" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/zboxcore/client" ) // AuthTicket authentication ticket for file sharing. diff --git a/zboxcore/marker/deletetoken.go b/zboxcore/marker/deletetoken.go index 2d7615255..09ae0438a 100644 --- a/zboxcore/marker/deletetoken.go +++ b/zboxcore/marker/deletetoken.go @@ -3,8 +3,8 @@ package marker import ( "fmt" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" - "github.com/0chain/gosdk_common/zboxcore/client" ) type DeleteToken struct { diff --git a/zboxcore/marker/readmarker.go b/zboxcore/marker/readmarker.go index da325627d..8989b50e5 100644 --- a/zboxcore/marker/readmarker.go +++ b/zboxcore/marker/readmarker.go @@ -4,10 +4,10 @@ import ( "fmt" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/client" ) type ReadMarker struct { diff --git a/zboxcore/marker/versionmarker.go b/zboxcore/marker/versionmarker.go index 2d4571842..300250e90 100644 --- a/zboxcore/marker/versionmarker.go +++ b/zboxcore/marker/versionmarker.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/client" ) type VersionMarker struct { diff --git a/zboxcore/marker/writemarker.go b/zboxcore/marker/writemarker.go index 0f59ab295..8305931a5 100644 --- a/zboxcore/marker/writemarker.go +++ b/zboxcore/marker/writemarker.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/sys" - "github.com/0chain/gosdk_common/zboxcore/client" ) type WriteMarker struct { diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index cdd4f5af9..78316ac0e 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -16,8 +16,8 @@ import ( "github.com/0chain/errors" thrown "github.com/0chain/errors" "github.com/0chain/gosdk/zboxcore/allocationchange" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -116,7 +116,7 @@ func (req *CommitRequest) commitBlobber() (err error) { vm := &marker.VersionMarker{ Version: req.version, Timestamp: req.timestamp, - ClientID: client.GetClientID(), + ClientID: client.Id(), AllocationID: req.allocationID, BlobberID: req.blobber.ID, IsRepair: req.isRepair, diff --git a/zboxcore/sdk/sharerequest.go b/zboxcore/sdk/sharerequest.go index ec812cada..4be3f6def 100644 --- a/zboxcore/sdk/sharerequest.go +++ b/zboxcore/sdk/sharerequest.go @@ -6,9 +6,9 @@ import ( "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/zboxcore/blockchain" - "github.com/0chain/gosdk_common/zboxcore/client" "github.com/0chain/gosdk_common/zboxcore/encryption" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/marker" @@ -55,7 +55,7 @@ func (req *ShareRequest) getAuthTicket(clientID, encPublicKey string) (*marker.A at := &marker.AuthTicket{ AllocationID: req.allocationID, - OwnerID: client.GetClientID(), + OwnerID: client.Id(), ClientID: clientID, FileName: req.remotefilename, FilePathHash: fileref.GetReferenceLookup(req.allocationID, req.remotefilepath), From 29a8e71af584dc36105ce3047362ae846a2197d5 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 24 Jan 2025 13:23:03 +0530 Subject: [PATCH 091/107] updates --- go.mod | 2 +- go.sum | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 97fdbb2b3..a03c55ebd 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250122192236-7180658d2e00 + github.com/0chain/gosdk_common v0.0.0-20250124074147-1da9c7e420af github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index d067259d1..209a26e4f 100644 --- a/go.sum +++ b/go.sum @@ -44,10 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e h1:TskvG+KrEWp4obrELJk1QRX3tjnsr1mlBapeb1fV2cU= -github.com/0chain/gosdk_common v0.0.0-20250121151838-b0477651681e/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= -github.com/0chain/gosdk_common v0.0.0-20250122192236-7180658d2e00 h1:wXxNBOnZxE1nG+6oKjdK5S58yckasW0W8UW2h70ZZTc= -github.com/0chain/gosdk_common v0.0.0-20250122192236-7180658d2e00/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250124074147-1da9c7e420af h1:H5TTXcjIVOZC26/uQ493eUROx1sR1hg7JshsUmEVbuw= +github.com/0chain/gosdk_common v0.0.0-20250124074147-1da9c7e420af/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= From 9445d47d0b268370317243500c083e290510e660 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Sat, 1 Feb 2025 18:58:58 +0530 Subject: [PATCH 092/107] fixes --- zboxcore/sdk/rollback.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 9d464a6b8..e5d03020a 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -142,7 +142,7 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error } connID := zboxutil.NewConnectionId() - err = formWriter.WriteField("write_marker", string(vmData)) + err = formWriter.WriteField("version_marker", string(vmData)) if err != nil { return err } From de1ffc876e867640ba9d1d219db76312ccdaa357 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Sun, 2 Feb 2025 04:25:05 +0530 Subject: [PATCH 093/107] fixes --- zboxcore/sdk/blobber_operations.go | 70 +++++++++++++++++---- zboxcore/sdk/sdk.go | 98 +++++++++++++++++++----------- 2 files changed, 120 insertions(+), 48 deletions(-) diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index b567b5c34..93f44ade1 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -1,9 +1,7 @@ -//go:build !mobile -// +build !mobile - package sdk import ( + "crypto/ed25519" "encoding/hex" "encoding/json" "fmt" @@ -11,7 +9,10 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/logger" + "go.uber.org/zap" ) // CreateAllocationForOwner creates a new allocation with the given options (txn: `storagesc.new_allocation_request`). @@ -44,8 +45,8 @@ func CreateAllocationForOwner( return "", 0, nil, errors.New("allocation_validation_failed", "atleast 1 data and 1 parity shards are required") } - allocationRequest, err := getNewAllocationBlobbers(StorageV2, - datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds, blobberAuthTickets, force) + allocationRequest, err := getNewAllocationBlobbers( + StorageV2, datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds, blobberAuthTickets, force) if err != nil { return "", 0, nil, errors.New("failed_get_allocation_blobbers", "failed to get blobbers for allocation: "+err.Error()) } @@ -54,11 +55,23 @@ func CreateAllocationForOwner( return "", 0, nil, sdkNotInitialized } + if client.PublicKey() == ownerpublickey { + privateSigningKey, err := generateOwnerSigningKey(ownerpublickey, owner) + if err != nil { + return "", 0, nil, errors.New("failed_generate_owner_signing_key", "failed to generate owner signing key: "+err.Error()) + } + pub := privateSigningKey.Public().(ed25519.PublicKey) + pk := hex.EncodeToString(pub) + allocationRequest["owner_signing_public_key"] = pk + } + allocationRequest["owner_id"] = owner 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 + allocationRequest["storage_version"] = StorageV2 + allocationRequest["auth_round_expiry"] = authRoundExpiry var sn = transaction.SmartContractTxnData{ Name: transaction.NEW_ALLOCATION_REQUEST, @@ -121,6 +134,9 @@ func UpdateAllocation( addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerID, ownerSigninPublicKey string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, ticket string, ) (hash string, nonce int64, err error) { + if ownerID == "" { + ownerID = client.Id() + } if lock > math.MaxInt64 { return "", 0, errors.New("invalid_lock", "int64 overflow on lock value") @@ -130,13 +146,13 @@ func UpdateAllocation( return "", 0, sdkNotInitialized } - alloc, err := GetAllocation(allocationID) + alloc, err := GetAllocationForUpdate(allocationID) if err != nil { return "", 0, allocationNotFound } updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = client.Id() + updateAllocationRequest["owner_id"] = ownerID updateAllocationRequest["owner_public_key"] = "" updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size @@ -145,7 +161,27 @@ func UpdateAllocation( updateAllocationRequest["add_blobber_auth_ticket"] = addBlobberAuthTicket updateAllocationRequest["remove_blobber_id"] = removeBlobberId updateAllocationRequest["set_third_party_extendable"] = setThirdPartyExtendable + updateAllocationRequest["owner_signing_public_key"] = ownerSigninPublicKey updateAllocationRequest["file_options_changed"], updateAllocationRequest["file_options"] = calculateAllocationFileOptions(alloc.FileOptions, fileOptionsParams) + updateAllocationRequest["auth_round_expiry"] = authRoundExpiry + + if ticket != "" { + + type Ticket struct { + AllocationID string `json:"allocation_id"` + UserID string `json:"user_id"` + RoundExpiry int64 `json:"round_expiry"` + OperationType string `json:"operation_type"` + Signature string `json:"signature"` + } + + ticketData := &Ticket{} + err := json.Unmarshal([]byte(ticket), ticketData) + if err != nil { + return "", 0, errors.New("invalid_ticket", "invalid ticket") + } + updateAllocationRequest["update_ticket"] = ticketData + } sn := transaction.SmartContractTxnData{ Name: transaction.STORAGESC_UPDATE_ALLOCATION, @@ -275,10 +311,6 @@ func StakePoolUnlock(providerType ProviderType, providerID, clientID string, fee return spuu.Amount, nonce, nil } -// -// write pool -// - // WritePoolLock locks given number of tokes for given duration in read pool. // - allocID: allocation ID // - tokens: number of tokens to lock @@ -326,3 +358,19 @@ func WritePoolUnlock(allocID string, fee uint64) (hash string, nonce int64, err hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, 0, fee, true) return } + +func generateOwnerSigningKey(ownerPublicKey, ownerID string) (ed25519.PrivateKey, error) { + if ownerPublicKey == "" { + return nil, errors.New("owner_public_key_required", "owner public key is required") + } + hashData := fmt.Sprintf("%s:%s", ownerPublicKey, "owner_signing_public_key") + sig, err := client.Sign(encryption.Hash(hashData), ownerID) + if err != nil { + logger.Logger.Error("error during sign", zap.Error(err)) + return nil, err + } + //use this signature as entropy to generate ecdsa key pair + decodedSig, _ := hex.DecodeString(sig) + privateSigningKey := ed25519.NewKeyFromSeed(decodedSig[:32]) + return privateSigningKey, nil +} diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 795afb802..20f1f46f6 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -11,14 +11,14 @@ import ( "github.com/0chain/common/core/currency" "github.com/0chain/errors" + "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/core/screstapi" "gopkg.in/natefinch/lumberjack.v2" - "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/encryption" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -96,6 +96,7 @@ 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 } @@ -174,7 +175,7 @@ func GetStakePoolInfo(providerType ProviderType, providerID string) (info *Stake info = new(StakePoolInfo) if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "error decoding response:") + return nil, errors.Wrap(err, "3 error decoding response:") } return @@ -215,7 +216,7 @@ func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUs info = new(StakePoolUserInfo) if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "error decoding response:") + return nil, errors.Wrap(err, "4 error decoding response:") } return @@ -268,7 +269,7 @@ func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { info = new(ChallengePoolInfo) if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "error decoding response:") + return nil, errors.Wrap(err, "5 error decoding response:") } return @@ -282,7 +283,8 @@ func GetMptData(key string) ([]byte, error) { var b []byte b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/get_mpt_key", map[string]string{"key": key}) + "/get_mpt_key", map[string]string{"key": key}, + ) if err != nil { return nil, errors.Wrap(err, "error requesting mpt key data:") } @@ -446,13 +448,9 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe Nodes []*Blobber } - url := fmt.Sprintf("/getblobbers?active=%s&limit=%d&offset=%d&stakable=%s", - strconv.FormatBool(active), - limit, - offset, - strconv.FormatBool(stakable), - ) - b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, url, nil) + b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getblobbers", map[string]string{"active": strconv.FormatBool(active), "limit": strconv.FormatInt(int64(limit), 10), + "offset": strconv.FormatInt(int64(offset), 10), + "stakable": strconv.FormatBool(stakable)}) var wrap nodes if err != nil { return nil, errors.Wrap(err, "error requesting blobbers:") @@ -462,7 +460,7 @@ func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobbe } if err = json.Unmarshal(b, &wrap); err != nil { - return nil, errors.Wrap(err, "error decoding response:") + return nil, errors.Wrap(err, "6 error decoding response:") } return wrap.Nodes, nil @@ -513,7 +511,8 @@ func GetBlobber(blobberID string) (blob *Blobber, err error) { b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/getBlobber", - map[string]string{"blobber_id": blobberID}) + map[string]string{"blobber_id": blobberID}, + ) if err != nil { return nil, errors.Wrap(err, "requesting blobber:") } @@ -537,7 +536,8 @@ func GetValidator(validatorID string) (validator *Validator, err error) { b, err = screstapi.MakeSCRestAPICall( STORAGE_SCADDRESS, "/get_validator", - map[string]string{"validator_id": validatorID}) + map[string]string{"validator_id": validatorID}, + ) if err != nil { return nil, errors.Wrap(err, "requesting validator:") } @@ -563,7 +563,8 @@ func GetValidators(stakable bool) (validators []*Validator, err error) { "/validators", map[string]string{ "stakable": strconv.FormatBool(stakable), - }) + }, + ) if err != nil { return nil, errors.Wrap(err, "requesting validator list") } @@ -625,17 +626,37 @@ func GetAllocation(allocationID string) (*Allocation, error) { if err != nil { return nil, errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) } + allocationObj := &Allocation{} err = json.Unmarshal(allocationBytes, allocationObj) if err != nil { return nil, errors.New("allocation_decode_error", "Error decoding the allocation: "+err.Error()+" "+string(allocationBytes)) } - allocationObj.numBlockDownloads = numBlockDownloads allocationObj.InitAllocation() return allocationObj, nil } +// GetAllocationForUpdate - get allocation for update from given allocation id without calling init allocation +func GetAllocationForUpdate(allocationID string) (*Allocation, error) { + if !client.IsSDKInitialized() { + return nil, sdkNotInitialized + } + params := make(map[string]string) + params["allocation"] = allocationID + allocationBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation", params) + if err != nil { + return nil, errors.New("allocation_fetch_error", "Error fetching the allocation."+err.Error()) + } + + allocationObj := &Allocation{} + err = json.Unmarshal(allocationBytes, allocationObj) + if err != nil { + return nil, errors.New("allocation_decode_error", "Error decoding the allocation: "+err.Error()+" "+string(allocationBytes)) + } + return allocationObj, nil +} + func GetAllocationUpdates(allocation *Allocation) error { if allocation == nil { return errors.New("allocation_not_initialized", "") @@ -700,6 +721,7 @@ func getAllocationsInternal(clientID string, limit, offset int) ([]*Allocation, if err != nil { return nil, errors.New("allocations_fetch_error", "Error fetching the allocations."+err.Error()) } + allocations := make([]*Allocation, 0) err = json.Unmarshal(allocationsBytes, &allocations) if err != nil { @@ -856,6 +878,7 @@ func getNewAllocationBlobbers( "blobber_auth_tickets": blobberAuthTickets, "read_price_range": readPrice, "write_price_range": writePrice, + "storage_version": storageVersion, }, nil } } @@ -890,6 +913,7 @@ func getNewAllocationBlobbers( "blobber_auth_tickets": uniqueBlobberAuthTickets, "read_price_range": readPrice, "write_price_range": writePrice, + "storage_version": storageVersion, }, nil } @@ -1239,6 +1263,25 @@ func ResetAllocationStats(allocationId string) (string, int64, error) { return hash, n, err } +func StorageSmartContractTxn(sn transaction.SmartContractTxnData) ( + hash, out string, nonce int64, txn *transaction.Transaction, err error) { + + return storageSmartContractTxnValue(sn, 0) +} + +func storageSmartContractTxn(sn transaction.SmartContractTxnData) ( + hash, out string, nonce int64, txn *transaction.Transaction, err error) { + + return storageSmartContractTxnValue(sn, 0) +} + +func storageSmartContractTxnValue(sn transaction.SmartContractTxnData, value uint64) ( + hash, out string, nonce int64, txn *transaction.Transaction, err error) { + + // Fee is set during sdk initialization. + return transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, value, client.TxnFee(), true) +} + func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { if !client.IsSDKInitialized() { return "", sdkNotInitialized @@ -1423,22 +1466,3 @@ func updateMaskBit(mask uint16, index uint8, value bool) uint16 { return mask & ^uint16(1< Date: Mon, 3 Feb 2025 13:53:54 +0530 Subject: [PATCH 094/107] some refactor --- go.mod | 2 +- go.sum | 4 +- mobilesdk/zbox/allocation.go | 3 +- winsdk/allocation.go | 3 +- zboxcore/sdk/allocation.go | 170 +----------- zboxcore/sdk/allocation_file_delete_test.go | 11 +- zboxcore/sdk/allocation_test.go | 13 +- zboxcore/sdk/blobber_operations.go | 288 -------------------- zboxcore/sdk/common.go | 4 + zboxcore/sdk/sdk.go | 23 +- 10 files changed, 48 insertions(+), 473 deletions(-) diff --git a/go.mod b/go.mod index a03c55ebd..fde846bd2 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250124074147-1da9c7e420af + github.com/0chain/gosdk_common v0.0.0-20250202211447-5a289392e195 github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 209a26e4f..78a395dc0 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250124074147-1da9c7e420af h1:H5TTXcjIVOZC26/uQ493eUROx1sR1hg7JshsUmEVbuw= -github.com/0chain/gosdk_common v0.0.0-20250124074147-1da9c7e420af/go.mod h1:5MtnciUdibSOd2nDEWw346eWXmvpZZAywwrgFm/qmKM= +github.com/0chain/gosdk_common v0.0.0-20250202211447-5a289392e195 h1:fi/d2JFRbmgOQAO3Kf44DFV7jxtPLdGdyfuIa8+dPNE= +github.com/0chain/gosdk_common v0.0.0-20250202211447-5a289392e195/go.mod h1:aGBabvKYk/B6G6bEBI8j1cBaWY2is9sCii88Ly6VeCU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/mobilesdk/zbox/allocation.go b/mobilesdk/zbox/allocation.go index 14ea8fc73..bcbbc2d3c 100644 --- a/mobilesdk/zbox/allocation.go +++ b/mobilesdk/zbox/allocation.go @@ -10,6 +10,7 @@ import ( "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" ) var ErrInvalidAllocation = errors.New("zbox: invalid allocation") @@ -462,7 +463,7 @@ func (a *Allocation) GetMaxStorageCostWithBlobbers(size int64, blobbersJson stri if a == nil || a.sdkAllocation == nil { return "", ErrInvalidAllocation } - var selBlobbers *[]*sdk.BlobberAllocation + var selBlobbers *[]*commonsdk.BlobberAllocation err := json.Unmarshal([]byte(blobbersJson), selBlobbers) if err != nil { return "", err diff --git a/winsdk/allocation.go b/winsdk/allocation.go index 2379ad94a..97824a269 100644 --- a/winsdk/allocation.go +++ b/winsdk/allocation.go @@ -11,6 +11,7 @@ import ( "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zcncore" ) @@ -86,7 +87,7 @@ func CreateFreeAllocation(freemarker *C.char) *C.char { lock := zcncore.ConvertToValue(marker.FreeTokens) - allocationID, _, err := sdk.CreateFreeAllocation(js, lock) + allocationID, _, err := commonsdk.CreateFreeAllocation(js, lock) if err != nil { log.Error("win: ", err, "lock: ", lock, " marker:", js) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 1c9692bf5..2af75e35b 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -31,6 +31,7 @@ import ( "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" l "github.com/0chain/gosdk_common/zboxcore/logger" @@ -144,154 +145,9 @@ type ConsolidatedFileMetaByName struct { UpdatedAt common.Timestamp } -type AllocationStats struct { - UsedSize int64 `json:"used_size"` - NumWrites int64 `json:"num_of_writes"` - NumReads int64 `json:"num_of_reads"` - TotalChallenges int64 `json:"total_challenges"` - OpenChallenges int64 `json:"num_open_challenges"` - SuccessChallenges int64 `json:"num_success_challenges"` - FailedChallenges int64 `json:"num_failed_challenges"` - LastestClosedChallengeTxn string `json:"latest_closed_challenge"` -} - -// PriceRange represents a price range allowed by user to filter blobbers. -type PriceRange struct { - Min uint64 `json:"min"` - Max uint64 `json:"max"` -} - -// IsValid price range. -func (pr *PriceRange) IsValid() bool { - return pr.Min <= pr.Max -} - -// Terms represents Blobber terms. A Blobber can update its terms, -// but any existing offer will use terms of offer signing time. -type Terms struct { - ReadPrice common.Balance `json:"read_price"` // tokens / GB - WritePrice common.Balance `json:"write_price"` // tokens / GB - MaxOfferDuration time.Duration `json:"max_offer_duration"` -} - -// UpdateTerms represents Blobber terms during update blobber calls. -// A Blobber can update its terms, but any existing offer will use terms of offer signing time. -type UpdateTerms struct { - ReadPrice *common.Balance `json:"read_price,omitempty"` // tokens / GB - WritePrice *common.Balance `json:"write_price,omitempty"` // tokens / GB - 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"` - Terms Terms `json:"terms"` - MinLockDemand common.Balance `json:"min_lock_demand"` - Spent common.Balance `json:"spent"` - Penalty common.Balance `json:"penalty"` - ReadReward common.Balance `json:"read_reward"` - Returned common.Balance `json:"returned"` - ChallengeReward common.Balance `json:"challenge_reward"` - FinalReward common.Balance `json:"final_reward"` -} - // Allocation represents a storage allocation. type Allocation struct { - // 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. - BlobberDetails []*BlobberAllocation `json:"blobber_details"` - - // 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 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"` - - IsEnterprise bool `json:"is_enterprise"` - - StorageVersion int `json:"storage_version"` - - // Owner ecdsa public key - OwnerSigningPublicKey string `json:"owner_signing_public_key"` - - // 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"` - + commonsdk.Allocation numBlockDownloads int downloadChan chan *DownloadRequest repairChan chan *RepairRequest @@ -337,12 +193,12 @@ type OperationRequest struct { } // GetReadPriceRange returns the read price range from the global configuration. -func GetReadPriceRange() (PriceRange, error) { +func GetReadPriceRange() (commonsdk.PriceRange, error) { return getPriceRange("max_read_price") } // GetWritePriceRange returns the write price range from the global configuration. -func GetWritePriceRange() (PriceRange, error) { +func GetWritePriceRange() (commonsdk.PriceRange, error) { return getPriceRange("max_write_price") } @@ -364,30 +220,30 @@ func (a *Allocation) SetCheckStatus(checkStatus bool) { a.checkStatus = checkStatus } -func getPriceRange(name string) (PriceRange, error) { +func getPriceRange(name string) (commonsdk.PriceRange, error) { conf, err := transaction.GetConfig("storage_sc_config") if err != nil { - return PriceRange{}, err + return commonsdk.PriceRange{}, err } f := conf.Fields[name] mrp, err := strconv.ParseFloat(f, 64) if err != nil { - return PriceRange{}, err + return commonsdk.PriceRange{}, err } coin, err := currency.ParseZCN(mrp) if err != nil { - return PriceRange{}, err + return commonsdk.PriceRange{}, err } max, err := coin.Int64() if err != nil { - return PriceRange{}, err + return commonsdk.PriceRange{}, err } - return PriceRange{0, uint64(max)}, err + return commonsdk.PriceRange{0, uint64(max)}, err } // GetStats returns the statistics of the allocation. -func (a *Allocation) GetStats() *AllocationStats { +func (a *Allocation) GetStats() *commonsdk.AllocationStats { return a.Stats } @@ -2958,7 +2814,7 @@ func (a *Allocation) CancelRepair() error { return errors.New("invalid_cancel_repair_request", "No repair in progress for the allocation") } -func (a *Allocation) GetMaxWriteReadFromBlobbers(blobbers []*BlobberAllocation) (maxW float64, maxR float64, err error) { +func (a *Allocation) GetMaxWriteReadFromBlobbers(blobbers []*commonsdk.BlobberAllocation) (maxW float64, maxR float64, err error) { if !a.isInitialized() { return 0, 0, notInitialized } @@ -3028,7 +2884,7 @@ func (a *Allocation) GetMinWriteRead() (minW float64, minR float64, err error) { // 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) { +func (a *Allocation) GetMaxStorageCostFromBlobbers(size int64, blobbers []*commonsdk.BlobberAllocation) (float64, error) { var cost common.Balance // total price for size / duration for _, d := range blobbers { diff --git a/zboxcore/sdk/allocation_file_delete_test.go b/zboxcore/sdk/allocation_file_delete_test.go index 344f9ffd0..49de50be3 100644 --- a/zboxcore/sdk/allocation_file_delete_test.go +++ b/zboxcore/sdk/allocation_file_delete_test.go @@ -13,6 +13,7 @@ import ( "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/require" @@ -47,10 +48,12 @@ func TestAllocation_DeleteFile(t *testing.T) { require := require.New(t) a := &Allocation{ - DataShards: 2, - ParityShards: 2, - FileOptions: 63, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + DataShards: 2, + ParityShards: 2, + FileOptions: 63, + Owner: mockClientId, + }, } a.InitAllocation() client.SetSdkInitialized(true) diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index 0b991fdf2..056491c27 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -18,6 +18,7 @@ import ( "github.com/0chain/gosdk_common/dev/blobber" "github.com/0chain/gosdk_common/dev/blobber/model" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/encryption" "golang.org/x/crypto/sha3" @@ -276,7 +277,7 @@ func newTestAllocationEmptyBlobbers() (ssc *Allocation) { ssc = new(Allocation) ssc.Expiration = 0 ssc.ID = "ID" - ssc.BlobberDetails = make([]*BlobberAllocation, 0) + ssc.BlobberDetails = make([]*commonsdk.BlobberAllocation, 0) return ssc } @@ -288,14 +289,14 @@ func newTestAllocation() (ssc *Allocation) { return ssc } -func newBlobbersDetails() (blobbers []*BlobberAllocation) { - blobberDetails := make([]*BlobberAllocation, 0) +func newBlobbersDetails() (blobbers []*commonsdk.BlobberAllocation) { + blobberDetails := make([]*commonsdk.BlobberAllocation, 0) for i := 1; i <= 1; i++ { - var balloc BlobberAllocation + var balloc commonsdk.BlobberAllocation balloc.Size = 1000 - balloc.Terms = Terms{ReadPrice: common.Balance(100000000), WritePrice: common.Balance(100000000)} + balloc.Terms = commonsdk.Terms{ReadPrice: common.Balance(100000000), WritePrice: common.Balance(100000000)} blobberDetails = append(blobberDetails, &balloc) } @@ -345,7 +346,7 @@ func TestPriceRange_IsValid(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - pr := &PriceRange{ + pr := &commonsdk.PriceRange{ Min: tt.fields.Min, Max: tt.fields.Max, } diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 93f44ade1..8a3b7a60a 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -1,118 +1,14 @@ package sdk import ( - "crypto/ed25519" - "encoding/hex" "encoding/json" - "fmt" "math" "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/core/transaction" - "github.com/0chain/gosdk_common/zboxcore/logger" - "go.uber.org/zap" ) -// 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, IsEnterprise, force bool, fileOptionsParams *FileOptionsParameters, authRoundExpiry int64, -) (hash string, nonce int64, txn *transaction.Transaction, err error) { - - if lock > math.MaxInt64 { - return "", 0, nil, errors.New("invalid_lock", "int64 overflow on lock value") - } - - if datashards < 1 || parityshards < 1 { - return "", 0, nil, errors.New("allocation_validation_failed", "atleast 1 data and 1 parity shards are required") - } - - allocationRequest, err := getNewAllocationBlobbers( - StorageV2, datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds, blobberAuthTickets, force) - if err != nil { - return "", 0, nil, errors.New("failed_get_allocation_blobbers", "failed to get blobbers for allocation: "+err.Error()) - } - - if !client.IsSDKInitialized() { - return "", 0, nil, sdkNotInitialized - } - - if client.PublicKey() == ownerpublickey { - privateSigningKey, err := generateOwnerSigningKey(ownerpublickey, owner) - if err != nil { - return "", 0, nil, errors.New("failed_generate_owner_signing_key", "failed to generate owner signing key: "+err.Error()) - } - pub := privateSigningKey.Public().(ed25519.PublicKey) - pk := hex.EncodeToString(pub) - allocationRequest["owner_signing_public_key"] = pk - } - - allocationRequest["owner_id"] = owner - 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 - allocationRequest["storage_version"] = StorageV2 - allocationRequest["auth_round_expiry"] = authRoundExpiry - - var sn = transaction.SmartContractTxnData{ - Name: transaction.NEW_ALLOCATION_REQUEST, - InputArgs: allocationRequest, - } - hash, _, nonce, txn, err = storageSmartContractTxnValue(sn, lock) - return -} - -// 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - recipientPublicKey := client.PublicKey() - - var input = map[string]interface{}{ - "recipient_public_key": recipientPublicKey, - "marker": marker, - } - - blobbers, err := GetFreeAllocationBlobbers(input) - if err != nil { - return "", 0, err - } - - input["blobbers"] = blobbers - - var sn = transaction.SmartContractTxnData{ - Name: transaction.NEW_FREE_ALLOCATION, - InputArgs: input, - } - hash, _, n, _, err := storageSmartContractTxnValue(sn, value) - return hash, n, err -} - // UpdateAllocation sends an update request for an allocation (txn: `storagesc.update_allocation_request`) // // - size is the size of the allocation. @@ -190,187 +86,3 @@ func UpdateAllocation( hash, _, nonce, _, err = storageSmartContractTxnValue(sn, lock) return } - -func GetUpdateAllocTicket(allocationID, userID, operationType string, roundExpiry int64) (string, error) { - payload := fmt.Sprintf("%s:%d:%s:%s", allocationID, roundExpiry, userID, operationType) - - signature, err := client.Sign(hex.EncodeToString([]byte(payload))) - if err != nil { - return "", err - } - - return signature, nil -} - -// 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - if providerType == 0 { - return "", 0, errors.New("stake_pool_lock", "provider is required") - } - - if providerID == "" { - return "", 0, errors.New("stake_pool_lock", "provider_id is required") - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerID, - } - - var sn = transaction.SmartContractTxnData{ - InputArgs: &spr, - } - - var scAddress string - switch providerType { - case ProviderBlobber, ProviderValidator: - scAddress = STORAGE_SCADDRESS - sn.Name = transaction.STORAGESC_STAKE_POOL_LOCK - case ProviderMiner, ProviderSharder: - scAddress = MINERSC_SCADDRESS - sn.Name = transaction.MINERSC_LOCK - case ProviderAuthorizer: - scAddress = ZCNSC_SCADDRESS - sn.Name = transaction.ZCNSC_LOCK - default: - return "", 0, errors.Newf("stake_pool_lock", "unsupported provider type: %v", providerType) - } - - hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(scAddress, sn, value, fee, true) - return -} - -// StakePoolUnlock unlocks a stake pool tokens. If tokens can't be unlocked due -// to opened offers, then it returns time where the tokens can be unlocked, -// marking the pool as 'want to unlock' to avoid its usage in offers in the -// 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, clientID string, fee uint64) (unstake int64, nonce int64, err error) { - if !client.IsSDKInitialized() { - return 0, 0, sdkNotInitialized - } - - if providerType == 0 { - return 0, 0, errors.New("stake_pool_lock", "provider is required") - } - - if providerID == "" { - return 0, 0, errors.New("stake_pool_lock", "provider_id is required") - } - - spr := stakePoolRequest{ - ProviderType: providerType, - ProviderID: providerID, - ClientID: clientID, - } - - var sn = transaction.SmartContractTxnData{ - InputArgs: &spr, - } - - var scAddress string - switch providerType { - case ProviderBlobber, ProviderValidator: - scAddress = STORAGE_SCADDRESS - sn.Name = transaction.STORAGESC_STAKE_POOL_UNLOCK - case ProviderMiner, ProviderSharder: - scAddress = MINERSC_SCADDRESS - sn.Name = transaction.MINERSC_UNLOCK - case ProviderAuthorizer: - scAddress = ZCNSC_SCADDRESS - sn.Name = transaction.ZCNSC_UNLOCK - default: - return 0, 0, errors.Newf("stake_pool_unlock", "unsupported provider type: %v", providerType) - } - - var out string - if _, out, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(scAddress, sn, 0, fee, true); err != nil { - return // an error - } - - var spuu stakePoolLock - if err = json.Unmarshal([]byte(out), &spuu); err != nil { - return - } - - return spuu.Amount, nonce, nil -} - -// 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - type lockRequest struct { - AllocationID string `json:"allocation_id"` - } - - var req lockRequest - req.AllocationID = allocID - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_WRITE_POOL_LOCK, - InputArgs: &req, - } - - hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, tokens, fee, true) - return -} - -// 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - type unlockRequest struct { - AllocationID string `json:"allocation_id"` - } - - var req unlockRequest - req.AllocationID = allocID - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_WRITE_POOL_UNLOCK, - InputArgs: &req, - } - hash, _, nonce, _, err = transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, 0, fee, true) - return -} - -func generateOwnerSigningKey(ownerPublicKey, ownerID string) (ed25519.PrivateKey, error) { - if ownerPublicKey == "" { - return nil, errors.New("owner_public_key_required", "owner public key is required") - } - hashData := fmt.Sprintf("%s:%s", ownerPublicKey, "owner_signing_public_key") - sig, err := client.Sign(encryption.Hash(hashData), ownerID) - if err != nil { - logger.Logger.Error("error during sign", zap.Error(err)) - return nil, err - } - //use this signature as entropy to generate ecdsa key pair - decodedSig, _ := hex.DecodeString(sig) - privateSigningKey := ed25519.NewKeyFromSeed(decodedSig[:32]) - return privateSigningKey, nil -} diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 29407459f..85300bbf3 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -22,6 +22,10 @@ import ( const alreadyExists = "file already exists" +func SetSaveProgress(save bool) { + shouldSaveProgress = save +} + func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx string, remoteFilePath, sig string, blobber *blockchain.StorageNode, clientId ...string) (fileref.RefEntity, error) { httpreq, err := zboxutil.NewObjectTreeRequest(blobber.Baseurl, allocationID, allocationTx, sig, remoteFilePath) if err != nil { diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 20f1f46f6..828641fd2 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -20,6 +20,7 @@ import ( "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/core/version" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/encryption" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/marker" @@ -64,10 +65,6 @@ func SetShouldVerifyHash(verify bool) { shouldVerifyHash = verify } -func SetSaveProgress(save bool) { - shouldSaveProgress = save -} - // GetVersion - returns version string func GetVersion() string { return version.VERSIONSTR @@ -304,7 +301,7 @@ type Blobber struct { BaseURL string `json:"url"` // Terms of the blobber - Terms Terms `json:"terms"` + Terms commonsdk.Terms `json:"terms"` // Capacity of the blobber Capacity common.Size `json:"capacity"` @@ -355,7 +352,7 @@ type Blobber struct { type UpdateBlobber struct { ID common.Key `json:"id"` BaseURL *string `json:"url,omitempty"` - Terms *UpdateTerms `json:"terms,omitempty"` + Terms *commonsdk.UpdateTerms `json:"terms,omitempty"` Capacity *common.Size `json:"capacity,omitempty"` Allocated *common.Size `json:"allocated,omitempty"` LastHealthCheck *common.Timestamp `json:"last_health_check,omitempty"` @@ -786,14 +783,14 @@ type CreateAllocationOptions struct { DataShards int ParityShards int Size int64 - ReadPrice PriceRange - WritePrice PriceRange + ReadPrice commonsdk.PriceRange + WritePrice commonsdk.PriceRange Lock uint64 BlobberIds []string BlobberAuthTickets []string ThirdPartyExtendable bool IsEnterprise bool - FileOptionsParams *FileOptionsParameters + FileOptionsParams *commonsdk.FileOptionsParameters Force bool StorageVersion int AuthRoundExpiry int64 @@ -807,7 +804,7 @@ type CreateAllocationOptions struct { func CreateAllocationWith(options CreateAllocationOptions) ( string, int64, *transaction.Transaction, error) { - return CreateAllocationForOwner(client.Id(), + return commonsdk.CreateAllocationForOwner(client.Id(), client.PublicKey(), options.DataShards, options.ParityShards, options.Size, options.ReadPrice, options.WritePrice, options.Lock, options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams, options.AuthRoundExpiry) @@ -827,7 +824,7 @@ func GetAllocationBlobbers( storageVersion, datashards, parityshards int, size int64, isRestricted int, - readPrice, writePrice PriceRange, + readPrice, writePrice commonsdk.PriceRange, force ...bool, ) ([]string, error) { var allocationRequest = map[string]interface{}{ @@ -865,7 +862,7 @@ func GetAllocationBlobbers( func getNewAllocationBlobbers( storageVersion, datashards, parityshards int, size int64, - readPrice, writePrice PriceRange, + readPrice, writePrice commonsdk.PriceRange, preferredBlobberIds, blobberAuthTickets []string, force bool, ) (map[string]interface{}, error) { for _, authTicket := range blobberAuthTickets { @@ -1355,7 +1352,7 @@ func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { func GetAllocationMinLock( datashards, parityshards int, size int64, - writePrice PriceRange, + writePrice commonsdk.PriceRange, ) (int64, error) { baSize := int64(math.Ceil(float64(size) / float64(datashards))) totalSize := baSize * int64(datashards+parityshards) From dcf5a694cc1028f566ba5f5a0dfbfc8e85704a2c Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 4 Feb 2025 02:47:02 +0530 Subject: [PATCH 095/107] refactor --- go.mod | 4 +- go.sum | 4 +- mobilesdk/sdk/sdk.go | 27 +- wasmsdk/allocation.go | 73 +- wasmsdk/blobber.go | 9 +- wasmsdk/proxy.go | 4 +- winsdk/sdk.go | 5 +- zboxcore/blockchain/entity.go | 234 ---- zboxcore/fileref/doc.go | 6 - zboxcore/fileref/fileref.go | 321 ----- zboxcore/fileref/hashnode.go | 82 -- zboxcore/fileref/hashnode_test.go | 227 ---- zboxcore/fileref/list.go | 76 -- zboxcore/fileref/refpath.go | 104 -- zboxcore/logger/logger.go | 13 - zboxcore/sdk/allocation.go | 7 +- zboxcore/sdk/allocation_file_delete_test.go | 10 +- zboxcore/sdk/allocation_file_test.go | 107 +- zboxcore/sdk/allocation_test.go | 128 +- zboxcore/sdk/blobber_operations.go | 60 +- zboxcore/sdk/chunked_upload_bench_test.go | 17 +- zboxcore/sdk/copyworker_test.go | 15 +- zboxcore/sdk/deleteworker_test.go | 11 +- zboxcore/sdk/downloadworker.go | 3 +- zboxcore/sdk/renameworker_test.go | 13 +- zboxcore/sdk/sdk.go | 1196 +------------------ zboxcore/sdk/transaction_mobile.go | 138 --- zboxcore/sdk/writemarker_mutex_test.go | 37 +- 28 files changed, 298 insertions(+), 2633 deletions(-) delete mode 100644 zboxcore/blockchain/entity.go delete mode 100644 zboxcore/fileref/doc.go delete mode 100644 zboxcore/fileref/fileref.go delete mode 100644 zboxcore/fileref/hashnode.go delete mode 100644 zboxcore/fileref/hashnode_test.go delete mode 100644 zboxcore/fileref/list.go delete mode 100644 zboxcore/fileref/refpath.go delete mode 100644 zboxcore/logger/logger.go delete mode 100644 zboxcore/sdk/transaction_mobile.go diff --git a/go.mod b/go.mod index fde846bd2..6aec70d88 100644 --- a/go.mod +++ b/go.mod @@ -33,12 +33,12 @@ require ( golang.org/x/image v0.14.0 // indirect golang.org/x/sync v0.7.0 gopkg.in/cheggaaa/pb.v1 v1.0.28 - gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) require ( - github.com/0chain/gosdk_common v0.0.0-20250202211447-5a289392e195 + github.com/0chain/gosdk_common v0.0.0-20250203211137-32f7f9862646 github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 78a395dc0..e3b27bd72 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250202211447-5a289392e195 h1:fi/d2JFRbmgOQAO3Kf44DFV7jxtPLdGdyfuIa8+dPNE= -github.com/0chain/gosdk_common v0.0.0-20250202211447-5a289392e195/go.mod h1:aGBabvKYk/B6G6bEBI8j1cBaWY2is9sCii88Ly6VeCU= +github.com/0chain/gosdk_common v0.0.0-20250203211137-32f7f9862646 h1:xya8sojAMIjOH3tZ8KTplvnY5rkHI0ZVeGlxo4HeQLs= +github.com/0chain/gosdk_common v0.0.0-20250203211137-32f7f9862646/go.mod h1:aGBabvKYk/B6G6bEBI8j1cBaWY2is9sCii88Ly6VeCU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 9e3de1ad1..fdd9fdb45 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -20,6 +20,7 @@ import ( "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/conf" "github.com/0chain/gosdk_common/core/util" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk/mobilesdk/zbox" @@ -164,15 +165,15 @@ func InitStorageSDK(clientJson string, configJson string) (*StorageSDK, error) { // - 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} + readPrice := commonsdk.PriceRange{Min: 0, Max: math.MaxInt64} + writePrice := commonsdk.PriceRange{Min: 0, Max: math.MaxInt64} l, err := util.ParseCoinStr(lock) if err != nil { return nil, err } - options := sdk.CreateAllocationOptions{ + options := commonsdk.CreateAllocationOptions{ DataShards: datashards, ParityShards: parityshards, Size: size, @@ -180,11 +181,11 @@ func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expira WritePrice: writePrice, Lock: uint64(l), BlobberIds: []string{}, - FileOptionsParams: &sdk.FileOptionsParameters{}, + FileOptionsParams: &commonsdk.FileOptionsParameters{}, BlobberAuthTickets: blobberAuthTickets, } - sdkAllocationID, _, _, err := sdk.CreateAllocationWith(options) + sdkAllocationID, _, _, err := commonsdk.CreateAllocationWith(options) if err != nil { return nil, err } @@ -205,15 +206,15 @@ func (s *StorageSDK) CreateAllocation(datashards, parityshards int, size, expira // - 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} + readPrice := commonsdk.PriceRange{Min: 0, Max: math.MaxInt64} + writePrice := commonsdk.PriceRange{Min: 0, Max: math.MaxInt64} l, err := util.ParseCoinStr(lock) if err != nil { return nil, err } - options := sdk.CreateAllocationOptions{ + options := commonsdk.CreateAllocationOptions{ DataShards: datashards, ParityShards: parityshards, Size: size, @@ -241,7 +242,7 @@ func (s *StorageSDK) CreateAllocationWithBlobbers(name string, datashards, parit } } - sdkAllocationID, _, _, err := sdk.CreateAllocationWith(options) + sdkAllocationID, _, _, err := commonsdk.CreateAllocationWith(options) if err != nil { return nil, err } @@ -322,14 +323,14 @@ func (s *StorageSDK) GetAllocationStats(allocationID string) (string, error) { // FinalizeAllocation finalize allocation // - allocationID: allocation ID func (s *StorageSDK) FinalizeAllocation(allocationID string) (string, error) { - hash, _, err := sdk.FinalizeAllocation(allocationID) + hash, _, err := commonsdk.FinalizeAllocation(allocationID) return hash, err } // CancelAllocation cancel allocation by ID // - allocationID: allocation ID func (s *StorageSDK) CancelAllocation(allocationID string) (string, error) { - hash, _, err := sdk.CancelAllocation(allocationID) + hash, _, err := commonsdk.CancelAllocation(allocationID) return hash, err } @@ -353,7 +354,7 @@ func (s *StorageSDK) WritePoolLock(durInSeconds int64, tokens, fee float64, allo if err != nil { return errors.Errorf("Error parsing fee: %v", err) } - _, _, err = sdk.WritePoolLock( + _, _, err = commonsdk.WritePoolLock( allocID, wpLockUint, feeUint, @@ -420,7 +421,7 @@ func (s *StorageSDK) RedeemFreeStorage(ticket string) (string, error) { return "", fmt.Errorf("invalid_free_marker: free marker is not assigned to your wallet") } - hash, _, err := sdk.CreateFreeAllocation(marker, lock) + hash, _, err := commonsdk.CreateFreeAllocation(marker, lock) return hash, err } diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 4e4713d03..efa7c0ecc 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -16,6 +16,7 @@ import ( "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" ) const TOKEN_UNIT int64 = 1e10 @@ -35,13 +36,13 @@ type decodeAuthTokenResp struct { // 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) + return commonsdk.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) + allocationID, _, err := commonsdk.CreateFreeAllocation(freeStorageMarker, 0) if err != nil { sdkLogger.Error("Error creating free allocation: ", err) return "", err @@ -65,13 +66,13 @@ func getAllocationBlobbers(preferredBlobberURLs []string, minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, isRestricted int, force bool) ([]string, error) { if len(preferredBlobberURLs) > 0 { - return sdk.GetBlobberIds(preferredBlobberURLs) + return commonsdk.GetBlobberIds(preferredBlobberURLs) } - return sdk.GetAllocationBlobbers(sdk.StorageV2, dataShards, parityShards, size, isRestricted, sdk.PriceRange{ + return commonsdk.GetAllocationBlobbers(sdk.StorageV2, dataShards, parityShards, size, isRestricted, commonsdk.PriceRange{ Min: uint64(minReadPrice), Max: uint64(maxReadPrice), - }, sdk.PriceRange{ + }, commonsdk.PriceRange{ Min: uint64(minWritePrice), Max: uint64(maxWritePrice), }, force) @@ -92,15 +93,15 @@ func createAllocation(datashards, parityshards int, size, authRoundExpiry int64, minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, lock int64, blobberIds, blobberAuthTickets []string, setThirdPartyExtendable, IsEnterprise, force bool) ( *transaction.Transaction, error) { - options := sdk.CreateAllocationOptions{ + options := commonsdk.CreateAllocationOptions{ DataShards: datashards, ParityShards: parityshards, Size: size, - ReadPrice: sdk.PriceRange{ + ReadPrice: commonsdk.PriceRange{ Min: uint64(minReadPrice), Max: uint64(maxReadPrice), }, - WritePrice: sdk.PriceRange{ + WritePrice: commonsdk.PriceRange{ Min: uint64(minWritePrice), Max: uint64(maxWritePrice), }, @@ -115,7 +116,7 @@ func createAllocation(datashards, parityshards int, size, authRoundExpiry int64, } sdkLogger.Info(options) - _, _, txn, err := sdk.CreateAllocationWith(options) + _, _, txn, err := commonsdk.CreateAllocationWith(options) return txn, err } @@ -173,13 +174,13 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for "", //owner, "", //ownerSigninPublicKey false, // thirdPartyExtendable - &sdk.FileOptionsParameters{ - ForbidUpload: sdk.FileOptionParam{Changed: forbidupload, Value: forbidupload}, - ForbidDelete: sdk.FileOptionParam{Changed: forbiddelete, Value: forbiddelete}, - ForbidUpdate: sdk.FileOptionParam{Changed: forbidupdate, Value: forbidupdate}, - ForbidMove: sdk.FileOptionParam{Changed: forbidmove, Value: forbidmove}, - ForbidCopy: sdk.FileOptionParam{Changed: forbidcopy, Value: forbidcopy}, - ForbidRename: sdk.FileOptionParam{Changed: forbidrename, Value: forbidrename}, + &commonsdk.FileOptionsParameters{ + ForbidUpload: commonsdk.FileOptionParam{Changed: forbidupload, Value: forbidupload}, + ForbidDelete: commonsdk.FileOptionParam{Changed: forbiddelete, Value: forbiddelete}, + ForbidUpdate: commonsdk.FileOptionParam{Changed: forbidupdate, Value: forbidupdate}, + ForbidMove: commonsdk.FileOptionParam{Changed: forbidmove, Value: forbidmove}, + ForbidCopy: commonsdk.FileOptionParam{Changed: forbidcopy, Value: forbidcopy}, + ForbidRename: commonsdk.FileOptionParam{Changed: forbidrename, Value: forbidrename}, }, "", ) @@ -205,13 +206,13 @@ func freezeAllocation(allocationID string) (string, error) { "", //owner, "", //ownerSigninPublicKey false, // thirdPartyExtendable - &sdk.FileOptionsParameters{ - ForbidUpload: sdk.FileOptionParam{Changed: true, Value: true}, - ForbidDelete: sdk.FileOptionParam{Changed: true, Value: true}, - ForbidUpdate: sdk.FileOptionParam{Changed: true, Value: true}, - ForbidMove: sdk.FileOptionParam{Changed: true, Value: true}, - ForbidCopy: sdk.FileOptionParam{Changed: true, Value: true}, - ForbidRename: sdk.FileOptionParam{Changed: true, Value: true}, + &commonsdk.FileOptionsParameters{ + ForbidUpload: commonsdk.FileOptionParam{Changed: true, Value: true}, + ForbidDelete: commonsdk.FileOptionParam{Changed: true, Value: true}, + ForbidUpdate: commonsdk.FileOptionParam{Changed: true, Value: true}, + ForbidMove: commonsdk.FileOptionParam{Changed: true, Value: true}, + ForbidCopy: commonsdk.FileOptionParam{Changed: true, Value: true}, + ForbidRename: commonsdk.FileOptionParam{Changed: true, Value: true}, }, "", ) @@ -227,7 +228,7 @@ 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) + hash, _, err := commonsdk.CancelAllocation(allocationID) if err == nil { clearAllocation(allocationID) @@ -268,7 +269,7 @@ func updateAllocationWithRepair(allocationID string, } } - alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, authRoundExpiry, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, false, &sdk.FileOptionsParameters{}, updateAllocTicket) + alloc, hash, isRepairRequired, err := allocationObj.UpdateWithStatus(size, authRoundExpiry, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, false, &commonsdk.FileOptionsParameters{}, updateAllocTicket) if err != nil { return hash, err } @@ -305,7 +306,7 @@ func updateAllocation(allocationID string, size, authRoundExpiry int64, extend bool, lock int64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, setThirdPartyExtendable bool) (string, error) { - hash, _, err := sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, &sdk.FileOptionsParameters{}, "") + hash, _, err := sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, "", ownerSigninPublicKey, setThirdPartyExtendable, &commonsdk.FileOptionsParameters{}, "") if err == nil { clearAllocation(allocationID) @@ -315,7 +316,7 @@ func updateAllocation(allocationID string, } func getUpdateAllocTicket(allocationID, userID, operationType string, roundExpiry int64) (string, error) { - sign, err := sdk.GetUpdateAllocTicket(allocationID, userID, operationType, roundExpiry) + sign, err := commonsdk.GetUpdateAllocTicket(allocationID, userID, operationType, roundExpiry) if err != nil { return "", err } @@ -333,9 +334,9 @@ func getAllocationMinLock(datashards, parityshards int, size int64, maxwritePrice uint64, ) (int64, error) { - writePrice := sdk.PriceRange{Min: 0, Max: maxwritePrice} + writePrice := commonsdk.PriceRange{Min: 0, Max: maxwritePrice} - value, err := sdk.GetAllocationMinLock(datashards, parityshards, size, writePrice) + value, err := commonsdk.GetAllocationMinLock(datashards, parityshards, size, writePrice) if err != nil { sdkLogger.Error(err) return 0, err @@ -357,7 +358,7 @@ func getUpdateAllocationMinLock( size int64, extend bool, addBlobberId, removeBlobberId string) (int64, error) { - return sdk.GetUpdateAllocationMinLock(allocationID, size, extend, addBlobberId, removeBlobberId) + return commonsdk.GetUpdateAllocationMinLock(allocationID, size, extend, addBlobberId, removeBlobberId) } // getRemoteFileMap list all files in an allocation from the blobbers. @@ -396,7 +397,7 @@ func getRemoteFileMap(allocationID string) ([]*fileResp, error) { // - tokens: sas tokens // - fee: sas tokens func lockWritePool(allocID string, tokens, fee uint64) (string, error) { - hash, _, err := sdk.WritePoolLock(allocID, tokens, fee) + hash, _, err := commonsdk.WritePoolLock(allocID, tokens, fee) return hash, err } @@ -407,7 +408,7 @@ func lockWritePool(allocID string, tokens, fee uint64) (string, error) { // - providerID: provider id func lockStakePool(providerType, tokens, fee uint64, providerID string) (string, error) { - hash, _, err := sdk.StakePoolLock(sdk.ProviderType(providerType), providerID, + hash, _, err := commonsdk.StakePoolLock(commonsdk.ProviderType(providerType), providerID, tokens, fee) return hash, err } @@ -417,21 +418,21 @@ func lockStakePool(providerType, tokens, fee uint64, providerID string) (string, // - fee: transaction fees (in SAS) // - providerID: provider id func unlockStakePool(providerType, fee uint64, providerID, clientID string) (int64, error) { - unstake, _, err := sdk.StakePoolUnlock(sdk.ProviderType(providerType), providerID, clientID, fee) + unstake, _, err := commonsdk.StakePoolUnlock(commonsdk.ProviderType(providerType), providerID, clientID, fee) return unstake, err } func collectRewards(providerType int, providerID string) (string, error) { - hash, _, err := sdk.CollectRewards(providerID, sdk.ProviderType(providerType)) + hash, _, err := commonsdk.CollectRewards(providerID, commonsdk.ProviderType(providerType)) return hash, 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) { +func getSkatePoolInfo(providerType int, providerID string) (*commonsdk.StakePoolInfo, error) { - info, err := sdk.GetStakePoolInfo(sdk.ProviderType(providerType), providerID) + info, err := commonsdk.GetStakePoolInfo(commonsdk.ProviderType(providerType), providerID) if err != nil { return nil, err diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index fa47423ae..7a6afefcb 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -26,6 +26,7 @@ import ( "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -156,7 +157,7 @@ func getFileStats(allocationID, remotePath string) ([]*sdk.FileStats, error) { // 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 + var blobberSettings commonsdk.Blobber err := json.Unmarshal([]byte(blobberSettingsJson), &blobberSettings) if err != nil { sdkLogger.Error(err) @@ -168,7 +169,7 @@ func updateBlobberSettings(blobberSettingsJson string) (*transaction.Transaction InputArgs: blobberSettings, } - _, _, _, txn, err := sdk.StorageSmartContractTxn(sn) + _, _, _, txn, err := commonsdk.StorageSmartContractTxn(sn) return txn, err } @@ -1081,8 +1082,8 @@ func downloadBlocks(allocId, remotePath, authTicket, lookupHash, writeChunkFuncN // 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) +func getBlobbers(stakable bool) ([]*commonsdk.Blobber, error) { + blobbs, err := commonsdk.GetBlobbers(true, stakable) if err != nil { return nil, err } diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 5f30f8a1f..f73b89776 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -15,10 +15,10 @@ import ( "github.com/0chain/gosdk/core/version" "github.com/0chain/gosdk/wasmsdk/jsbridge" - "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/core/zcncrypto" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zcncore" "github.com/hack-pad/safejs" @@ -36,7 +36,7 @@ var ( func main() { fmt.Printf("0CHAIN - GOSDK (version=%v)\n", version.VERSIONSTR) sys.Files = sys.NewMemFS() - sdkLogger = sdk.GetLogger() + sdkLogger = commonsdk.GetLogger() zcnLogger = zcncore.GetLogger() window := js.Global() diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 9b40be203..2955c9b1f 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -17,6 +17,7 @@ import ( "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxapi" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/0chain/gosdk_common/zcncore" @@ -50,8 +51,8 @@ func SetLogFile(file *C.char) *C.char { return WithJSON(false, err) } - sdk.GetLogger().SetLevel(logger.DEBUG) - sdk.GetLogger().SetLogFile(f, true) + commonsdk.GetLogger().SetLevel(logger.DEBUG) + commonsdk.GetLogger().SetLogFile(f, true) zcncore.GetLogger().SetLevel(logger.DEBUG) zcncore.GetLogger().SetLogFile(f, true) diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go deleted file mode 100644 index b21b60845..000000000 --- a/zboxcore/blockchain/entity.go +++ /dev/null @@ -1,234 +0,0 @@ -// Methods and types for blockchain entities and interactions. -package blockchain - -import ( - "encoding/json" - "math" - "sync" - "sync/atomic" - - "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/util" - - "github.com/0chain/gosdk_common/core/conf" -) - -var miners []string -var mGuard sync.Mutex - -func getMinMinersSubmit() int { - minMiners := util.MaxInt(calculateMinRequired(float64(chain.MinSubmit), float64(len(chain.Miners))/100), 1) - return minMiners -} - -func calculateMinRequired(minRequired, percent float64) int { - return int(math.Ceil(minRequired * percent)) -} - -// GetStableMiners get stable miners -func GetStableMiners() []string { - mGuard.Lock() - defer mGuard.Unlock() - if len(miners) == 0 { - miners = util.GetRandom(chain.Miners, getMinMinersSubmit()) - } - - return miners -} - -// ResetStableMiners reset stable miners to random miners -func ResetStableMiners() { - mGuard.Lock() - defer mGuard.Unlock() - miners = util.GetRandom(chain.Miners, getMinMinersSubmit()) -} - -type ChainConfig struct { - BlockWorker string - Sharders []string - Miners []string - MinSubmit int - MinConfirmation int - ChainID string - MaxTxnQuery int - QuerySleepTime int -} - -// StakePoolSettings information. -type StakePoolSettings struct { - DelegateWallet string `json:"delegate_wallet"` - NumDelegates int `json:"num_delegates"` - ServiceCharge float64 `json:"service_charge"` -} - -// 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"` - AllocationVersion int64 `json:"-"` - - 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 { - val = 1 - } - 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) - return sharders, err -} - -var chain *ChainConfig -var Sharders *client.NodeHolder - -func init() { - chain = &ChainConfig{ - MaxTxnQuery: 5, - QuerySleepTime: 5, - MinSubmit: 10, - MinConfirmation: 10, - } -} - -// 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) - if err != nil { - return err - } - sharders, err := PopulateNodes(sharderjson) - if err != nil { - return err - } - SetSharders(sharders) - 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 -} - -func GetQuerySleepTime() int { - return chain.QuerySleepTime -} - -func GetMinSubmit() int { - return chain.MinSubmit -} - -func GetMinConfirmation() int { - return chain.MinConfirmation -} - -func SetBlockWorker(blockWorker string) { - chain.BlockWorker = blockWorker -} - -func SetSharders(sharderArray []string) { - consensus := conf.DefaultSharderConsensous - config, err := conf.GetClientConfig() - if err == nil && config != nil { - consensus = config.SharderConsensous - } - if len(sharderArray) < consensus { - consensus = len(sharderArray) - } - Sharders = client.NewHolder(sharderArray, consensus) -} - -func SetMiners(minerArray []string) { - chain.Miners = minerArray -} - -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/fileref/doc.go b/zboxcore/fileref/doc.go deleted file mode 100644 index 517ac3a63..000000000 --- a/zboxcore/fileref/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// 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 deleted file mode 100644 index 5aebc9ee4..000000000 --- a/zboxcore/fileref/fileref.go +++ /dev/null @@ -1,321 +0,0 @@ -package fileref - -import ( - "fmt" - "hash/fnv" - "math" - "strconv" - "strings" - - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/encryption" - 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" -) - -var fileCache, _ = lru.New[string, FileRef](100) - -type Collaborator struct { - RefID int64 `json:"ref_id"` - ClientID string `json:"client_id"` - CreatedAt string `json:"created_at"` -} - -type FileRef struct { - Ref `mapstructure:",squash"` - CustomMeta string `json:"custom_meta" mapstructure:"custom_meta"` - // ValidationRootSignature is signature signed by client for hash_of(ActualFileHashSignature + ValidationRoot) - ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` - ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` - ActualFileSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` - ActualFileHash string `json:"actual_file_hash" mapstructure:"actual_file_hash"` - // ActualFileHashSignature is signature signed by client for ActualFileHash - ActualFileHashSignature string `json:"actual_file_hash_signature" mapstructure:"actual_file_hash_signature"` - ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` - ActualThumbnailHash string `json:"actual_thumbnail_hash" mapstructure:"actual_thumbnail_hash"` - MimeType string `json:"mimetype" mapstructure:"mimetype"` - EncryptedKey string `json:"encrypted_key" mapstructure:"encrypted_key"` - EncryptedKeyPoint string `json:"encrypted_key_point" mapstructure:"encrypted_key_point"` - Collaborators []Collaborator `json:"collaborators" mapstructure:"collaborators"` -} - -func (fRef *FileRef) MetaID() string { - - hash := fnv.New64a() - hash.Write([]byte(fRef.Path)) - - return strconv.FormatUint(hash.Sum64(), 36) -} - -type RefEntity interface { - GetNumBlocks() int64 - GetSize() int64 - GetFileMetaHash() string - GetHash() string - CalculateHash() string - GetType() string - GetPathHash() string - GetLookupHash() string - GetPath() string - GetName() string - GetFileID() string - GetCreatedAt() common.Timestamp - GetUpdatedAt() common.Timestamp - GetAllocationVersion() int64 -} - -type Ref struct { - Type string `json:"type" mapstructure:"type"` - AllocationID string `json:"allocation_id" mapstructure:"allocation_id"` - Name string `json:"name" mapstructure:"name"` - Path string `json:"path" mapstructure:"path"` - Size int64 `json:"size" mapstructure:"size"` - ActualSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` - Hash string `json:"hash" mapstructure:"hash"` - ChunkSize int64 `json:"chunk_size" mapstructure:"chunk_size"` - NumBlocks int64 `json:"num_of_blocks" mapstructure:"num_of_blocks"` - PathHash string `json:"path_hash" mapstructure:"path_hash"` - LookupHash string `json:"lookup_hash" mapstructure:"lookup_hash"` - FileID string `json:"file_id" mapstructure:"file_id"` - FileMetaHash string `json:"file_meta_hash" mapstructure:"file_meta_hash"` - ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` - ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` - ActualThumbnailHash string `json:"actual_thumbnail_hash" mapstructure:"actual_thumbnail_hash"` - ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` - IsEmpty bool `json:"is_empty" mapstructure:"is_empty"` - AllocationVersion int64 `json:"allocation_version" mapstructure:"allocation_version"` - HashToBeComputed bool - ChildrenLoaded bool - Children []RefEntity `json:"-" mapstructure:"-"` - CreatedAt common.Timestamp `json:"created_at" mapstructure:"created_at"` - 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) -} - -func GetCacheKey(lookuphash, blobberID string) string { - return encryption.FastHash(lookuphash + ":" + blobberID) -} - -func StoreFileRef(key string, fr FileRef) { - fileCache.Add(key, fr) -} - -func GetFileRef(key string) (FileRef, bool) { - if fr, ok := fileCache.Get(key); ok { - return fr, true - } - return FileRef{}, false -} - -func DeleteFileRef(key string) { - fileCache.Remove(key) -} - -func (r *Ref) CalculateHash() string { - if len(r.Children) == 0 && !r.ChildrenLoaded && !r.HashToBeComputed { - return r.Hash - } - - childHashes := make([]string, len(r.Children)) - childFileMetaHashes := make([]string, len(r.Children)) - childPaths := make([]string, len(r.Children)) - var refNumBlocks int64 - var size int64 - - for index, childRef := range r.Children { - childRef.CalculateHash() - childFileMetaHashes[index] = childRef.GetFileMetaHash() - childHashes[index] = childRef.GetHash() - childPaths[index] = childRef.GetPath() - refNumBlocks += childRef.GetNumBlocks() - size += childRef.GetSize() - } - - r.FileMetaHash = encryption.Hash(r.GetPath() + strings.Join(childFileMetaHashes, ":")) - r.Hash = encryption.Hash(r.GetHashData() + strings.Join(childHashes, ":")) - - r.PathHash = encryption.Hash(strings.Join(childPaths, ":")) - r.NumBlocks = refNumBlocks - r.Size = size - - return r.Hash -} - -func (r *Ref) GetFileMetaHash() string { - return r.FileMetaHash -} - -func (r *Ref) GetHash() string { - return r.Hash -} - -func (r *Ref) GetHashData() string { - return fmt.Sprintf("%s:%s:%s", r.AllocationID, r.Path, r.FileID) -} - -func (r *Ref) GetType() string { - return r.Type -} - -func (r *Ref) GetNumBlocks() int64 { - return r.NumBlocks -} - -func (r *Ref) GetSize() int64 { - return r.Size -} - -func (r *Ref) GetPathHash() string { - return r.PathHash -} - -func (r *Ref) GetLookupHash() string { - return r.LookupHash -} - -func (r *Ref) GetPath() string { - return r.Path -} - -func (r *Ref) GetName() string { - return r.Name -} - -func (r *Ref) GetFileID() string { - return r.FileID -} - -func (r *Ref) GetCreatedAt() common.Timestamp { - return r.CreatedAt -} - -func (r *Ref) GetUpdatedAt() common.Timestamp { - return r.UpdatedAt -} - -func (r *Ref) AddChild(child RefEntity) { - if r.Children == nil { - r.Children = make([]RefEntity, 0) - } - var index int - var ltFound bool // less than found - // Add child in sorted fashion - for i, ref := range r.Children { - if strings.Compare(child.GetPath(), ref.GetPath()) == -1 { - index = i - ltFound = true - break - } - } - if ltFound { - r.Children = append(r.Children[:index+1], r.Children[index:]...) - r.Children[index] = child - } else { - r.Children = append(r.Children, child) - } - r.ChildrenLoaded = true -} - -func (r *Ref) RemoveChild(idx int) { - if idx < 0 { - return - } - r.Children = append(r.Children[:idx], r.Children[idx+1:]...) -} - -func (r *Ref) GetAllocationVersion() int64 { - return r.AllocationVersion -} - -func (fr *FileRef) GetFileMetaHash() string { - return fr.FileMetaHash -} -func (fr *FileRef) GetFileMetaHashData() string { - return fmt.Sprintf( - "%s:%d:%d:%s", - fr.Path, fr.Size, - fr.ActualFileSize, fr.ActualFileHash) -} - -func (fr *FileRef) GetHashData() string { - return fmt.Sprintf( - "%s:%s:%s:%s:%d:%d:%s:%d:%s", - fr.AllocationID, - fr.Type, // don't need to add it as well - fr.Name, // don't see any utility as fr.Path below has name in it - fr.Path, - fr.Size, - fr.ActualFileSize, - fr.ActualFileHash, - fr.ChunkSize, - fr.FileID, - ) -} - -func (fr *FileRef) GetHash() string { - return fr.Hash -} - -func (fr *FileRef) CalculateHash() string { - fr.Hash = encryption.Hash(fr.GetHashData()) - fr.FileMetaHash = encryption.Hash(fr.GetFileMetaHashData()) - fr.NumBlocks = int64(math.Ceil(float64(fr.Size*1.0) / CHUNK_SIZE)) - return fr.Hash -} - -func (fr *FileRef) GetType() string { - return fr.Type -} - -func (fr *FileRef) GetNumBlocks() int64 { - return fr.NumBlocks -} - -func (fr *FileRef) GetSize() int64 { - return fr.Size -} - -func (fr *FileRef) GetPathHash() string { - return fr.PathHash -} - -func (fr *FileRef) GetLookupHash() string { - return fr.LookupHash -} - -func (fr *FileRef) GetPath() string { - return fr.Path -} - -func (fr *FileRef) GetName() string { - return fr.Name -} - -func (fr *FileRef) GetFileID() string { - return fr.FileID -} - -func (fr *FileRef) GetCreatedAt() common.Timestamp { - return fr.CreatedAt -} - -func (fr *FileRef) GetUpdatedAt() common.Timestamp { - return fr.UpdatedAt -} diff --git a/zboxcore/fileref/hashnode.go b/zboxcore/fileref/hashnode.go deleted file mode 100644 index a19b3c742..000000000 --- a/zboxcore/fileref/hashnode.go +++ /dev/null @@ -1,82 +0,0 @@ -package fileref - -import ( - "strconv" - "strings" - - "github.com/0chain/gosdk_common/core/encryption" -) - -// Hashnode ref node in hash tree -type Hashnode struct { - // hash data - AllocationID string `json:"allocation_id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Path string `json:"path,omitempty"` - ValidationRoot string `json:"validation_root,omitempty"` - FixedMerkleRoot string `json:"fixed_merkle_root,omitempty"` - ActualFileHash string `json:"actual_file_hash,omitempty"` - ChunkSize int64 `json:"chunk_size,omitempty"` - Size int64 `json:"size,omitempty"` - ActualFileSize int64 `json:"actual_file_size,omitempty"` - - Children []*Hashnode `json:"children,omitempty"` - lookupHash string `json:"-"` -} - -func (n *Hashnode) AddChild(c *Hashnode) { - if n.Children == nil { - n.Children = make([]*Hashnode, 0, 10) - } - - n.Children = append(n.Children, c) -} - -// GetLookupHash get lookuphash -func (n *Hashnode) GetLookupHash() string { - if n.lookupHash == "" { - n.lookupHash = encryption.Hash(n.AllocationID + ":" + n.Path) - } - return n.lookupHash -} - -// GetHashCode get hash code -func (n *Hashnode) GetHashCode() string { - // dir - if n.Type == DIRECTORY { - if len(n.Children) == 0 { - return "" - } - - childHashes := make([]string, len(n.Children)) - - var size int64 - - for i, child := range n.Children { - childHashes[i] = child.GetHashCode() - size += child.Size - } - - n.Size = size - - return encryption.Hash(strings.Join(childHashes, ":")) - - } - - hashArray := []string{ - n.AllocationID, - n.Type, - n.Name, - n.Path, - strconv.FormatInt(n.Size, 10), - n.ValidationRoot, - n.FixedMerkleRoot, - strconv.FormatInt(n.ActualFileSize, 10), - n.ActualFileHash, - strconv.FormatInt(n.ChunkSize, 10), - } - - return encryption.Hash(strings.Join(hashArray, ":")) - -} diff --git a/zboxcore/fileref/hashnode_test.go b/zboxcore/fileref/hashnode_test.go deleted file mode 100644 index 6d065b57f..000000000 --- a/zboxcore/fileref/hashnode_test.go +++ /dev/null @@ -1,227 +0,0 @@ -package fileref - -import ( - "strconv" - "strings" - "testing" - - "github.com/0chain/gosdk_common/core/encryption" - "github.com/stretchr/testify/require" -) - -func TestHashnode_GetHashcode(t *testing.T) { - tests := []struct { - name string - exceptedRef blobberRef - actualHashnode Hashnode - }{ - { - name: "Empty root should be same", - exceptedRef: blobberRef{ - Type: DIRECTORY, - }, - actualHashnode: Hashnode{ - Type: DIRECTORY, - }, - }, - { - name: "Nested nodes should be same", - exceptedRef: blobberRef{ - AllocationID: "nested_nodes", - Type: DIRECTORY, - Name: "/", - Path: "/", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 1024, - Size: 10240, - ActualFileSize: 10240, - Children: []*blobberRef{ - { - AllocationID: "nested_nodes", - Type: DIRECTORY, - Name: "sub1", - Path: "/sub1", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 1024, - Size: 10240, - ActualFileSize: 10240, - childrenLoaded: true, - LookupHash: GetReferenceLookup("nested_nodes", "/sub1"), - Children: []*blobberRef{ - { - AllocationID: "nested_nodes", - Type: FILE, - Name: "file1", - Path: "/sub1/file1", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 1024, - Size: 10240, - ActualFileSize: 10240, - LookupHash: GetReferenceLookup("nested_nodes", "/sub1/file1"), - }, - }, - }, - { - AllocationID: "nested_nodes", - Type: DIRECTORY, - Name: "emptydir", - Path: "/emptydir", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 0, - Size: 0, - ActualFileSize: 0, - LookupHash: GetReferenceLookup("nested_nodes", "/emptydir"), - }, - }, - }, - actualHashnode: Hashnode{ - AllocationID: "nested_nodes", - Type: DIRECTORY, - Name: "/", - Path: "/", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 1024, - Size: 10240, - ActualFileSize: 10240, - Children: []*Hashnode{ - { - AllocationID: "nested_nodes", - Type: DIRECTORY, - Name: "sub1", - Path: "/sub1", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 1024, - Size: 10240, - ActualFileSize: 10240, - Children: []*Hashnode{ - { - AllocationID: "nested_nodes", - Type: FILE, - Name: "file1", - Path: "/sub1/file1", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 1024, - Size: 10240, - ActualFileSize: 10240, - }, - }, - }, - { - AllocationID: "nested_nodes", - Type: DIRECTORY, - Name: "emptydir", - Path: "/emptydir", - ValidationRoot: "content_hash", - FixedMerkleRoot: "merkle_root", - ActualFileHash: "actual_file_hash", - ChunkSize: 0, - Size: 0, - ActualFileSize: 0, - }, - }, - }, - }, - } - - for _, it := range tests { - t.Run(it.name, func(test *testing.T) { - require.Equal(test, it.exceptedRef.CalculateHash(), it.actualHashnode.GetHashCode()) - }) - } -} - -// blobberRef copied from https://github.com/0chain/blobber/blob/staging/code/go/0chain.net/blobbercore/reference/ref.go for unit tests -type blobberRef struct { - ID int64 `gorm:"column:id;primary_key"` - Type string `gorm:"column:type" dirlist:"type" filelist:"type"` - AllocationID string `gorm:"column:allocation_id"` - LookupHash string `gorm:"column:lookup_hash" dirlist:"lookup_hash" filelist:"lookup_hash"` - Name string `gorm:"column:name" dirlist:"name" filelist:"name"` - Path string `gorm:"column:path" dirlist:"path" filelist:"path"` - Hash string `gorm:"column:hash" dirlist:"hash" filelist:"hash"` - - ParentPath string `gorm:"column:parent_path"` - - ValidationRoot string `gorm:"column:validation_root" filelist:"validation_root"` - Size int64 `gorm:"column:size" dirlist:"size" filelist:"size"` - FixedMerkleRoot string `gorm:"column:fixed_merkle_root" filelist:"fixed_merkle_root"` - ActualFileSize int64 `gorm:"column:actual_file_size" filelist:"actual_file_size"` - ActualFileHash string `gorm:"column:actual_file_hash" filelist:"actual_file_hash"` - - Children []*blobberRef `gorm:"-"` - childrenLoaded bool - - ChunkSize int64 `gorm:"column:chunk_size" dirlist:"chunk_size" filelist:"chunk_size"` -} - -func (fr *blobberRef) GetFileHashData() string { - hashArray := make([]string, 0, 11) - hashArray = append(hashArray, - fr.AllocationID, - fr.Type, - fr.Name, - fr.Path, - strconv.FormatInt(fr.Size, 10), - fr.ValidationRoot, - fr.FixedMerkleRoot, - strconv.FormatInt(fr.ActualFileSize, 10), - fr.ActualFileHash, - strconv.FormatInt(fr.ChunkSize, 10), - ) - - return strings.Join(hashArray, ":") -} - -func (fr *blobberRef) CalculateFileHash() string { - fr.Hash = encryption.Hash(fr.GetFileHashData()) - fr.LookupHash = GetReferenceLookup(fr.AllocationID, fr.Path) - - return fr.Hash -} - -func (r *blobberRef) CalculateDirHash() string { - // empty directory, return hash directly - if len(r.Children) == 0 && !r.childrenLoaded { - return r.Hash - } - for _, childRef := range r.Children { - childRef.CalculateHash() - } - childHashes := make([]string, len(r.Children)) - - var size int64 - for index, childRef := range r.Children { - childHashes[index] = childRef.Hash - - size += childRef.Size - } - - r.Hash = encryption.Hash(strings.Join(childHashes, ":")) - - r.Size = size - - r.LookupHash = GetReferenceLookup(r.AllocationID, r.Path) - - return r.Hash -} - -func (r *blobberRef) CalculateHash() string { - if r.Type == DIRECTORY { - return r.CalculateDirHash() - } - return r.CalculateFileHash() -} diff --git a/zboxcore/fileref/list.go b/zboxcore/fileref/list.go deleted file mode 100644 index d1df6f901..000000000 --- a/zboxcore/fileref/list.go +++ /dev/null @@ -1,76 +0,0 @@ -package fileref - -import ( - "github.com/0chain/errors" - "github.com/mitchellh/mapstructure" -) - -type ListResult struct { - AllocationRoot string `json:"allocation_root"` - Meta map[string]interface{} `json:"meta_data"` - Entities []map[string]interface{} `json:"list"` -} - -func (lr *ListResult) GetDirTree(allocationID string) (*Ref, error) { - if lr.Meta == nil { - return nil, errors.New("invalid_list_path", "badly formatted list result, nil meta") - } - reftype := lr.Meta["type"].(string) - if reftype == DIRECTORY { - rootRef := &Ref{Type: DIRECTORY} - rootRef.AllocationID = allocationID - var md mapstructure.Metadata - config := &mapstructure.DecoderConfig{ - Metadata: &md, - Result: rootRef, - TagName: "mapstructure", - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - err = decoder.Decode(lr.Meta) - if err != nil { - return nil, err - } - err = lr.populateChildren(rootRef) - if err != nil { - return nil, err - } - return rootRef, nil - } - return nil, errors.New("invalid_list_path", "Invalid list path. list was not for a directory") -} - -func (lr *ListResult) populateChildren(ref *Ref) error { - for _, rpc := range lr.Entities { - reftype := rpc["type"].(string) - var childEntity RefEntity - if reftype == DIRECTORY { - dref := &Ref{Type: DIRECTORY} - dref.AllocationID = ref.AllocationID - childEntity = dref - } else { - fref := &FileRef{} - fref.Type = FILE - fref.AllocationID = ref.AllocationID - childEntity = fref - } - var md mapstructure.Metadata - config := &mapstructure.DecoderConfig{ - Metadata: &md, - Result: childEntity, - TagName: "mapstructure", - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return err - } - err = decoder.Decode(rpc) - if err != nil { - return err - } - ref.Children = append(ref.Children, childEntity) - } - return nil -} diff --git a/zboxcore/fileref/refpath.go b/zboxcore/fileref/refpath.go deleted file mode 100644 index a641a9e41..000000000 --- a/zboxcore/fileref/refpath.go +++ /dev/null @@ -1,104 +0,0 @@ -package fileref - -import ( - "github.com/0chain/errors" - "github.com/mitchellh/mapstructure" -) - -type ReferencePath struct { - Meta map[string]interface{} `json:"meta_data"` - List []*ReferencePath `json:"list,omitempty"` -} - -func (rp *ReferencePath) GetRefFromObjectTree(allocationID string) (RefEntity, error) { - reftype := rp.Meta["type"].(string) - if reftype == FILE { - rootRef := &FileRef{} - rootRef.Type = FILE - rootRef.AllocationID = allocationID - var md mapstructure.Metadata - config := &mapstructure.DecoderConfig{ - Metadata: &md, - Result: rootRef, - TagName: "mapstructure", - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - err = decoder.Decode(rp.Meta) - if err != nil { - return nil, err - } - return rootRef, nil - } - return rp.GetDirTree(allocationID) -} - -// GetDirTree covert and build root Ref with children -func (rp *ReferencePath) GetDirTree(allocationID string) (*Ref, error) { - reftype := rp.Meta["type"].(string) - if reftype == DIRECTORY { - rootRef := &Ref{Type: DIRECTORY} - rootRef.AllocationID = allocationID - var md mapstructure.Metadata - config := &mapstructure.DecoderConfig{ - Metadata: &md, - Result: rootRef, - TagName: "mapstructure", - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - err = decoder.Decode(rp.Meta) - if err != nil { - return nil, err - } - err = rp.populateChildren(rootRef) - if err != nil { - return nil, err - } - return rootRef, nil - } - return nil, errors.New("invalid_ref_path", "Invalid reference path. root was not a directory type") -} - -func (rp *ReferencePath) populateChildren(ref *Ref) error { - for _, rpc := range rp.List { - reftype := rpc.Meta["type"].(string) - var childEntity RefEntity - if reftype == DIRECTORY { - dref := &Ref{Type: DIRECTORY} - dref.AllocationID = ref.AllocationID - childEntity = dref - } else { - fref := &FileRef{} - fref.Type = FILE - fref.AllocationID = ref.AllocationID - childEntity = fref - } - var md mapstructure.Metadata - config := &mapstructure.DecoderConfig{ - Metadata: &md, - Result: childEntity, - TagName: "mapstructure", - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return err - } - err = decoder.Decode(rpc.Meta) - if err != nil { - return err - } - ref.AddChild(childEntity) //append(ref.Children, childEntity) - if childEntity.GetType() == DIRECTORY && rpc.List != nil && len(rpc.List) > 0 { - err = rpc.populateChildren(childEntity.(*Ref)) - } - if err != nil { - return err - } - } - return nil -} diff --git a/zboxcore/logger/logger.go b/zboxcore/logger/logger.go deleted file mode 100644 index cf36a3b33..000000000 --- a/zboxcore/logger/logger.go +++ /dev/null @@ -1,13 +0,0 @@ -// Proxy for the core logger package. -package logger - -import "github.com/0chain/gosdk_common/core/logger" - -var defaultLogLevel = logger.DEBUG - -// Logger global logger instance -var Logger logger.Logger - -func init() { - Logger.Init(defaultLogLevel, "0box-sdk") -} diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 2af75e35b..009209bba 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -238,8 +238,7 @@ func getPriceRange(name string) (commonsdk.PriceRange, error) { if err != nil { return commonsdk.PriceRange{}, err } - return commonsdk.PriceRange{0, uint64(max)}, err - + return commonsdk.PriceRange{Min: 0, Max: uint64(max)}, err } // GetStats returns the statistics of the allocation. @@ -2979,7 +2978,7 @@ func (a *Allocation) UpdateWithRepair( extend bool, lock uint64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, - setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, updateAllocTicket string, + setThirdPartyExtendable bool, fileOptionsParams *commonsdk.FileOptionsParameters, updateAllocTicket string, statusCB StatusCallback, ) (string, error) { updatedAlloc, hash, isRepairRequired, err := a.UpdateWithStatus(size, authRoundExpiry, extend, lock, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, setThirdPartyExtendable, fileOptionsParams, updateAllocTicket) @@ -3014,7 +3013,7 @@ func (a *Allocation) UpdateWithStatus( extend bool, lock uint64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey string, - setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, + setThirdPartyExtendable bool, fileOptionsParams *commonsdk.FileOptionsParameters, updateAllocTicket string, ) (*Allocation, string, bool, error) { var ( diff --git a/zboxcore/sdk/allocation_file_delete_test.go b/zboxcore/sdk/allocation_file_delete_test.go index 49de50be3..c0cf66aa0 100644 --- a/zboxcore/sdk/allocation_file_delete_test.go +++ b/zboxcore/sdk/allocation_file_delete_test.go @@ -167,10 +167,12 @@ func TestAllocation_deleteFile(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) a := &Allocation{ - DataShards: 2, - ParityShards: 2, - FileOptions: 63, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + DataShards: 2, + ParityShards: 2, + FileOptions: 63, + Owner: mockClientId, + }, } a.InitAllocation() client.SetSdkInitialized(true) diff --git a/zboxcore/sdk/allocation_file_test.go b/zboxcore/sdk/allocation_file_test.go index ab3f40e5f..c2257aabc 100644 --- a/zboxcore/sdk/allocation_file_test.go +++ b/zboxcore/sdk/allocation_file_test.go @@ -20,6 +20,7 @@ import ( "github.com/0chain/gosdk/zboxcore/mocks" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -210,12 +211,14 @@ func TestAllocation_UpdateFile(t *testing.T) { const mockLocalPath = "1.txt" a := &Allocation{ - ID: "TestAllocation_UpdateFile", - Tx: "TestAllocation_UpdateFile", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + ID: "TestAllocation_UpdateFile", + Tx: "TestAllocation_UpdateFile", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -281,11 +284,13 @@ func TestAllocation_UploadFile(t *testing.T) { defer teardown(t) } a := &Allocation{ - Tx: "TestAllocation_UploadFile", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Tx: "TestAllocation_UploadFile", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -319,12 +324,14 @@ func TestAllocation_UpdateFileWithThumbnail(t *testing.T) { zboxutil.FastHttpClient = &mockFastClient a := &Allocation{ - ID: "TestAllocation_UpdateFile_WithThumbNail", - Tx: "TestAllocation_UpdateFile_WithThumbNail", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + ID: "TestAllocation_UpdateFile_WithThumbNail", + Tx: "TestAllocation_UpdateFile_WithThumbNail", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -400,11 +407,13 @@ func TestAllocation_UploadFileWithThumbnail(t *testing.T) { defer teardown(t) } a := &Allocation{ - Tx: "TestAllocation_UploadFileWithThumbnail", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Tx: "TestAllocation_UploadFileWithThumbnail", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -435,12 +444,14 @@ func TestAllocation_EncryptAndUpdateFile(t *testing.T) { const mockLocalPath = "1.txt" a := &Allocation{ - ID: "TestAllocation_Encrypt_And_UpdateFile", - Tx: "TestAllocation_Encrypt_And_UpdateFile", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + ID: "TestAllocation_Encrypt_And_UpdateFile", + Tx: "TestAllocation_Encrypt_And_UpdateFile", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -508,11 +519,13 @@ func TestAllocation_EncryptAndUploadFile(t *testing.T) { defer teardown(t) } a := &Allocation{ - Tx: "TestAllocation_EncryptAndUploadFile", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Tx: "TestAllocation_EncryptAndUploadFile", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -556,12 +569,14 @@ func TestAllocation_EncryptAndUpdateFileWithThumbnail(t *testing.T) { } a := &Allocation{ - ID: "TestAllocation_EncryptAndUpdateFileWithThumbnail", - Tx: "TestAllocation_EncryptAndUpdateFileWithThumbnail", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + ID: "TestAllocation_EncryptAndUpdateFileWithThumbnail", + Tx: "TestAllocation_EncryptAndUpdateFileWithThumbnail", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, } setupMockAllocation(t, a) @@ -633,12 +648,14 @@ func TestAllocation_EncryptAndUploadFileWithThumbnail(t *testing.T) { } a := &Allocation{ - Tx: "TestAllocation_EncryptAndUploadFileWithThumbnail", - ParityShards: 2, - DataShards: 2, - Size: 2 * GB, - ctx: context.TODO(), - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Tx: "TestAllocation_EncryptAndUploadFileWithThumbnail", + ParityShards: 2, + DataShards: 2, + Size: 2 * GB, + Owner: mockClientId, + }, + ctx: context.TODO(), } setupMockAllocation(t, a) diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index 056491c27..8376fddd9 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -363,14 +363,16 @@ func TestPriceRange_IsValid(t *testing.T) { func TestAllocation_InitAllocation(t *testing.T) { a := Allocation{ - FileOptions: 63, + Allocation: commonsdk.Allocation{ + FileOptions: 63, + }, } a.InitAllocation() require.New(t).NotZero(a) } func TestAllocation_dispatchWork(t *testing.T) { - a := Allocation{DataShards: 2, ParityShards: 2, downloadChan: make(chan *DownloadRequest), repairChan: make(chan *RepairRequest)} + a := Allocation{Allocation: commonsdk.Allocation{DataShards: 2, ParityShards: 2}, downloadChan: make(chan *DownloadRequest), repairChan: make(chan *RepairRequest)} t.Run("Test_Cover_Context_Canceled", func(t *testing.T) { ctx, cancelFn := context.WithCancel(context.Background()) go a.dispatchWork(ctx) @@ -388,9 +390,11 @@ func TestAllocation_dispatchWork(t *testing.T) { } func TestAllocation_GetStats(t *testing.T) { - stats := &AllocationStats{} + stats := &commonsdk.AllocationStats{} a := &Allocation{ - Stats: stats, + Allocation: commonsdk.Allocation{ + Stats: stats, + }, } got := a.GetStats() require.New(t).Same(stats, got) @@ -433,8 +437,10 @@ func TestAllocation_GetBlobberStats(t *testing.T) { require := require.New(t) tt.setup(t, tt.name) a := &Allocation{ - ID: mockAllocationId, - Tx: mockAllocationTxId, + Allocation: commonsdk.Allocation{ + ID: mockAllocationId, + Tx: mockAllocationTxId, + }, } a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ ID: tt.name + mockBlobberId, @@ -653,9 +659,11 @@ func TestAllocation_RepairRequired(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) a := &Allocation{ - DataShards: 2, - ParityShards: 2, - FileOptions: 63, + Allocation: commonsdk.Allocation{ + DataShards: 2, + ParityShards: 2, + FileOptions: 63, + }, } a.InitAllocation() client.SetSdkInitialized(true) @@ -780,8 +788,10 @@ func TestAllocation_DownloadFile(t *testing.T) { require := require.New(t) a := &Allocation{ - ParityShards: 2, - DataShards: 2, + Allocation: commonsdk.Allocation{ + ParityShards: 2, + DataShards: 2, + }, } setupMockAllocation(t, a) @@ -827,8 +837,10 @@ func TestAllocation_DownloadFileByBlock(t *testing.T) { require := require.New(t) a := &Allocation{ - ParityShards: 2, - DataShards: 2, + Allocation: commonsdk.Allocation{ + ParityShards: 2, + DataShards: 2, + }, } setupMockAllocation(t, a) @@ -1020,8 +1032,10 @@ func TestAllocation_GetRefs(t *testing.T) { functionName := "TestAllocation_GetRefs" t.Run("Test_Get_Refs_Returns_Slice_Of_Length_0_When_File_Not_Present", func(t *testing.T) { a := &Allocation{ - DataShards: 2, - ParityShards: 2, + Allocation: commonsdk.Allocation{ + DataShards: 2, + ParityShards: 2, + }, } testCaseName := "Test_Get_Refs_Returns_Slice_Of_Length_0_When_File_Not_Present" a.InitAllocation() @@ -1119,9 +1133,11 @@ func TestAllocation_GetFileMeta(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) a := &Allocation{ - DataShards: 2, - ParityShards: 2, - FileOptions: 63, + Allocation: commonsdk.Allocation{ + DataShards: 2, + ParityShards: 2, + FileOptions: 63, + }, } a.InitAllocation() client.SetSdkInitialized(true) @@ -1178,7 +1194,7 @@ func TestAllocation_GetAuthTicketForShare(t *testing.T) { ClientKey: mockClientKey, }) require := require.New(t) - a := &Allocation{DataShards: 1, ParityShards: 1, FileOptions: 63} + a := &Allocation{Allocation: commonsdk.Allocation{DataShards: 1, ParityShards: 1, FileOptions: 63}} a.InitAllocation() for i := 0; i < numberBlobbers; i++ { a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{}) @@ -1381,9 +1397,11 @@ func TestAllocation_GetAuthTicket(t *testing.T) { require := require.New(t) a := &Allocation{ - DataShards: 1, - ParityShards: 1, - FileOptions: 63, + Allocation: commonsdk.Allocation{ + DataShards: 1, + ParityShards: 1, + FileOptions: 63, + }, } a.InitAllocation() client.SetSdkInitialized(true) @@ -1447,7 +1465,7 @@ func TestAllocation_CancelDownload(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { require := require.New(t) - a := &Allocation{FileOptions: 63} + a := &Allocation{Allocation: commonsdk.Allocation{FileOptions: 63}} a.InitAllocation() client.SetSdkInitialized(true) if tt.setup != nil { @@ -1588,11 +1606,13 @@ func TestAllocation_ListDirFromAuthTicket(t *testing.T) { ClientKey: mockClientKey, }) a := &Allocation{ - ID: mockAllocationId, - Tx: mockAllocationTxId, - FileOptions: 63, - DataShards: 2, - ParityShards: 2, + Allocation: commonsdk.Allocation{ + ID: mockAllocationId, + Tx: mockAllocationTxId, + FileOptions: 63, + DataShards: 2, + ParityShards: 2, + }, } if tt.parameters.expectedResult != nil { tt.parameters.expectedResult.deleteMask = zboxutil.NewUint128(1).Lsh(uint64(a.DataShards + a.ParityShards)).Sub64(1) @@ -1642,10 +1662,12 @@ func TestAllocation_downloadFromAuthTicket(t *testing.T) { }) a := &Allocation{ - ID: mockAllocationId, - Tx: mockAllocationTxId, - DataShards: 2, - ParityShards: 2, + Allocation: commonsdk.Allocation{ + ID: mockAllocationId, + Tx: mockAllocationTxId, + DataShards: 2, + ParityShards: 2, + }, } setupMockAllocation(t, a) setupMockGetFileInfoResponse(t, &mockClient) @@ -1868,11 +1890,13 @@ func TestAllocation_listDir(t *testing.T) { require := require.New(t) a := &Allocation{ - ID: mockAllocationId, - Tx: mockAllocationTxId, - FileOptions: 63, - DataShards: 2, - ParityShards: 2, + Allocation: commonsdk.Allocation{ + ID: mockAllocationId, + Tx: mockAllocationTxId, + FileOptions: 63, + DataShards: 2, + ParityShards: 2, + }, } if tt.parameters.expectedResult != nil { tt.parameters.expectedResult.deleteMask = zboxutil.NewUint128(1).Lsh(uint64(a.DataShards + a.ParityShards)).Sub64(1) @@ -2000,11 +2024,13 @@ func TestAllocation_GetFileMetaFromAuthTicket(t *testing.T) { }) a := &Allocation{ - ID: mockAllocationId, - Tx: mockAllocationTxId, - DataShards: 2, - ParityShards: 2, - FileOptions: 63, + Allocation: commonsdk.Allocation{ + ID: mockAllocationId, + Tx: mockAllocationTxId, + DataShards: 2, + ParityShards: 2, + FileOptions: 63, + }, } a.InitAllocation() client.SetSdkInitialized(true) @@ -2240,8 +2266,10 @@ func TestAllocation_StartRepair(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) a := &Allocation{ - DataShards: 2, - ParityShards: 2, + Allocation: commonsdk.Allocation{ + DataShards: 2, + ParityShards: 2, + }, } setupMockAllocation(t, a) for i := 0; i < numBlobbers; i++ { @@ -2379,11 +2407,13 @@ func getMockAuthTicket(t *testing.T) string { ClientKey: mockClientKey, }) a := &Allocation{ - ID: mockAllocationId, - Tx: mockAllocationTxId, - DataShards: 1, - ParityShards: 1, - FileOptions: 63, + Allocation: commonsdk.Allocation{ + ID: mockAllocationId, + Tx: mockAllocationTxId, + DataShards: 1, + ParityShards: 1, + FileOptions: 63, + }, } a.InitAllocation() diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index 8a3b7a60a..a95993c22 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -1,12 +1,11 @@ package sdk import ( - "encoding/json" "math" "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/transaction" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" ) // UpdateAllocation sends an update request for an allocation (txn: `storagesc.update_allocation_request`) @@ -28,7 +27,7 @@ func UpdateAllocation( allocationID string, lock uint64, addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerID, ownerSigninPublicKey string, - setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, ticket string, + setThirdPartyExtendable bool, fileOptionsParams *commonsdk.FileOptionsParameters, ticket string, ) (hash string, nonce int64, err error) { if ownerID == "" { ownerID = client.Id() @@ -47,42 +46,23 @@ func UpdateAllocation( return "", 0, allocationNotFound } - updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = ownerID - updateAllocationRequest["owner_public_key"] = "" - updateAllocationRequest["id"] = allocationID - updateAllocationRequest["size"] = size - updateAllocationRequest["extend"] = extend - updateAllocationRequest["add_blobber_id"] = addBlobberId - updateAllocationRequest["add_blobber_auth_ticket"] = addBlobberAuthTicket - updateAllocationRequest["remove_blobber_id"] = removeBlobberId - updateAllocationRequest["set_third_party_extendable"] = setThirdPartyExtendable - updateAllocationRequest["owner_signing_public_key"] = ownerSigninPublicKey - updateAllocationRequest["file_options_changed"], updateAllocationRequest["file_options"] = calculateAllocationFileOptions(alloc.FileOptions, fileOptionsParams) - updateAllocationRequest["auth_round_expiry"] = authRoundExpiry - - if ticket != "" { - - type Ticket struct { - AllocationID string `json:"allocation_id"` - UserID string `json:"user_id"` - RoundExpiry int64 `json:"round_expiry"` - OperationType string `json:"operation_type"` - Signature string `json:"signature"` - } - - ticketData := &Ticket{} - err := json.Unmarshal([]byte(ticket), ticketData) - if err != nil { - return "", 0, errors.New("invalid_ticket", "invalid ticket") - } - updateAllocationRequest["update_ticket"] = ticketData - } - - sn := transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_UPDATE_ALLOCATION, - InputArgs: updateAllocationRequest, - } - hash, _, nonce, _, err = storageSmartContractTxnValue(sn, lock) + hash, nonce, err = commonsdk.UpdateAllocationWithRequest( + commonsdk.UpdateAllocationOptions{ + Size: size, + Extend: extend, + AllocationID: allocationID, + Lock: lock, + AddBlobberID: addBlobberId, + AddBlobberAuthTicket: addBlobberAuthTicket, + RemoveBlobberID: removeBlobberId, + SetThirdPartyExtendable: setThirdPartyExtendable, + FileOptionsParams: fileOptionsParams, + OwnerID: ownerID, + OwnerSigninPublicKey: ownerSigninPublicKey, + Ticket: ticket, + AuthRoundExpiry: authRoundExpiry, + FileOptions: alloc.FileOptions, + }, + ) return } diff --git a/zboxcore/sdk/chunked_upload_bench_test.go b/zboxcore/sdk/chunked_upload_bench_test.go index dd41d218c..4b8bcdf99 100644 --- a/zboxcore/sdk/chunked_upload_bench_test.go +++ b/zboxcore/sdk/chunked_upload_bench_test.go @@ -10,6 +10,7 @@ import ( "github.com/0chain/gosdk_common/dev" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) @@ -47,7 +48,7 @@ func generateRandomBytes(n int64) []byte { func BenchmarkChunkedUpload(b *testing.B) { - SetLogFile("cmdlog.log", false) + commonsdk.SetLogFile("cmdlog.log", false) logger.Logger.SetLevel(2) @@ -84,12 +85,14 @@ func BenchmarkChunkedUpload(b *testing.B) { b.ResetTimer() a := &Allocation{ - ID: "1a0190c411f3e742c881b7b84c964dc1bb435d459bd3beca74a6c0ae8ececd92", - Tx: "1a0190c411f3e742c881b7b84c964dc1bb435d459bd3beca74a6c0ae8ececd92", - DataShards: 2, - ParityShards: 1, - ctx: context.TODO(), - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + ID: "1a0190c411f3e742c881b7b84c964dc1bb435d459bd3beca74a6c0ae8ececd92", + Tx: "1a0190c411f3e742c881b7b84c964dc1bb435d459bd3beca74a6c0ae8ececd92", + DataShards: 2, + ParityShards: 1, + Owner: mockClientId, + }, + ctx: context.TODO(), } a.fullconsensus, a.consensusThreshold = a.getConsensuses() for i := 0; i < (a.DataShards + a.ParityShards); i++ { diff --git a/zboxcore/sdk/copyworker_test.go b/zboxcore/sdk/copyworker_test.go index b5b22904e..cd43808bd 100644 --- a/zboxcore/sdk/copyworker_test.go +++ b/zboxcore/sdk/copyworker_test.go @@ -21,6 +21,7 @@ import ( devMock "github.com/0chain/gosdk_common/dev/mock" "github.com/0chain/gosdk_common/sdks/blobber" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" @@ -210,7 +211,9 @@ func TestCopyRequest_copyBlobberObject(t *testing.T) { ctx: context.TODO(), connectionID: mockConnectionId, allocationObj: &Allocation{ - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Owner: mockClientId, + }, }, } req.blobbers = append(req.blobbers, &blockchain.StorageNode{ @@ -439,10 +442,12 @@ func TestCopyRequest_ProcessCopy(t *testing.T) { require := require.New(t) a := &Allocation{ - Tx: "TestCopyRequest_ProcessCopy", - DataShards: numBlobbers, - FileOptions: 63, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Tx: "TestCopyRequest_ProcessCopy", + DataShards: numBlobbers, + FileOptions: 63, + Owner: mockClientId, + }, } a.InitAllocation() diff --git a/zboxcore/sdk/deleteworker_test.go b/zboxcore/sdk/deleteworker_test.go index 970e3808d..08172bcc8 100644 --- a/zboxcore/sdk/deleteworker_test.go +++ b/zboxcore/sdk/deleteworker_test.go @@ -18,6 +18,7 @@ import ( "github.com/0chain/gosdk_common/core/resty" "github.com/0chain/gosdk_common/core/zcncrypto" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" @@ -178,7 +179,9 @@ func TestDeleteRequest_deleteBlobberFile(t *testing.T) { connectionID: mockConnectionId, wg: func() *sync.WaitGroup { wg.Add(1); return &wg }(), allocationObj: &Allocation{ - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Owner: mockClientId, + }, }, } req.blobbers = append(req.blobbers, &blockchain.StorageNode{ @@ -379,8 +382,10 @@ func TestDeleteRequest_ProcessDelete(t *testing.T) { req.ctx, req.ctxCncl = context.WithCancel(context.TODO()) a := &Allocation{ - DataShards: numBlobbers, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + DataShards: numBlobbers, + Owner: mockClientId, + }, } for i := 0; i < tt.numBlobbers; i++ { diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index fe4242628..355013112 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -23,6 +23,7 @@ import ( "github.com/0chain/gosdk_common/core/common" "github.com/0chain/gosdk_common/core/sys" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/encryption" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/logger" @@ -1081,7 +1082,7 @@ type blobberFile struct { func GetFileRefFromBlobber(allocationID, blobberId, remotePath string) (fRef *fileref.FileRef, err error) { wg := &sync.WaitGroup{} wg.Add(1) - blobber, err := GetBlobber(blobberId) + blobber, err := commonsdk.GetBlobber(blobberId) if err != nil { return nil, err } diff --git a/zboxcore/sdk/renameworker_test.go b/zboxcore/sdk/renameworker_test.go index eb17bbcdb..a890f7470 100644 --- a/zboxcore/sdk/renameworker_test.go +++ b/zboxcore/sdk/renameworker_test.go @@ -21,6 +21,7 @@ import ( devMock "github.com/0chain/gosdk_common/dev/mock" "github.com/0chain/gosdk_common/sdks/blobber" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" "github.com/0chain/gosdk_common/zboxcore/zboxutil" "github.com/stretchr/testify/mock" @@ -226,7 +227,9 @@ func TestRenameRequest_renameBlobberObject(t *testing.T) { tt.setup(t, tt.name, tt.parameters) req := &RenameRequest{ allocationObj: &Allocation{ - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Owner: mockClientId, + }, }, allocationID: mockAllocationId, allocationTx: mockAllocationTxId, @@ -461,9 +464,11 @@ func TestRenameRequest_ProcessRename(t *testing.T) { require := require.New(t) a := &Allocation{ - Tx: "TestRenameRequest_ProcessRename", - DataShards: numBlobbers, - Owner: mockClientId, + Allocation: commonsdk.Allocation{ + Tx: "TestRenameRequest_ProcessRename", + DataShards: numBlobbers, + Owner: mockClientId, + }, } setupMockAllocation(t, a) diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 828641fd2..cdde2af15 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -4,27 +4,15 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io" - "math" - "net/http" - "strconv" - "github.com/0chain/common/core/currency" "github.com/0chain/errors" - "github.com/0chain/gosdk_common/core/logger" "github.com/0chain/gosdk_common/core/screstapi" - "gopkg.in/natefinch/lumberjack.v2" + "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/core/client" - "github.com/0chain/gosdk_common/core/common" - "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/core/version" - "github.com/0chain/gosdk_common/zboxcore/blockchain" "github.com/0chain/gosdk_common/zboxcore/commonsdk" - "github.com/0chain/gosdk_common/zboxcore/encryption" - l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/marker" - "github.com/0chain/gosdk_common/zboxcore/zboxutil" ) const STORAGE_SCADDRESS = "6dba10422e368813802877a85039d3985d96760ed844092319743fb3a76712d7" @@ -70,523 +58,6 @@ func GetVersion() string { return version.VERSIONSTR } -// SetLogLevel set the log level. -// - lvl: 0 disabled; higher number (upto 4) more verbosity -func SetLogLevel(lvl int) { - l.Logger.SetLevel(lvl) -} - -// 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, - MaxSize: 100, // MB - MaxBackups: 5, // number of backups - MaxAge: 28, //days - LocalTime: false, - Compress: false, // disabled by default - } - - l.Logger.SetLogFile(ioWriter, verbose) - l.Logger.Info("******* Storage SDK Version: ", version.VERSIONSTR, " *******") -} - -// GetLogger retrieves logger instance -func GetLogger() *logger.Logger { - return l.Logger -} - -type BackPool struct { - ID string `json:"id"` - Balance common.Balance `json:"balance"` -} - -// -// stake pool -// - -// StakePoolOfferInfo represents stake pool offer information. -type StakePoolOfferInfo struct { - Lock common.Balance `json:"lock"` - Expire common.Timestamp `json:"expire"` - AllocationID common.Key `json:"allocation_id"` - IsExpired bool `json:"is_expired"` -} - -// StakePoolRewardsInfo represents stake pool rewards. -type StakePoolRewardsInfo struct { - Charge common.Balance `json:"charge"` // total for all time - Blobber common.Balance `json:"blobber"` // total for all time - Validator common.Balance `json:"validator"` // total for all time -} - -// StakePoolDelegatePoolInfo represents delegate pool of a stake pool info. -type StakePoolDelegatePoolInfo struct { - ID common.Key `json:"id"` // blobber ID - Balance common.Balance `json:"balance"` // current balance - DelegateID common.Key `json:"delegate_id"` // wallet - Rewards common.Balance `json:"rewards"` // current - UnStake bool `json:"unstake"` // want to unstake - - TotalReward common.Balance `json:"total_reward"` - TotalPenalty common.Balance `json:"total_penalty"` - Status string `json:"status"` - RoundCreated int64 `json:"round_created"` - StakedAt common.Timestamp `json:"staked_at"` -} - -// 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 - StakeTotal common.Balance `json:"stake_total"` - // delegate pools - Delegate []StakePoolDelegatePoolInfo `json:"delegate"` - // rewards - Rewards common.Balance `json:"rewards"` - // total rewards - TotalRewards common.Balance `json:"total_rewards"` - // Settings of the stake pool - Settings blockchain.StakePoolSettings `json:"settings"` -} - -// 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 !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - - var b []byte - b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getStakePoolStat", - map[string]string{"provider_type": strconv.Itoa(int(providerType)), "provider_id": providerID}) - if err != nil { - return nil, errors.Wrap(err, "error requesting stake pool info:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - info = new(StakePoolInfo) - if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "3 error decoding response:") - } - - return -} - -// StakePoolUserInfo represents user stake pools statistic. -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. -// - clientID: client ID -// - offset: offset -// - limit: limit -func GetStakePoolUserInfo(clientID string, offset, limit int) (info *StakePoolUserInfo, err error) { - if !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - if clientID == "" { - clientID = client.Id() - } - - var b []byte - params := map[string]string{ - "client_id": clientID, - "offset": strconv.FormatInt(int64(offset), 10), - "limit": strconv.FormatInt(int64(limit), 10), - } - b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/getUserStakePoolStat", params) - if err != nil { - return nil, errors.Wrap(err, "error requesting stake pool user info:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - info = new(StakePoolUserInfo) - if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "4 error decoding response:") - } - - return -} - -type stakePoolRequest struct { - ProviderType ProviderType `json:"provider_type,omitempty"` - ProviderID string `json:"provider_id,omitempty"` - ClientID string `json:"client_id,omitempty"` -} - -// stakePoolLock is stake pool unlock response in case where tokens -// can't be unlocked due to opened offers. -type stakePoolLock struct { - Client string `json:"client"` - ProviderId string `json:"provider_id"` - ProviderType ProviderType `json:"provider_type"` - Amount int64 `json:"amount"` -} - -// -// challenge pool -// - -// ChallengePoolInfo represents a challenge pool stat. -type ChallengePoolInfo struct { - ID string `json:"id"` - Balance common.Balance `json:"balance"` - StartTime common.Timestamp `json:"start_time"` - Expiration common.Timestamp `json:"expiration"` - Finalized bool `json:"finalized"` -} - -// GetChallengePoolInfo retrieve challenge pool info for given allocation. -// - allocID: allocation ID -func GetChallengePoolInfo(allocID string) (info *ChallengePoolInfo, err error) { - if !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - - var b []byte - b, err = screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/getChallengePoolStat", map[string]string{"allocation_id": allocID}) - if err != nil { - return nil, errors.Wrap(err, "error requesting challenge pool info:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - info = new(ChallengePoolInfo) - if err = json.Unmarshal(b, info); err != nil { - return nil, errors.Wrap(err, "5 error decoding response:") - } - - return -} - -// GetMptData retrieves mpt key data. -func GetMptData(key string) ([]byte, error) { - if !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - - var b []byte - b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, - "/get_mpt_key", map[string]string{"key": key}, - ) - if err != nil { - return nil, errors.Wrap(err, "error requesting mpt key data:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - return b, nil -} - -// Blobber type represents blobber information. -type Blobber struct { - // ID of the blobber - ID common.Key `json:"id"` - - // BaseURL of the blobber - BaseURL string `json:"url"` - - // Terms of the blobber - Terms commonsdk.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. -// Note the types are of pointer types with omitempty json property. -// This is done to correctly identify which properties are actually changing. -type UpdateBlobber struct { - ID common.Key `json:"id"` - BaseURL *string `json:"url,omitempty"` - Terms *commonsdk.UpdateTerms `json:"terms,omitempty"` - Capacity *common.Size `json:"capacity,omitempty"` - Allocated *common.Size `json:"allocated,omitempty"` - LastHealthCheck *common.Timestamp `json:"last_health_check,omitempty"` - StakePoolSettings *blockchain.UpdateStakePoolSettings `json:"stake_pool_settings,omitempty"` - TotalStake *int64 `json:"total_stake,omitempty"` - UsedAllocation *int64 `json:"used_allocation,omitempty"` - TotalOffers *int64 `json:"total_offers,omitempty"` - TotalServiceCharge *int64 `json:"total_service_charge,omitempty"` - UncollectedServiceCharge *int64 `json:"uncollected_service_charge,omitempty"` - IsKilled *bool `json:"is_killed,omitempty"` - IsShutdown *bool `json:"is_shutdown,omitempty"` - NotAvailable *bool `json:"not_available,omitempty"` - IsRestricted *bool `json:"is_restricted,omitempty"` - StorageVersion *int `json:"storage_version,omitempty"` - DelegateWallet *string `json:"delegate_wallet,omitempty"` -} - -// ResetBlobberStatsDto represents blobber stats reset request. -type ResetBlobberStatsDto struct { - BlobberID string `json:"blobber_id"` - PrevAllocated int64 `json:"prev_allocated"` - PrevSavedData int64 `json:"prev_saved_data"` - NewAllocated int64 `json:"new_allocated"` - NewSavedData int64 `json:"new_saved_data"` -} - -// Validator represents validator information. -type Validator struct { - ID common.Key `json:"validator_id"` - BaseURL string `json:"url"` - PublicKey string `json:"-"` - 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"` - StakeTotal int64 `json:"stake_total"` - TotalServiceCharge int64 `json:"total_service_charge"` - UncollectedServiceCharge int64 `json:"uncollected_service_charge"` - LastHealthCheck common.Timestamp `json:"last_health_check"` - IsKilled bool `json:"is_killed"` - 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"` - DelegateWallet *string `json:"delegate_wallet,omitempty"` - MinStake *common.Balance `json:"min_stake,omitempty"` - MaxStake *common.Balance `json:"max_stake,omitempty"` - NumDelegates *int `json:"num_delegates,omitempty"` - ServiceCharge *float64 `json:"service_charge,omitempty"` - StakeTotal *int64 `json:"stake_total,omitempty"` - TotalServiceCharge *int64 `json:"total_service_charge,omitempty"` - UncollectedServiceCharge *int64 `json:"uncollected_service_charge,omitempty"` - LastHealthCheck *common.Timestamp `json:"last_health_check,omitempty"` - IsKilled *bool `json:"is_killed,omitempty"` - 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), - BaseURL: v.BaseURL, - } - - sp := &blockchain.UpdateStakePoolSettings{ - DelegateWallet: v.DelegateWallet, - NumDelegates: v.NumDelegates, - ServiceCharge: v.ServiceCharge, - } - - if v.DelegateWallet != nil || - v.MinStake != nil || - v.MaxStake != nil || - v.NumDelegates != nil || - v.ServiceCharge != nil { - blockValidator.StakePoolSettings = sp - } - - return blockValidator -} - -func getBlobbersInternal(active, stakable bool, limit, offset int) (bs []*Blobber, err error) { - type nodes struct { - Nodes []*Blobber - } - - b, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/getblobbers", map[string]string{"active": strconv.FormatBool(active), "limit": strconv.FormatInt(int64(limit), 10), - "offset": strconv.FormatInt(int64(offset), 10), - "stakable": strconv.FormatBool(stakable)}) - var wrap nodes - if err != nil { - return nil, errors.Wrap(err, "error requesting blobbers:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response") - } - - if err = json.Unmarshal(b, &wrap); err != nil { - return nil, errors.Wrap(err, "6 error decoding response:") - } - - 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 !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - - limit, offset := 20, 0 - - blobbers, err := getBlobbersInternal(active, stakable, limit, offset) - if err != nil { - return nil, err - } - - var blobbersSl []*Blobber - blobbersSl = append(blobbersSl, blobbers...) - for { - // if the len of output returned is less than the limit it means this is the last round of pagination - if len(blobbers) < limit { - break - } - - // get the next set of blobbers - offset += 20 - blobbers, err = getBlobbersInternal(active, stakable, limit, offset) - if err != nil { - return blobbers, err - } - blobbersSl = append(blobbersSl, blobbers...) - - } - return blobbersSl, nil -} - -// GetBlobber retrieve blobber by id. -// - blobberID: the id of blobber -func GetBlobber(blobberID string) (blob *Blobber, err error) { - if !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - var b []byte - b, err = screstapi.MakeSCRestAPICall( - STORAGE_SCADDRESS, - "/getBlobber", - map[string]string{"blobber_id": blobberID}, - ) - if err != nil { - return nil, errors.Wrap(err, "requesting blobber:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response from sharders") - } - blob = new(Blobber) - if err = json.Unmarshal(b, blob); err != nil { - return nil, errors.Wrap(err, "decoding response:") - } - return -} - -// GetValidator retrieve validator instance by id. -// - validatorID: the id of validator -func GetValidator(validatorID string) (validator *Validator, err error) { - if !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - var b []byte - b, err = screstapi.MakeSCRestAPICall( - STORAGE_SCADDRESS, - "/get_validator", - map[string]string{"validator_id": validatorID}, - ) - if err != nil { - return nil, errors.Wrap(err, "requesting validator:") - } - if len(b) == 0 { - return nil, errors.New("", "empty response from sharders") - } - validator = new(Validator) - if err = json.Unmarshal(b, validator); err != nil { - return nil, errors.Wrap(err, "decoding response:") - } - return -} - -// GetValidators returns list of validators. -// - stakable: if true then only stakable validators are returned -func GetValidators(stakable bool) (validators []*Validator, err error) { - if !client.IsSDKInitialized() { - return nil, sdkNotInitialized - } - var b []byte - b, err = screstapi.MakeSCRestAPICall( - STORAGE_SCADDRESS, - "/validators", - map[string]string{ - "stakable": strconv.FormatBool(stakable), - }, - ) - if err != nil { - return nil, errors.Wrap(err, "requesting validator list") - } - if len(b) == 0 { - return nil, errors.New("", "empty response from sharders") - } - if err = json.Unmarshal(b, &validators); err != nil { - return nil, errors.Wrap(err, "decoding response:") - } - return -} - -// GetClientEncryptedPublicKey - get the client's public key -func GetClientEncryptedPublicKey() (string, error) { - if !client.IsSDKInitialized() { - return "", sdkNotInitialized - } - encScheme := encryption.NewEncryptionScheme() - _, err := encScheme.Initialize(client.Wallet().Mnemonic) - if err != nil { - return "", err - } - 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 @@ -763,378 +234,6 @@ func GetAllocationsForClient(clientID string) ([]*Allocation, error) { return allocationsFin, nil } -type FileOptionParam struct { - Changed bool - 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 - ForbidUpdate FileOptionParam - ForbidMove FileOptionParam - ForbidCopy FileOptionParam - ForbidRename FileOptionParam -} - -// CreateAllocationOptions is used to specify the options for creating a new allocation. -type CreateAllocationOptions struct { - DataShards int - ParityShards int - Size int64 - ReadPrice commonsdk.PriceRange - WritePrice commonsdk.PriceRange - Lock uint64 - BlobberIds []string - BlobberAuthTickets []string - ThirdPartyExtendable bool - IsEnterprise bool - FileOptionsParams *commonsdk.FileOptionsParameters - Force bool - StorageVersion int - AuthRoundExpiry int64 -} - -// 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 commonsdk.CreateAllocationForOwner(client.Id(), - client.PublicKey(), options.DataShards, options.ParityShards, - options.Size, options.ReadPrice, options.WritePrice, options.Lock, - options.BlobberIds, options.BlobberAuthTickets, options.ThirdPartyExtendable, options.IsEnterprise, options.Force, options.FileOptionsParams, options.AuthRoundExpiry) -} - -// 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( - storageVersion, datashards, parityshards int, - size int64, - isRestricted int, - readPrice, writePrice commonsdk.PriceRange, - force ...bool, -) ([]string, error) { - var allocationRequest = map[string]interface{}{ - "data_shards": datashards, - "parity_shards": parityshards, - "size": size, - "read_price_range": readPrice, - "write_price_range": writePrice, - "is_restricted": isRestricted, - "storage_version": storageVersion, - } - - allocationData, _ := json.Marshal(allocationRequest) - - params := make(map[string]string) - params["allocation_data"] = string(allocationData) - if len(force) > 0 && force[0] { - params["force"] = strconv.FormatBool(force[0]) - } - - allocBlobber, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params) - if err != nil { - return nil, err - } - var allocBlobberIDs []string - - err = json.Unmarshal(allocBlobber, &allocBlobberIDs) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal blobber IDs") - } - - return allocBlobberIDs, nil -} - -func getNewAllocationBlobbers( - storageVersion, datashards, parityshards int, - size int64, - readPrice, writePrice commonsdk.PriceRange, - preferredBlobberIds, blobberAuthTickets []string, force bool, -) (map[string]interface{}, error) { - for _, authTicket := range blobberAuthTickets { - if len(authTicket) > 0 { - return map[string]interface{}{ - "data_shards": datashards, - "parity_shards": parityshards, - "size": size, - "blobbers": preferredBlobberIds, - "blobber_auth_tickets": blobberAuthTickets, - "read_price_range": readPrice, - "write_price_range": writePrice, - "storage_version": storageVersion, - }, nil - } - } - - allocBlobberIDs, err := GetAllocationBlobbers( - storageVersion, datashards, parityshards, size, 2, readPrice, writePrice, force, - ) - if err != nil { - return nil, err - } - - blobbers := append(preferredBlobberIds, allocBlobberIDs...) - - // filter duplicates - ids := make(map[string]bool) - uniqueBlobbers := []string{} - uniqueBlobberAuthTickets := []string{} - - for _, b := range blobbers { - if !ids[b] { - uniqueBlobbers = append(uniqueBlobbers, b) - uniqueBlobberAuthTickets = append(uniqueBlobberAuthTickets, "") - ids[b] = true - } - } - - return map[string]interface{}{ - "data_shards": datashards, - "parity_shards": parityshards, - "size": size, - "blobbers": uniqueBlobbers, - "blobber_auth_tickets": uniqueBlobberAuthTickets, - "read_price_range": readPrice, - "write_price_range": writePrice, - "storage_version": storageVersion, - }, 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 { - return nil, nil - } - - urlsStr, err := json.Marshal(blobberUrls) - if err != nil { - return nil, err - } - - params := make(map[string]string) - params["blobber_urls"] = string(urlsStr) - idsStr, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/blobber_ids", params) - if err != nil { - return nil, err - } - - var blobberIDs []string - err = json.Unmarshal(idsStr, &blobberIDs) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal preferred blobber IDs") - } - - 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) - - params := make(map[string]string) - params["free_allocation_data"] = string(data) - - allocBlobber, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/free_alloc_blobbers", params) - if err != nil { - return nil, err - } - var allocBlobberIDs []string - - err = json.Unmarshal(allocBlobber, &allocBlobberIDs) - if err != nil { - return nil, errors.Wrap(err, "failed to unmarshal blobber IDs") - } - - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var input = map[string]interface{}{ - "name": name, - "public_key": publicKey, - "individual_limit": individualLimit, - "total_limit": totalLimit, - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.ADD_FREE_ALLOCATION_ASSIGNER, - InputArgs: input, - } - hash, _, n, _, err := storageSmartContractTxn(sn) - - return hash, n, err -} - -// 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_FINALIZE_ALLOCATION, - InputArgs: map[string]interface{}{"allocation_id": allocID}, - } - hash, _, nonce, _, err = storageSmartContractTxn(sn) - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_CANCEL_ALLOCATION, - InputArgs: map[string]interface{}{"allocation_id": allocID}, - } - hash, _, nonce, _, err = storageSmartContractTxn(sn) - return -} - -// ProviderType is the type of the provider. -type ProviderType int - -const ( - ProviderMiner ProviderType = iota + 1 - ProviderSharder - ProviderBlobber - ProviderValidator - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var input = map[string]interface{}{ - "provider_id": providerId, - } - var sn = transaction.SmartContractTxnData{ - InputArgs: input, - } - switch providerType { - case ProviderBlobber: - sn.Name = transaction.STORAGESC_KILL_BLOBBER - case ProviderValidator: - sn.Name = transaction.STORAGESC_KILL_VALIDATOR - default: - return "", 0, fmt.Errorf("kill provider type %v not implimented", providerType) - } - hash, _, n, _, err := storageSmartContractTxn(sn) - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var input = map[string]interface{}{ - "provider_id": providerID, - } - - var sn = transaction.SmartContractTxnData{ - InputArgs: input, - } - switch providerType { - case ProviderBlobber: - sn.Name = transaction.STORAGESC_SHUTDOWN_BLOBBER - case ProviderValidator: - sn.Name = transaction.STORAGESC_SHUTDOWN_VALIDATOR - default: - return "", 0, fmt.Errorf("shutdown provider type %v not implimented", providerType) - } - hash, _, n, _, err := storageSmartContractTxn(sn) - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var input = map[string]interface{}{ - "provider_id": providerId, - "provider_type": providerType, - } - - var sn = transaction.SmartContractTxnData{ - InputArgs: input, - } - - var scAddress string - switch providerType { - case ProviderBlobber, ProviderValidator: - scAddress = STORAGE_SCADDRESS - sn.Name = transaction.STORAGESC_COLLECT_REWARD - case ProviderMiner, ProviderSharder: - scAddress = MINERSC_SCADDRESS - sn.Name = transaction.MINERSC_COLLECT_REWARD - // case ProviderAuthorizer: - // scAddress = ZCNSC_SCADDRESS - // sn.Name = transaction.ZCNSC_COLLECT_REWARD - default: - return "", 0, fmt.Errorf("collect rewards provider type %v not implimented", providerType) - } - - hash, _, n, _, err := transaction.SmartContractTxn(scAddress, sn, true) - 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. @@ -1169,297 +268,6 @@ func TransferAllocation(allocationId, newOwner, newOwnerPublicKey string) (strin Name: transaction.STORAGESC_UPDATE_ALLOCATION, InputArgs: allocationRequest, } - hash, _, n, _, err := storageSmartContractTxn(sn) - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_UPDATE_BLOBBER_SETTINGS, - InputArgs: blob, - } - resp, _, nonce, _, err = storageSmartContractTxn(sn) - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_UPDATE_VALIDATOR_SETTINGS, - InputArgs: v.ConvertToValidationNode(), - } - resp, _, nonce, _, err = storageSmartContractTxn(sn) - 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 !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_RESET_BLOBBER_STATS, - InputArgs: rbs, - } - hash, _, n, _, err := storageSmartContractTxn(sn) - return hash, n, err -} - -type StorageNodeIdField struct { - Id string `json:"id"` -} - -func ResetBlobberVersion(snId *StorageNodeIdField) (string, int64, error) { - if !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_RESET_BLOBBER_VERSION, - InputArgs: snId, - } - hash, _, n, _, err := storageSmartContractTxn(sn) - return hash, n, err -} - -func InsertKilledProviderID(snId *StorageNodeIdField) (string, int64, error) { - if !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_INSERT_KILLED_PROVIDER_ID, - InputArgs: snId, - } - hash, _, n, _, err := storageSmartContractTxn(sn) + hash, _, n, _, err := commonsdk.StorageSmartContractTxn(sn) return hash, n, err } - -func ResetAllocationStats(allocationId string) (string, int64, error) { - if !client.IsSDKInitialized() { - return "", 0, sdkNotInitialized - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_RESET_ALLOCATION_STATS, - InputArgs: allocationId, - } - hash, _, n, _, err := storageSmartContractTxn(sn) - return hash, n, err -} - -func StorageSmartContractTxn(sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return storageSmartContractTxnValue(sn, 0) -} - -func storageSmartContractTxn(sn transaction.SmartContractTxnData) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - return storageSmartContractTxnValue(sn, 0) -} - -func storageSmartContractTxnValue(sn transaction.SmartContractTxnData, value uint64) ( - hash, out string, nonce int64, txn *transaction.Transaction, err error) { - - // Fee is set during sdk initialization. - return transaction.SmartContractTxnValueFeeWithRetry(STORAGE_SCADDRESS, sn, value, client.TxnFee(), true) -} - -func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { - if !client.IsSDKInitialized() { - return "", sdkNotInitialized - } - var fabricConfig struct { - URL string `json:"url"` - Body struct { - Channel string `json:"channel"` - ChaincodeName string `json:"chaincode_name"` - ChaincodeVersion string `json:"chaincode_version"` - Method string `json:"method"` - Args []string `json:"args"` - } `json:"body"` - Auth struct { - Username string `json:"username"` - Password string `json:"password"` - } `json:"auth"` - } - - err := json.Unmarshal([]byte(fabricConfigJSON), &fabricConfig) - if err != nil { - return "", errors.New("fabric_config_decode_error", "Unable to decode fabric config json") - } - - // Clear if any existing args passed - fabricConfig.Body.Args = fabricConfig.Body.Args[:0] - - fabricConfig.Body.Args = append(fabricConfig.Body.Args, metaTxnData) - - fabricData, err := json.Marshal(fabricConfig.Body) - if err != nil { - return "", errors.New("fabric_config_encode_error", "Unable to encode fabric config body") - } - - req, ctx, cncl, err := zboxutil.NewHTTPRequest(http.MethodPost, fabricConfig.URL, fabricData) - if err != nil { - return "", errors.New("fabric_commit_error", "Unable to create new http request with error "+err.Error()) - } - - // Set basic auth - req.SetBasicAuth(fabricConfig.Auth.Username, fabricConfig.Auth.Password) - - var fabricResponse string - err = zboxutil.HttpDo(ctx, cncl, req, func(resp *http.Response, err error) error { - if err != nil { - l.Logger.Error("Fabric commit error : ", err) - return err - } - defer resp.Body.Close() - respBody, err := io.ReadAll(resp.Body) - if err != nil { - return errors.Wrap(err, "Error reading response :") - } - l.Logger.Debug("Fabric commit result:", string(respBody)) - if resp.StatusCode == http.StatusOK { - fabricResponse = string(respBody) - return nil - } - return errors.New(strconv.Itoa(resp.StatusCode), "Fabric commit status not OK!") - }) - return fabricResponse, err -} - -// 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, - writePrice commonsdk.PriceRange, -) (int64, error) { - baSize := int64(math.Ceil(float64(size) / float64(datashards))) - totalSize := baSize * int64(datashards+parityshards) - - sizeInGB := float64(totalSize) / GB - - cost := sizeInGB * float64(writePrice.Max) - coin, err := currency.Float64ToCoin(cost) - if err != nil { - return 0, err - } - i, err := coin.Int64() - if err != nil { - return 0, err - } - 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, - extend bool, - addBlobberId, - removeBlobberId string) (int64, error) { - updateAllocationRequest := make(map[string]interface{}) - updateAllocationRequest["owner_id"] = client.Id() - updateAllocationRequest["owner_public_key"] = "" - updateAllocationRequest["id"] = allocationID - updateAllocationRequest["size"] = size - updateAllocationRequest["extend"] = extend - updateAllocationRequest["add_blobber_id"] = addBlobberId - updateAllocationRequest["remove_blobber_id"] = removeBlobberId - - data, err := json.Marshal(updateAllocationRequest) - if err != nil { - return 0, errors.Wrap(err, "failed to encode request into json") - } - - params := make(map[string]string) - params["data"] = string(data) - - responseBytes, err := screstapi.MakeSCRestAPICall(STORAGE_SCADDRESS, "/allocation-update-min-lock", params) - if err != nil { - return 0, errors.Wrap(err, "failed to request allocation update min lock") - } - - var response = make(map[string]int64) - if err = json.Unmarshal(responseBytes, &response); err != nil { - return 0, errors.Wrap(err, fmt.Sprintf("failed to decode response: %s", string(responseBytes))) - } - - v, ok := response["min_lock_demand"] - if !ok { - return 0, errors.New("", "min_lock_demand not found in response") - } - return v, nil -} - -// calculateAllocationFileOptions calculates the FileOptions 16-bit mask given the user input -func calculateAllocationFileOptions(initial uint16, fop *FileOptionsParameters) (bool, uint16) { - if fop == nil { - return false, initial - } - - mask := initial - - if fop.ForbidUpload.Changed { - mask = updateMaskBit(mask, 0, !fop.ForbidUpload.Value) - } - - if fop.ForbidDelete.Changed { - mask = updateMaskBit(mask, 1, !fop.ForbidDelete.Value) - } - - if fop.ForbidUpdate.Changed { - mask = updateMaskBit(mask, 2, !fop.ForbidUpdate.Value) - } - - if fop.ForbidMove.Changed { - mask = updateMaskBit(mask, 3, !fop.ForbidMove.Value) - } - - if fop.ForbidCopy.Changed { - mask = updateMaskBit(mask, 4, !fop.ForbidCopy.Value) - } - - if fop.ForbidRename.Changed { - mask = updateMaskBit(mask, 5, !fop.ForbidRename.Value) - } - - return mask != initial, mask -} - -// updateMaskBit Set/Clear (based on `value`) bit value of the bit of `mask` at `index` (starting with LSB as 0) and return the updated mask -func updateMaskBit(mask uint16, index uint8, value bool) uint16 { - if value { - return mask | uint16(1< Date: Tue, 4 Feb 2025 12:43:00 +0530 Subject: [PATCH 096/107] refactor --- go.mod | 4 ++-- go.sum | 4 ++-- zboxcore/sdk/sdk.go | 30 ++++++++++-------------------- 3 files changed, 14 insertions(+), 24 deletions(-) diff --git a/go.mod b/go.mod index 6aec70d88..8dcdd6dbb 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/lithammer/shortuuid/v3 v3.0.7 github.com/machinebox/graphql v0.2.2 // indirect github.com/mitchellh/go-homedir v1.1.0 - github.com/mitchellh/mapstructure v1.5.0 + github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/pkg/errors v0.9.1 github.com/shopspring/decimal v1.3.1 // indirect github.com/spf13/viper v1.15.0 // indirect @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250203211137-32f7f9862646 + github.com/0chain/gosdk_common v0.0.0-20250204070817-3c82b7ad6a9f github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index e3b27bd72..4c5e2326f 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250203211137-32f7f9862646 h1:xya8sojAMIjOH3tZ8KTplvnY5rkHI0ZVeGlxo4HeQLs= -github.com/0chain/gosdk_common v0.0.0-20250203211137-32f7f9862646/go.mod h1:aGBabvKYk/B6G6bEBI8j1cBaWY2is9sCii88Ly6VeCU= +github.com/0chain/gosdk_common v0.0.0-20250204070817-3c82b7ad6a9f h1:H3Edk0y4Q8GEsPAbIsmn+WKiTC/uA4L/YuX0x/3Adz0= +github.com/0chain/gosdk_common v0.0.0-20250204070817-3c82b7ad6a9f/go.mod h1:aGBabvKYk/B6G6bEBI8j1cBaWY2is9sCii88Ly6VeCU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index cdde2af15..6036a8735 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -7,7 +7,6 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/screstapi" - "github.com/0chain/gosdk_common/core/transaction" "github.com/0chain/gosdk_common/core/client" "github.com/0chain/gosdk_common/core/version" @@ -251,23 +250,14 @@ func TransferAllocation(allocationId, newOwner, newOwnerPublicKey string) (strin return "", 0, allocationNotFound } - var allocationRequest = map[string]interface{}{ - "id": allocationId, - "owner_id": newOwner, - "owner_public_key": newOwnerPublicKey, - "size": 0, - "expiration_date": 0, - "update_terms": false, - "add_blobber_id": "", - "remove_blobber_id": "", - "set_third_party_extendable": alloc.ThirdPartyExtendable, - "file_options_changed": false, - "file_options": alloc.FileOptions, - } - var sn = transaction.SmartContractTxnData{ - Name: transaction.STORAGESC_UPDATE_ALLOCATION, - InputArgs: allocationRequest, - } - hash, _, n, _, err := commonsdk.StorageSmartContractTxn(sn) - return hash, n, err + return commonsdk.TransferAllocation( + commonsdk.UpdateAllocationOptions{ + AllocationID: allocationId, + OwnerID: newOwner, + OwnerPublicKey: newOwnerPublicKey, + SetThirdPartyExtendable: alloc.ThirdPartyExtendable, + FileOptions: alloc.FileOptions, + }, + ) + } From 5586b1ee41203d3e8c0af91112b7b86e5178e1c6 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Thu, 27 Feb 2025 18:29:07 +0530 Subject: [PATCH 097/107] added gosdk leftover changes --- zboxcore/sdk/allocation.go | 24 +++++- zboxcore/sdk/blobber_operations.go | 22 +++++ zboxcore/sdk/chunked_upload_model.go | 2 + zboxcore/sdk/downloadworker.go | 120 ++++++++++++++++++++------- zboxcore/sdk/filerefsworker.go | 2 + zboxcore/sdk/reader.go | 2 +- 6 files changed, 141 insertions(+), 31 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 009209bba..6481664cb 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -3,6 +3,7 @@ package sdk import ( "bytes" "context" + "crypto/ed25519" "encoding/base64" "encoding/json" "fmt" @@ -165,7 +166,9 @@ type Allocation struct { consensusThreshold int fullconsensus int allocationVersion int64 - sig string `json:"-"` + sig string `json:"-"` + allocationRoot string `json:"-"` + privateSigningKey ed25519.PrivateKey `json:"-"` } // OperationRequest represents an operation request with its related options. @@ -1196,6 +1199,17 @@ func (a *Allocation) generateDownloadRequest( downloadReq.allocOwnerID = a.Owner downloadReq.sig = a.sig downloadReq.allocOwnerPubKey = a.OwnerPublicKey + downloadReq.allocOwnerSigningPubKey = a.OwnerSigningPublicKey + if len(a.privateSigningKey) == 0 { + sk, err := generateOwnerSigningKey(client.PublicKey(), client.Id()) + if err != nil { + return nil, err + } + downloadReq.allocOwnerSigningPrivateKey = sk + } else { + downloadReq.allocOwnerSigningPrivateKey = a.privateSigningKey + } + logger.Logger.Debug("Download req private key", downloadReq.allocOwnerSigningPrivateKey) downloadReq.ctx, downloadReq.ctxCncl = context.WithCancel(a.ctx) downloadReq.fileHandler = fileHandler downloadReq.localFilePath = localFilePath @@ -1299,7 +1313,6 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { } wg.Wait() elapsedProcessDownloadRequest := time.Since(now) - // Do not send readmarkers for free reads if a.readFree { for _, dr := range drs { @@ -2641,6 +2654,13 @@ func (a *Allocation) downloadFromAuthTicket(fileHandler sys.File, authTicket str downloadReq.sig = a.sig downloadReq.allocOwnerID = a.Owner downloadReq.allocOwnerPubKey = a.OwnerPublicKey + downloadReq.allocOwnerSigningPubKey = a.OwnerSigningPublicKey + //for auth ticket set your own signing key + sk, err := generateOwnerSigningKey(client.PublicKey(), client.Id()) + if err != nil { + return err + } + downloadReq.allocOwnerSigningPrivateKey = sk downloadReq.ctx, downloadReq.ctxCncl = context.WithCancel(a.ctx) downloadReq.fileHandler = fileHandler downloadReq.localFilePath = localFilePath diff --git a/zboxcore/sdk/blobber_operations.go b/zboxcore/sdk/blobber_operations.go index a95993c22..c109157b4 100644 --- a/zboxcore/sdk/blobber_operations.go +++ b/zboxcore/sdk/blobber_operations.go @@ -1,11 +1,17 @@ package sdk import ( + "crypto/ed25519" + "encoding/hex" + "fmt" "math" "github.com/0chain/errors" "github.com/0chain/gosdk_common/core/client" + "github.com/0chain/gosdk_common/core/encryption" "github.com/0chain/gosdk_common/zboxcore/commonsdk" + "github.com/0chain/gosdk_common/zboxcore/logger" + "go.uber.org/zap" ) // UpdateAllocation sends an update request for an allocation (txn: `storagesc.update_allocation_request`) @@ -66,3 +72,19 @@ func UpdateAllocation( ) return } + +func generateOwnerSigningKey(ownerPublicKey, ownerID string) (ed25519.PrivateKey, error) { + if ownerPublicKey == "" { + return nil, errors.New("owner_public_key_required", "owner public key is required") + } + hashData := fmt.Sprintf("%s:%s", ownerPublicKey, "owner_signing_public_key") + sig, err := client.Sign(encryption.Hash(hashData), ownerID) + if err != nil { + logger.Logger.Error("error during sign", zap.Error(err)) + return nil, err + } + //use this signature as entropy to generate ecdsa key pair + decodedSig, _ := hex.DecodeString(sig) + privateSigningKey := ed25519.NewKeyFromSeed(decodedSig[:32]) + return privateSigningKey, nil +} diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index d1cfaa4bf..20355f4c0 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -20,6 +20,8 @@ import ( "golang.org/x/crypto/sha3" ) +const SignatureV2 = 1 + // ChunkedUpload upload manager with chunked upload feature type ChunkedUpload struct { consensus Consensus diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 355013112..024eb5ab5 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -3,6 +3,7 @@ package sdk import ( "bytes" "context" + "crypto/ed25519" "crypto/md5" "encoding/hex" "encoding/json" @@ -84,6 +85,7 @@ type DownloadRequest struct { endBlock int64 chunkSize int numBlocks int64 + validationRootMap map[string]*blobberFile statusCallback StatusCallback ctx context.Context ctxCncl context.CancelFunc @@ -95,25 +97,29 @@ type DownloadRequest struct { fileCallback func() contentMode string Consensus - effectiveBlockSize int // blocksize - encryptionOverHead - ecEncoder reedsolomon.Encoder - maskMu *sync.Mutex - encScheme encryption.EncryptionScheme - shouldVerify bool - blocksPerShard int64 - connectionID string - skip bool - freeRead bool - fRef *fileref.FileRef - chunksPerShard int64 - size int64 - offset int64 - bufferMap map[int]zboxutil.DownloadBuffer - downloadStorer DownloadProgressStorer - workdir string - downloadQueue downloadQueue // Always initialize this queue with max time taken - isResume bool - isEnterprise bool + effectiveBlockSize int // blocksize - encryptionOverHead + ecEncoder reedsolomon.Encoder + maskMu *sync.Mutex + encScheme encryption.EncryptionScheme + shouldVerify bool + blocksPerShard int64 + connectionID string + skip bool + freeRead bool + fRef *fileref.FileRef + chunksPerShard int64 + size int64 + offset int64 + bufferMap map[int]zboxutil.DownloadBuffer + downloadStorer DownloadProgressStorer + workdir string + downloadQueue downloadQueue // Always initialize this queue with max time taken + isResume bool + isEnterprise bool + storageVersion int + allocOwnerSigningPubKey string + // in case of auth ticket, this key will be of the shared user rather than the owner of the allocation + allocOwnerSigningPrivateKey ed25519.PrivateKey } type downloadPriority struct { @@ -468,10 +474,11 @@ func (req *DownloadRequest) processDownload() { } elapsedInitEC := time.Since(now) if req.encryptedKey != "" { - err = req.initEncryption() + logger.Logger.Info("encryption version: ", fRef.EncryptionVersion) + err = req.initEncryption(fRef.EncryptionVersion) if err != nil { req.errorCB( - fmt.Errorf("Error while initializing encryption"), remotePathCB, + fmt.Errorf("Error while initializing encryption "+err.Error()), remotePathCB, ) return } @@ -962,16 +969,73 @@ func (req *DownloadRequest) initEC() error { } // initEncryption will initialize encScheme with client's keys -func (req *DownloadRequest) initEncryption() (err error) { +func (req *DownloadRequest) initEncryption(encryptionVersion int) (err error) { req.encScheme = encryption.NewEncryptionScheme() - mnemonic := client.Mnemonic() - if mnemonic != "" { - _, err = req.encScheme.Initialize(client.Mnemonic()) - if err != nil { - return err + var entropy string + if req.authTicket != nil { + if len(req.allocOwnerSigningPrivateKey) != 0 { + _, err := req.encScheme.Initialize(hex.EncodeToString(req.allocOwnerSigningPrivateKey)) + if err != nil { + return err + } + pubKey, err := req.encScheme.GetPublicKey() + if err != nil { + return err + } + if pubKey != req.authTicket.EncryptionPublicKey { + // try with mnemonics + entropy = client.Mnemonic() + if entropy == "" { + return errors.New("mnemonic_required", "Mnemonic required for decryption") + } + req.encScheme = encryption.NewEncryptionScheme() + _, err = req.encScheme.Initialize(entropy) + if err != nil { + return err + } + pubKey, err = req.encScheme.GetPublicKey() + if err != nil { + return err + } + if pubKey != req.authTicket.EncryptionPublicKey { + return errors.New("invalid_encryption_key", "Encryption key mismatch") + } + } + } else { + entropy = client.Mnemonic() + if entropy == "" { + return errors.New("mnemonic_required", "Mnemonic required for decryption") + } + req.encScheme = encryption.NewEncryptionScheme() + _, err = req.encScheme.Initialize(entropy) + if err != nil { + return err + } + pubKey, err := req.encScheme.GetPublicKey() + if err != nil { + return err + } + if pubKey != req.authTicket.EncryptionPublicKey { + return errors.New("invalid_signing_key", "signing key is empty") + } } } else { - return errors.New("invalid_mnemonic", "Invalid mnemonic") + if encryptionVersion == SignatureV2 { + if len(req.allocOwnerSigningPrivateKey) == 0 { + return errors.New("invalid_signing_key", "Invalid private signing key") + } + entropy = hex.EncodeToString(req.allocOwnerSigningPrivateKey) + } else { + entropy = client.Mnemonic() + } + if entropy != "" { + _, err = req.encScheme.Initialize(entropy) + if err != nil { + return err + } + } else { + return errors.New("invalid_mnemonic", "Invalid mnemonic") + } } err = req.encScheme.InitForDecryption("filetype:audio", req.encryptedKey) diff --git a/zboxcore/sdk/filerefsworker.go b/zboxcore/sdk/filerefsworker.go index b8b7a195a..a4bafb312 100644 --- a/zboxcore/sdk/filerefsworker.go +++ b/zboxcore/sdk/filerefsworker.go @@ -330,6 +330,8 @@ type SimilarField struct { ActualThumbnailSize int64 `json:"actual_thumbnail_size"` ActualThumbnailHash string `json:"actual_thumbnail_hash"` CustomMeta string `json:"custom_meta"` + SignatureVersion int `json:"signature_version"` + EncryptionVersion int `json:"encryption_version"` } type RecentlyAddedRefRequest struct { diff --git a/zboxcore/sdk/reader.go b/zboxcore/sdk/reader.go index c68d40bc7..457eede4b 100644 --- a/zboxcore/sdk/reader.go +++ b/zboxcore/sdk/reader.go @@ -223,7 +223,7 @@ func GetDStorageFileReader(alloc *Allocation, ref *ORef, sdo *StreamDownloadOpti if ref.EncryptedKey != "" { sd.effectiveBlockSize = BlockSize - EncryptionOverHead sd.encryptedKey = ref.EncryptedKey - err = sd.initEncryption() + err = sd.initEncryption(ref.SignatureVersion) if err != nil { return nil, err } From fea75d59d7d95bb1f29706470373d040c7aa3843 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 28 Feb 2025 15:45:37 +0530 Subject: [PATCH 098/107] added alloc version check for rollback --- zboxcore/sdk/allocation.go | 2 +- zboxcore/sdk/rollback.go | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 6481664cb..8ffdf60ec 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -793,7 +793,7 @@ func (a *Allocation) GetCurrentVersion() (bool, error) { wg.Add(1) go func(rb *RollbackBlobber) { defer wg.Done() - err := rb.processRollback(context.TODO(), a.ID) + err := rb.processRollback(context.TODO(), a.ID, a.allocationVersion) if err != nil { success = false } diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index e5d03020a..0981ad66d 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -115,9 +115,10 @@ func GetWritemarker(allocID, allocTx, sig, id, baseUrl string, clientId ...strin return nil, fmt.Errorf("writemarker error response %d", http.StatusTooManyRequests) } -func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error { +func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string, allocVersion int64) error { // don't rollback if the blobber is already in repair mode otherwise it will lead to inconsistent state - if rb.lvm == nil || rb.lvm.VersionMarker.IsRepair { + // don't rollback if the allocation verison is already + if rb.lvm == nil || rb.lvm.VersionMarker.IsRepair || allocVersion == 0 { return nil } vm := &marker.VersionMarker{ @@ -350,7 +351,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, []BlobberStatus, error) { wg.Add(1) go func(rb *RollbackBlobber) { defer wg.Done() - err := rb.processRollback(context.TODO(), a.Tx) + err := rb.processRollback(context.TODO(), a.Tx, a.allocationVersion) if err != nil { atomic.AddInt32(&errCnt, 1) rb.commitResult = ErrorCommitResult(err.Error()) @@ -414,7 +415,7 @@ func (a *Allocation) RollbackWithMask(mask zboxutil.Uint128) { wg.Add(1) go func(rb *RollbackBlobber) { defer wg.Done() - err := rb.processRollback(context.TODO(), a.Tx) + err := rb.processRollback(context.TODO(), a.Tx, a.allocationVersion) if err != nil { rb.commitResult = ErrorCommitResult(err.Error()) l.Logger.Error("error during rollback", zap.Error(err)) From 23dfbea214968593ff89ff052a52f004bd74fa3e Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Fri, 7 Mar 2025 01:19:45 +0530 Subject: [PATCH 099/107] added fix --- zboxcore/sdk/allocation.go | 1 + zboxcore/sdk/sharerequest.go | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 8ffdf60ec..6611a69cf 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -2177,6 +2177,7 @@ func (a *Allocation) GetAuthTicket(path, filename string, ctx: a.ctx, remotefilepath: path, remotefilename: filename, + signingPrivateKey: a.privateSigningKey, } if referenceType == fileref.DIRECTORY { diff --git a/zboxcore/sdk/sharerequest.go b/zboxcore/sdk/sharerequest.go index 4be3f6def..3db0141c7 100644 --- a/zboxcore/sdk/sharerequest.go +++ b/zboxcore/sdk/sharerequest.go @@ -2,6 +2,8 @@ package sdk import ( "context" + "crypto/ed25519" + "encoding/hex" "sync" "github.com/0chain/errors" @@ -25,6 +27,7 @@ type ShareRequest struct { expirationSeconds int64 blobbers []*blockchain.StorageNode ctx context.Context + signingPrivateKey ed25519.PrivateKey } func (req *ShareRequest) GetFileRef() (*fileref.FileRef, error) { @@ -71,7 +74,19 @@ func (req *ShareRequest) getAuthTicket(clientID, encPublicKey string) (*marker.A if encPublicKey != "" { // file is encrypted encScheme := encryption.NewEncryptionScheme() - if _, err := encScheme.Initialize((client.GetClient().Mnemonic)); err != nil { + var entropy string + if fRef.EncryptionVersion == SignatureV2 { + if len(req.signingPrivateKey) == 0 { + return nil, errors.New("wallet_error", "signing private key is empty") + } + entropy = hex.EncodeToString(req.signingPrivateKey) + } else { + entropy = client.Wallet().Mnemonic + } + if entropy == "" { + return nil, errors.New("wallet_error", "wallet mnemonic is empty") + } + if _, err := encScheme.Initialize((entropy)); err != nil { return nil, err } @@ -82,6 +97,7 @@ func (req *ShareRequest) getAuthTicket(clientID, encPublicKey string) (*marker.A at.ReEncryptionKey = reKey at.Encrypted = true + at.EncryptionPublicKey = encPublicKey } if err := at.Sign(); err != nil { From c2e9762bbc1857376b664c222fa34adabe712724 Mon Sep 17 00:00:00 2001 From: Maulik Singhal <69348454+smaulik13@users.noreply.github.com> Date: Sun, 16 Mar 2025 22:14:20 +0530 Subject: [PATCH 100/107] Update build-sdks.yml --- .github/workflows/build-sdks.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index 500847b96..547191bf5 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -82,7 +82,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v5 with: name: zcncore-ios path: | @@ -186,7 +186,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v5 with: name: zcncore-android path: zcncore-android.tar.gz @@ -257,7 +257,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v5 with: name: zcncore-macos path: | @@ -325,7 +325,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v5 with: name: zcn-windows path: | @@ -352,7 +352,7 @@ jobs: run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.23 make wasm-build - name: 'Upload Artifact' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v5 with: name: zcn.wasm path: zcn.wasm From 5806b72e19896aa4f56b4528140c958bcb0c931f Mon Sep 17 00:00:00 2001 From: Maulik Singhal <69348454+smaulik13@users.noreply.github.com> Date: Mon, 17 Mar 2025 23:13:53 +0530 Subject: [PATCH 101/107] Update build-sdks.yml --- .github/workflows/build-sdks.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index 547191bf5..500847b96 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -82,7 +82,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v3 with: name: zcncore-ios path: | @@ -186,7 +186,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v3 with: name: zcncore-android path: zcncore-android.tar.gz @@ -257,7 +257,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v3 with: name: zcncore-macos path: | @@ -325,7 +325,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v3 with: name: zcn-windows path: | @@ -352,7 +352,7 @@ jobs: run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.23 make wasm-build - name: 'Upload Artifact' - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v3 with: name: zcn.wasm path: zcn.wasm From 8fce149a7d0a065e56230705b15aa1b86f1eea08 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Mon, 17 Mar 2025 23:18:15 +0530 Subject: [PATCH 102/107] wasm build --- .github/workflows/build-sdks.yml | 70 ++++++++++++++++++++++++-------- 1 file changed, 52 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index 500847b96..3a85bbb19 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -18,16 +18,16 @@ env: jobs: build-ios: name: Build-ios - runs-on: macos-runner + runs-on: macos-latest steps: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.23 + - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.23 + go-version: 1.22.5 - name: Clean build run: make clean-mobilesdk @@ -82,7 +82,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: zcncore-ios path: | @@ -96,10 +96,10 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.23 + - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.23 + go-version: 1.22.5 - name: Install deps run: | @@ -186,23 +186,23 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: zcncore-android path: zcncore-android.tar.gz build-macos: name: Build-macos - runs-on: macos-runner + runs-on: macos-latest steps: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.23 + - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.23 + go-version: 1.22.5 - name: Clean build run: make clean-mobilesdk @@ -257,7 +257,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: zcncore-macos path: | @@ -271,10 +271,10 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up Go 1.23 + - name: Set up Go 1.22 uses: actions/setup-go@v3 with: - go-version: 1.23 + go-version: 1.22.5 - name: Install deps run: | @@ -325,7 +325,7 @@ jobs: file_glob: true - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: zcn-windows path: | @@ -349,10 +349,44 @@ jobs: sudo apt-get -y install build-essential nghttp2 libnghttp2-dev libssl-dev wget - name: Build - run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.23 make wasm-build + run: | + docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.23 make wasm-build + gzip -9 zcn.wasm && mv zcn.wasm.gz zcn.wasm + mv zcn.wasm enterprise-zcn.wasm + tar -czvf zcn_enterprise_wasm.tar.gz enterprise-zcn.wasm + + - name: Setup Build + id: setup_build + run: | + tag=$(echo ${GITHUB_REF#refs/tags/}) + echo ${tag} + if [[ "${{github.event_name}}" = "workflow_dispatch" ]]; then + echo "> 0Chain: trigger from workflow_dispatch" + + echo "::set-output name=RELEASE::false" + echo "::set-output name=TAG::none" + + elif [[ ${tag} = v*\.*\.* ]] ; then + echo "> 0Chain: trigger from git event" + + # upload output on release + echo "::set-output name=RELEASE::true" + echo "::set-output name=TAG::${tag}" + fi + + - name: Upload zcn_enterprise_wasm to release + if: steps.setup_build.outputs.RELEASE == 'true' + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: zcn_enterprise_wasm.tar.gz + tag: ${{ steps.setup_build.outputs.TAG }} + overwrite: true + file_glob: true - name: 'Upload Artifact' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: zcn.wasm - path: zcn.wasm + name: zcn_enterprise_wasm + path: | + zcn_enterprise_wasm.tar.gz From fea26e85282fc26066fd5224c47dad07d5f110cc Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 18 Mar 2025 00:37:02 +0530 Subject: [PATCH 103/107] build fix --- _util/build_mobile.mk | 3 ++- core/version/version.go | 3 ++- mobilesdk/zcn/writepool.go | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/_util/build_mobile.mk b/_util/build_mobile.mk index 1eeee97e0..e8babac38 100644 --- a/_util/build_mobile.mk +++ b/_util/build_mobile.mk @@ -1,5 +1,6 @@ 0CHAIN_PATH := github.com/0chain GOSDK_PATH := $(0CHAIN_PATH)/gosdk +GOSDK_COMMON_PATH = $(0CHAIN_PATH)/gosdk_common OUTDIR := $(ROOT_DIR)/out IOSMOBILESDKDIR := $(OUTDIR)/iossdk ANDROIDMOBILESDKDIR := $(OUTDIR)/androidsdk @@ -9,7 +10,7 @@ ANDROIDBINNAME := zcncore.aar MINIOSVERSIONMIN := "-miphoneos-version-min=7.0=7.0 -mios-version-min=7.0 -mios-simulator-version-min=7.0" MINMACOSVERSIONMIN := "-mmacosx-version-min=10.12" -PKG_EXPORTS := $(GOSDK_PATH)/zcncore $(GOSDK_PATH)/core/common $(GOSDK_PATH)/mobilesdk/sdk $(GOSDK_PATH)/mobilesdk/zbox $(GOSDK_PATH)/mobilesdk/zboxapi $(GOSDK_PATH)/mobilesdk/zcn +PKG_EXPORTS := $(GOSDK_COMMON_PATH)/zcncore $(GOSDK_COMMON_PATH)/core/common $(GOSDK_PATH)/mobilesdk/sdk $(GOSDK_PATH)/mobilesdk/zbox $(GOSDK_PATH)/mobilesdk/zboxapi $(GOSDK_PATH)/mobilesdk/zcn .PHONY: setup-gomobile build-iossimulator build-ios build-android build-android-debug diff --git a/core/version/version.go b/core/version/version.go index 9213a1e29..04b6e1054 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -1,5 +1,6 @@ + //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version +const VERSIONSTR = "v1.18.5-58-g8fce149a" -const VERSIONSTR = "v1.16.3-10-g66360b13" diff --git a/mobilesdk/zcn/writepool.go b/mobilesdk/zcn/writepool.go index 7d78d7292..7bd40bbdd 100644 --- a/mobilesdk/zcn/writepool.go +++ b/mobilesdk/zcn/writepool.go @@ -6,7 +6,7 @@ package zcn import ( "strconv" - "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" ) // WritePoolLock locks given number of tokes for given duration in read pool. @@ -27,7 +27,7 @@ func WritePoolLock(allocID string, tokens, fee string) (string, error) { return "", err } - hash, _, err := sdk.WritePoolLock( + hash, _, err := commonsdk.WritePoolLock( allocID, tokensUint, feeUint, From 659076aef5cead20f01b6006b85440c341f77914 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 18 Mar 2025 01:21:45 +0530 Subject: [PATCH 104/107] build fix --- go.mod | 2 +- go.sum | 7 +++---- mobilesdk/sdk/sdk.go | 10 +++++----- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index 8dcdd6dbb..f8e09debf 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250204070817-3c82b7ad6a9f + github.com/0chain/gosdk_common v0.0.0-20250317194632-2bc6b797b13f github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 4c5e2326f..19c372e02 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250204070817-3c82b7ad6a9f h1:H3Edk0y4Q8GEsPAbIsmn+WKiTC/uA4L/YuX0x/3Adz0= -github.com/0chain/gosdk_common v0.0.0-20250204070817-3c82b7ad6a9f/go.mod h1:aGBabvKYk/B6G6bEBI8j1cBaWY2is9sCii88Ly6VeCU= +github.com/0chain/gosdk_common v0.0.0-20250317194632-2bc6b797b13f h1:4cvs31VWC1E0vsPFkQCblsYQaYQKBO+oyxeqWYWBg0E= +github.com/0chain/gosdk_common v0.0.0-20250317194632-2bc6b797b13f/go.mod h1:+FBmkG4JocGmD+8gyE4kyst15p+3xm3Nf+nrg4cu5V4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= @@ -887,9 +887,8 @@ google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHh gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/cheggaaa/pb.v1 v1.0.28 h1:n1tBJnnK2r7g9OW2btFH91V92STTUevLXYFb8gy9EMk= gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index fdd9fdb45..a84a459b2 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -58,14 +58,14 @@ type StorageSDK struct { // - verbose: output detail logs func SetLogFile(logFile string, verbose bool) { zcncore.SetLogFile(logFile, verbose) - sdk.SetLogFile(logFile, verbose) + commonsdk.SetLogFile(logFile, verbose) } // SetLogLevel set the log level. // // `lvl` - 0 disabled; higher number (upto 4) more verbosity func SetLogLevel(logLevel int) { - sdk.SetLogLevel(logLevel) + commonsdk.SetLogLevel(logLevel) } // Init init the sdk with chain config @@ -227,7 +227,7 @@ func (s *StorageSDK) CreateAllocationWithBlobbers(name string, datashards, parit if blobberUrls != "" { urls := strings.Split(blobberUrls, ",") if len(urls) > 0 { - ids, err := sdk.GetBlobberIds(urls) + ids, err := commonsdk.GetBlobberIds(urls) if err != nil { return nil, err } @@ -378,13 +378,13 @@ func (s *StorageSDK) UpdateAllocation(size, authRoundExpiry int64, extend bool, return "", errors.Errorf("int64 overflow in lock") } - hash, _, err = sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, lock, "", "", "", "", "", false, &sdk.FileOptionsParameters{}, "") + hash, _, err = sdk.UpdateAllocation(size, authRoundExpiry, extend, allocationID, lock, "", "", "", "", "", false, &commonsdk.FileOptionsParameters{}, "") return hash, err } // GetBlobbersList get list of active blobbers, and format them as array json string func (s *StorageSDK) GetBlobbersList() (string, error) { - blobbs, err := sdk.GetBlobbers(true, false) + blobbs, err := commonsdk.GetBlobbers(true, false) if err != nil { return "", err } From ba628432aceddde73b13e206938b8eadba6136ca Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 18 Mar 2025 17:48:02 +0530 Subject: [PATCH 105/107] more refactor --- go.mod | 2 +- go.sum | 4 +- wasmsdk/allocation.go | 4 + wasmsdk/blobber.go | 2 +- wasmsdk/common.go | 5 +- winsdk/cache.go | 5 +- winsdk/storage.go | 3 +- winsdk/stream.go | 3 +- zboxcore/sdk/allocation.go | 123 +++++++++++-------------------- zboxcore/sdk/allocation_test.go | 10 +-- zboxcore/sdk/commitmetaworker.go | 6 +- zboxcore/sdk/common.go | 5 +- 12 files changed, 73 insertions(+), 99 deletions(-) diff --git a/go.mod b/go.mod index f8e09debf..1410579ed 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250317194632-2bc6b797b13f + github.com/0chain/gosdk_common v0.0.0-20250318121140-c82820c54dea github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 19c372e02..770dd25b0 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250317194632-2bc6b797b13f h1:4cvs31VWC1E0vsPFkQCblsYQaYQKBO+oyxeqWYWBg0E= -github.com/0chain/gosdk_common v0.0.0-20250317194632-2bc6b797b13f/go.mod h1:+FBmkG4JocGmD+8gyE4kyst15p+3xm3Nf+nrg4cu5V4= +github.com/0chain/gosdk_common v0.0.0-20250318121140-c82820c54dea h1:wHD0sD4TvrR4oEmDOwPmHpco9e+vigl3850MrQpBo50= +github.com/0chain/gosdk_common v0.0.0-20250318121140-c82820c54dea/go.mod h1:+FBmkG4JocGmD+8gyE4kyst15p+3xm3Nf+nrg4cu5V4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index efa7c0ecc..6f4dd3e99 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -546,3 +546,7 @@ func repairSize(allocationID, remotePath string) (sdk.RepairSize, error) { } return alloc.RepairSize(remotePath) } + +func generateOwnerSigningKey(ownerPublicKey, ownerID string) (string, error) { + return commonsdk.GenerateOwnerSigningPublicKey() +} diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 7a6afefcb..8970709e0 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -416,7 +416,7 @@ func Share(allocationID, remotePath, clientID, encryptionPublicKey string, expir } -func getFileMetaByName(allocationID, fileNameQuery string) ([]*sdk.ConsolidatedFileMetaByName, error) { +func getFileMetaByName(allocationID, fileNameQuery string) ([]*commonsdk.ConsolidatedFileMetaByName, error) { allocationObj, err := getAllocation(allocationID) if err != nil { return nil, err diff --git a/wasmsdk/common.go b/wasmsdk/common.go index 7c9f4f8ac..43d1dded0 100644 --- a/wasmsdk/common.go +++ b/wasmsdk/common.go @@ -9,6 +9,7 @@ import ( "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" ) // PrintError is to print to stderr @@ -21,8 +22,8 @@ func PrintInfo(v ...interface{}) { sdkLogger.Info(v...) } -func getFileMeta(allocationObj *sdk.Allocation, remotePath string, commit bool) (*sdk.ConsolidatedFileMeta, bool, error) { - var fileMeta *sdk.ConsolidatedFileMeta +func getFileMeta(allocationObj *sdk.Allocation, remotePath string, commit bool) (*commonsdk.ConsolidatedFileMeta, bool, error) { + var fileMeta *commonsdk.ConsolidatedFileMeta isFile := false if commit { diff --git a/winsdk/cache.go b/winsdk/cache.go index f3dc5213a..7622708bc 100644 --- a/winsdk/cache.go +++ b/winsdk/cache.go @@ -7,6 +7,7 @@ import ( "time" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/marker" lru "github.com/hashicorp/golang-lru/v2" ) @@ -18,7 +19,7 @@ type cachedAllocation struct { type cachedFileMeta struct { CacheExpiresAt time.Time - FileMeta *sdk.ConsolidatedFileMeta + FileMeta *commonsdk.ConsolidatedFileMeta } var ( @@ -67,7 +68,7 @@ func getAllocationWith(authTicket string) (*sdk.Allocation, *marker.AuthTicket, return alloc, at, err } -func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, error) { +func getFileMeta(allocationID, remotePath string) (*commonsdk.ConsolidatedFileMeta, error) { var it *cachedFileMeta var ok bool diff --git a/winsdk/storage.go b/winsdk/storage.go index cdfbaa392..8110a19d5 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -16,6 +16,7 @@ import ( "github.com/0chain/gosdk/zboxcore/sdk" "github.com/0chain/gosdk_common/core/common" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/marker" ) @@ -209,7 +210,7 @@ func GetFileMeta(allocationID, path, authTicket *C.char) *C.char { s := C.GoString(path) - var f *sdk.ConsolidatedFileMeta + var f *commonsdk.ConsolidatedFileMeta if isShared { f, err = alloc.GetFileMetaFromAuthTicket(t, ticket.FilePathHash) } else { diff --git a/winsdk/stream.go b/winsdk/stream.go index bad529daf..c495b518c 100644 --- a/winsdk/stream.go +++ b/winsdk/stream.go @@ -19,6 +19,7 @@ import ( "sync" "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" lru "github.com/hashicorp/golang-lru/v2" ) @@ -163,7 +164,7 @@ func streamingMedia(w http.ResponseWriter, req *http.Request) { } } -func downloadBlocks(remotePath string, f *sdk.ConsolidatedFileMeta, ra httpRange) ([]byte, error) { +func downloadBlocks(remotePath string, f *commonsdk.ConsolidatedFileMeta, ra httpRange) ([]byte, error) { defer func() { if r := recover(); r != nil { log.Error("win: ", r) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 6611a69cf..5828e0378 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -5,6 +5,7 @@ import ( "context" "crypto/ed25519" "encoding/base64" + "encoding/hex" "encoding/json" "fmt" "io" @@ -78,74 +79,6 @@ 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 - ID string `json:"ID"` - Tx string `json:"Tx"` - TotalSize int64 `json:"TotalSize"` - UsedSize int `json:"UsedSize"` - OwnerID string `json:"OwnerID"` - OwnerPublicKey string `json:"OwnerPublicKey"` - Expiration int `json:"Expiration"` - AllocationRoot string `json:"AllocationRoot"` - BlobberSize int `json:"BlobberSize"` - BlobberSizeUsed int `json:"BlobberSizeUsed"` - LatestRedeemedWM string `json:"LatestRedeemedWM"` - IsRedeemRequired bool `json:"IsRedeemRequired"` - CleanedUp bool `json:"CleanedUp"` - Finalized bool `json:"Finalized"` - Terms []struct { - ID int `json:"ID"` - BlobberID string `json:"BlobberID"` - AllocationID string `json:"AllocationID"` - ReadPrice int `json:"ReadPrice"` - WritePrice int `json:"WritePrice"` - } `json:"Terms"` -} - -// ConsolidatedFileMeta represents the file meta data. -type ConsolidatedFileMeta struct { - Name string - Type string - Path string - LookupHash string - Hash string - MimeType string - Size int64 - NumBlocks int64 - ActualFileSize int64 - ActualNumBlocks int64 - EncryptedKey string - - ActualThumbnailSize int64 - ActualThumbnailHash string - - 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 -} - // Allocation represents a storage allocation. type Allocation struct { commonsdk.Allocation @@ -250,16 +183,16 @@ func (a *Allocation) GetStats() *commonsdk.AllocationStats { } // GetBlobberStats returns the statistics of the blobbers in the allocation. -func (a *Allocation) GetBlobberStats() map[string]*BlobberAllocationStats { +func (a *Allocation) GetBlobberStats() map[string]*commonsdk.BlobberAllocationStats { numList := len(a.Blobbers) wg := &sync.WaitGroup{} wg.Add(numList) - rspCh := make(chan *BlobberAllocationStats, numList) + rspCh := make(chan *commonsdk.BlobberAllocationStats, numList) for _, blobber := range a.Blobbers { go getAllocationDataFromBlobber(blobber, a.ID, a.Tx, rspCh, wg, a.Owner) } wg.Wait() - result := make(map[string]*BlobberAllocationStats, len(a.Blobbers)) + result := make(map[string]*commonsdk.BlobberAllocationStats, len(a.Blobbers)) for i := 0; i < numList; i++ { resp := <-rspCh result[resp.BlobberURL] = resp @@ -273,6 +206,35 @@ func SetDownloadWorkerCount(count int) { downloadWorkerCount = count } +func (a *Allocation) generateAndSetOwnerSigningPublicKey() { + //create ecdsa public key from signature + if a.OwnerPublicKey != client.PublicKey() { + return + } + privateSigningKey, err := commonsdk.GenerateOwnerSigningKey(a.OwnerPublicKey, a.Owner) + if err != nil { + l.Logger.Error("Failed to generate owner signing key", zap.Error(err)) + return + } + if a.OwnerSigningPublicKey == "" && !a.Finalized && !a.Canceled && client.Wallet().IsSplit { + pubKey := privateSigningKey.Public().(ed25519.PublicKey) + a.OwnerSigningPublicKey = hex.EncodeToString(pubKey) + hash, _, err := UpdateAllocation(0, 0, false, a.ID, 0, "", "", "", "", a.OwnerSigningPublicKey, false, nil, "") + if err != nil { + l.Logger.Error("Failed to update owner signing public key ", err, " allocationID: ", a.ID, " hash: ", hash) + return + } + l.Logger.Info("Owner signing public key updated with transaction : ", hash, " ownerSigningPublicKey : ", a.OwnerSigningPublicKey) + a.Tx = hash + } else if a.OwnerSigningPublicKey != "" { + pubKey := privateSigningKey.Public().(ed25519.PublicKey) + l.Logger.Info("Owner signing public key already exists: ", a.OwnerSigningPublicKey, " generated: ", hex.EncodeToString(pubKey)) + } else { + return + } + a.privateSigningKey = privateSigningKey +} + // InitAllocation initializes the allocation. func (a *Allocation) InitAllocation() { a.downloadChan = make(chan *DownloadRequest, 100) @@ -292,6 +254,7 @@ func (a *Allocation) InitAllocation() { } } } + a.generateAndSetOwnerSigningPublicKey() a.startWorker(a.ctx) InitCommitWorker(a.Blobbers) InitBlockDownloader(a.Blobbers, downloadWorkerCount) @@ -1201,7 +1164,7 @@ func (a *Allocation) generateDownloadRequest( downloadReq.allocOwnerPubKey = a.OwnerPublicKey downloadReq.allocOwnerSigningPubKey = a.OwnerSigningPublicKey if len(a.privateSigningKey) == 0 { - sk, err := generateOwnerSigningKey(client.PublicKey(), client.Id()) + sk, err := commonsdk.GenerateOwnerSigningKey(client.PublicKey(), client.Id()) if err != nil { return nil, err } @@ -1764,12 +1727,12 @@ func (a *Allocation) GetRecentlyAddedRefs(page int, fromDate int64, pageLimit in // 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) { +func (a *Allocation) GetFileMeta(path string) (*commonsdk.ConsolidatedFileMeta, error) { if !a.isInitialized() { return nil, notInitialized } - result := &ConsolidatedFileMeta{} + result := &commonsdk.ConsolidatedFileMeta{} listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} listReq.ClientId = a.Owner listReq.allocationID = a.ID @@ -1806,12 +1769,12 @@ func (a *Allocation) GetFileMeta(path string) (*ConsolidatedFileMeta, error) { // GetFileMetaByName retrieve consolidated file metadata given its name (its full path starting from root "/"). // - fileName: full file path starting from the allocation root. // - fileName: full file path starting from the allocation root. -func (a *Allocation) GetFileMetaByName(fileName string) ([]*ConsolidatedFileMetaByName, error) { +func (a *Allocation) GetFileMetaByName(fileName string) ([]*commonsdk.ConsolidatedFileMetaByName, error) { if !a.isInitialized() { return nil, notInitialized } - resultArr := []*ConsolidatedFileMetaByName{} + resultArr := []*commonsdk.ConsolidatedFileMetaByName{} listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} listReq.allocationID = a.ID listReq.allocationTx = a.Tx @@ -1823,7 +1786,7 @@ func (a *Allocation) GetFileMetaByName(fileName string) ([]*ConsolidatedFileMeta _, _, refs, _ := listReq.getMultipleFileConsensusFromBlobbers() if len(refs) != 0 { for _, ref := range refs { - result := &ConsolidatedFileMetaByName{} + result := &commonsdk.ConsolidatedFileMetaByName{} if ref != nil { result.Type = ref.Type result.Name = ref.Name @@ -1872,12 +1835,12 @@ func (a *Allocation) GetChunkReadSize(encrypt bool) int64 { // 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) { +func (a *Allocation) GetFileMetaFromAuthTicket(authTicket string, lookupHash string) (*commonsdk.ConsolidatedFileMeta, error) { if !a.isInitialized() { return nil, notInitialized } - result := &ConsolidatedFileMeta{} + result := &commonsdk.ConsolidatedFileMeta{} sEnc, err := base64.StdEncoding.DecodeString(authTicket) if err != nil { return nil, errors.New("auth_ticket_decode_error", "Error decoding the auth ticket."+err.Error()) @@ -2657,7 +2620,7 @@ func (a *Allocation) downloadFromAuthTicket(fileHandler sys.File, authTicket str downloadReq.allocOwnerPubKey = a.OwnerPublicKey downloadReq.allocOwnerSigningPubKey = a.OwnerSigningPublicKey //for auth ticket set your own signing key - sk, err := generateOwnerSigningKey(client.PublicKey(), client.Id()) + sk, err := commonsdk.GenerateOwnerSigningKey(client.PublicKey(), client.Id()) if err != nil { return err } diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index 8376fddd9..59400bf16 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -420,7 +420,7 @@ func TestAllocation_GetBlobberStats(t *testing.T) { return strings.HasPrefix(req.URL.Path, "TestAllocation_GetBlobberStats"+testName) })).Return(&http.Response{ Body: func() io.ReadCloser { - jsonFR, err := json.Marshal(&BlobberAllocationStats{ + jsonFR, err := json.Marshal(&commonsdk.BlobberAllocationStats{ ID: mockAllocationId, Tx: mockAllocationTxId, }) @@ -449,8 +449,8 @@ func TestAllocation_GetBlobberStats(t *testing.T) { got := a.GetBlobberStats() require.NotEmptyf(got, "Error no blobber stats result found") - expected := make(map[string]*BlobberAllocationStats, 1) - expected["TestAllocation_GetBlobberStats"+tt.name+mockBlobberUrl] = &BlobberAllocationStats{ + expected := make(map[string]*commonsdk.BlobberAllocationStats, 1) + expected["TestAllocation_GetBlobberStats"+tt.name+mockBlobberUrl] = &commonsdk.BlobberAllocationStats{ ID: mockAllocationId, Tx: mockAllocationTxId, BlobberID: tt.name + mockBlobberId, @@ -1159,7 +1159,7 @@ func TestAllocation_GetFileMeta(t *testing.T) { return } require.NoErrorf(err, "unexpected error: %v", err) - expectedResult := &ConsolidatedFileMeta{ + expectedResult := &commonsdk.ConsolidatedFileMeta{ Hash: mockActualHash, } require.EqualValues(expectedResult, got) @@ -2049,7 +2049,7 @@ func TestAllocation_GetFileMetaFromAuthTicket(t *testing.T) { return } require.NoErrorf(err, "unexpected error: %v", err) - expectedResult := &ConsolidatedFileMeta{ + expectedResult := &commonsdk.ConsolidatedFileMeta{ Hash: mockActualHash, } require.EqualValues(expectedResult, got) diff --git a/zboxcore/sdk/commitmetaworker.go b/zboxcore/sdk/commitmetaworker.go index 03697991b..04da61721 100644 --- a/zboxcore/sdk/commitmetaworker.go +++ b/zboxcore/sdk/commitmetaworker.go @@ -1,11 +1,13 @@ package sdk +import "github.com/0chain/gosdk_common/zboxcore/commonsdk" + type CommitMetaData struct { CrudType string - MetaData *ConsolidatedFileMeta + MetaData *commonsdk.ConsolidatedFileMeta } type CommitMetaResponse struct { TxnID string - MetaData *ConsolidatedFileMeta + MetaData *commonsdk.ConsolidatedFileMeta } diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index 85300bbf3..e03a2f9e5 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -15,6 +15,7 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk_common/constants" "github.com/0chain/gosdk_common/zboxcore/blockchain" + "github.com/0chain/gosdk_common/zboxcore/commonsdk" "github.com/0chain/gosdk_common/zboxcore/fileref" l "github.com/0chain/gosdk_common/zboxcore/logger" "github.com/0chain/gosdk_common/zboxcore/zboxutil" @@ -69,7 +70,7 @@ func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx st return lR.GetRefFromObjectTree(allocationID) } -func getAllocationDataFromBlobber(blobber *blockchain.StorageNode, allocationId string, allocationTx string, respCh chan<- *BlobberAllocationStats, wg *sync.WaitGroup, clientId ...string) { +func getAllocationDataFromBlobber(blobber *blockchain.StorageNode, allocationId string, allocationTx string, respCh chan<- *commonsdk.BlobberAllocationStats, wg *sync.WaitGroup, clientId ...string) { defer wg.Done() httpreq, err := zboxutil.NewAllocationRequest(blobber.Baseurl, allocationId, allocationTx, clientId...) if err != nil { @@ -77,7 +78,7 @@ func getAllocationDataFromBlobber(blobber *blockchain.StorageNode, allocationId return } - var result BlobberAllocationStats + var result commonsdk.BlobberAllocationStats ctx, cncl := context.WithTimeout(context.Background(), (time.Second * 30)) err = zboxutil.HttpDo(ctx, cncl, httpreq, func(resp *http.Response, err error) error { if err != nil { From 1488f2efd41975d9c3d6b9fea6265262ada18e73 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 18 Mar 2025 19:09:14 +0530 Subject: [PATCH 106/107] go mod update --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 1410579ed..79c42192e 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common v0.0.0-20250318121140-c82820c54dea + github.com/0chain/gosdk_common 6dd2826659217ed7d5b68bf9a16e25a90165106a github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 From 026d9c8701a01558cfb0b441b8093714c4743b64 Mon Sep 17 00:00:00 2001 From: smaulik13 Date: Tue, 18 Mar 2025 19:11:01 +0530 Subject: [PATCH 107/107] go mod update --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 79c42192e..96abbcfe0 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - github.com/0chain/gosdk_common 6dd2826659217ed7d5b68bf9a16e25a90165106a + github.com/0chain/gosdk_common v0.0.0-20250318134004-c9cbffc71102 github.com/hack-pad/go-webworkers v0.1.0 github.com/minio/sha256-simd v1.0.1 github.com/valyala/bytebufferpool v1.0.0 diff --git a/go.sum b/go.sum index 770dd25b0..66bb77aee 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/0chain/common v1.18.3 h1:42dYOv2KyMTSanuS67iDtfv+ErbSRqR8NJ3MG72MwaI= github.com/0chain/common v1.18.3/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/0chain/gosdk_common v0.0.0-20250318121140-c82820c54dea h1:wHD0sD4TvrR4oEmDOwPmHpco9e+vigl3850MrQpBo50= -github.com/0chain/gosdk_common v0.0.0-20250318121140-c82820c54dea/go.mod h1:+FBmkG4JocGmD+8gyE4kyst15p+3xm3Nf+nrg4cu5V4= +github.com/0chain/gosdk_common v0.0.0-20250318134004-c9cbffc71102 h1:CKVvICaxGCK25rbOFLtjtO9GZKSpsiorXwudlVkH03Y= +github.com/0chain/gosdk_common v0.0.0-20250318134004-c9cbffc71102/go.mod h1:+FBmkG4JocGmD+8gyE4kyst15p+3xm3Nf+nrg4cu5V4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=