Skip to content

Commit

Permalink
Merge branch 'sprint-1.18' into fix/txn-split-key
Browse files Browse the repository at this point in the history
  • Loading branch information
Jayashsatolia403 authored Nov 1, 2024
2 parents 8bd60c3 + 7269fb8 commit e73e12a
Show file tree
Hide file tree
Showing 19 changed files with 298 additions and 125 deletions.
13 changes: 12 additions & 1 deletion core/client/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/0chain/gosdk/core/conf"
"strings"

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

"github.com/0chain/gosdk/constants"
"github.com/0chain/gosdk/core/sys"
"github.com/0chain/gosdk/core/zcncrypto"
Expand Down Expand Up @@ -63,6 +64,7 @@ func init() {

sys.Verify = verifySignature
sys.VerifyWith = verifySignatureWith
sys.VerifyEd25519With = verifyEd25519With
}

func signHash(hash string, signatureScheme string, keys []sys.KeyPair) (string, error) {
Expand Down Expand Up @@ -104,6 +106,15 @@ func verifySignatureWith(pubKey, signature, hash string) (bool, error) {
return sch.Verify(signature, hash)
}

func verifyEd25519With(pubKey, signature, hash string) (bool, error) {
sch := zcncrypto.NewSignatureScheme(constants.ED25519.String())
err := sch.SetPublicKey(pubKey)
if err != nil {
return false, err
}
return sch.Verify(signature, hash)
}

func GetClientSysKeys(clients ...string) []sys.KeyPair {
var wallet *zcncrypto.Wallet
if len(clients) > 0 && clients[0] != "" && client.wallets[clients[0]] != nil {
Expand Down
17 changes: 12 additions & 5 deletions core/conf/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,19 @@ func GetClientConfig() (*Config, error) {
// InitClientConfig set global client config
func InitClientConfig(c *Config) {
onceCfg.Do(func() {
sharderConsensous := c.SharderConsensous
if sharderConsensous < 1 {
sharderConsensous = DefaultSharderConsensous
}
cfg = c
cfg.SharderConsensous = sharderConsensous
if cfg.SharderConsensous < 1 {
cfg.SharderConsensous = DefaultSharderConsensous
}
if cfg.MaxTxnQuery < 1 {
cfg.MaxTxnQuery = DefaultMaxTxnQuery
}
if cfg.QuerySleepTime < 1 {
cfg.QuerySleepTime = DefaultQuerySleepTime
}
if cfg.MinSubmit < 1 {
cfg.MinSubmit = DefaultMinSubmit
}
})
}

Expand Down
2 changes: 2 additions & 0 deletions core/sys/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ var (
Authorize AuthorizeFunc

AuthCommon AuthorizeFunc

VerifyEd25519With VerifyWithFunc
)

// SetAuthorize sets the authorize callback function
Expand Down
80 changes: 42 additions & 38 deletions core/transaction/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,77 +277,81 @@ func (t *Transaction) VerifySigWith(pubkey string, verifyHandler VerifyFunc) (bo
}

func SendTransactionSync(txn *Transaction, miners []string) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
const requestTimeout = 30 * time.Second // Timeout for each request

wg := sync.WaitGroup{}
wg.Add(len(miners))
fails := make(chan error, len(miners))
var wg sync.WaitGroup

for _, miner := range miners {
url := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL)
wg.Add(1)
minerURL := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL)

go func(url string) {
defer wg.Done()
select {
case <-ctx.Done():
fails <- ctx.Err() // Timeout or cancellation
default:
_, err := sendTransactionToURL(url, txn, nil)
if err != nil {
fails <- err
}

// Create a context with a 30-second timeout for each request
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()

_, err := sendTransactionToURL(ctx, url, txn)
if err != nil {
fails <- err
}
}(url)
}(minerURL)
}

done := make(chan struct{})
// Close the channel when all requests are finished
go func() {
wg.Wait()
close(fails)
close(done)
}()

select {
case <-done: // All requests completed
case <-ctx.Done(): // Timeout reached
return ctx.Err()
}

// Error processing logic here (same as original)
failureCount := 0
// Collect errors from all requests
var failureCount int
messages := make(map[string]int)
for e := range fails {
if e != nil {

for err := range fails {
if err != nil {
failureCount++
messages[e.Error()]++
messages[err.Error()]++
}
}

max := 0
dominant := ""
for m, s := range messages {
if s > max {
dominant = m
// Identify the most frequent error
var maxCount int
var dominantErr string
for msg, count := range messages {
if count > maxCount {
maxCount = count
dominantErr = msg
}
}

if failureCount == len(miners) {
return fmt.Errorf(dominant)
return fmt.Errorf(dominantErr)
}
return nil
}

func sendTransactionToURL(url string, txn *Transaction, wg *sync.WaitGroup) ([]byte, error) {
func sendTransactionToURL(ctx context.Context, url string, txn *Transaction) ([]byte, error) {
// Create a new HTTP POST request with context
postReq, err := util.NewHTTPPostRequest(url, txn)
if err != nil {
//Logger.Error("Error in serializing the transaction", txn, err.Error())
return nil, err
return nil, fmt.Errorf("error creating HTTP request: %w", err)
}

// Use the provided context in the request's Post method
postReq.Ctx = ctx
postResponse, err := postReq.Post()
if err != nil {
return nil, fmt.Errorf("submit transaction failed: %w", err)
}

if postResponse.StatusCode >= 200 && postResponse.StatusCode <= 299 {
return []byte(postResponse.Body), nil
}
return nil, errors.Wrap(err, errors.New("submit transaction failed", postResponse.Body))

return nil, fmt.Errorf("submit transaction failed: %s", postResponse.Body)
}

type cachedObject struct {
Expand Down Expand Up @@ -638,7 +642,7 @@ func SmartContractTxnValueFee(scAddress string, sn SmartContractTxnData,

if t == nil {
return "", "", 0, txn, errors.New("transaction_validation_failed",
"Failed to get the transaction confirmation")
"Failed to get the transaction confirmation : "+txn.Hash)
}

if t.Status == TxnFail {
Expand Down
8 changes: 4 additions & 4 deletions core/util/httpnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type GetResponse struct {

type PostRequest struct {
req *http.Request
ctx context.Context
Ctx context.Context
cncl context.CancelFunc
url string
}
Expand Down Expand Up @@ -129,7 +129,7 @@ func NewHTTPGetRequestContext(ctx context.Context, url string) (*GetRequest, err
gr.PostRequest = &PostRequest{}
gr.url = url
gr.req = req
gr.ctx, gr.cncl = context.WithCancel(ctx)
gr.Ctx, gr.cncl = context.WithCancel(ctx)
return gr, nil
}

Expand All @@ -147,7 +147,7 @@ func NewHTTPPostRequest(url string, data interface{}) (*PostRequest, error) {
req.Header.Set("Access-Control-Allow-Origin", "*")
pr.url = url
pr.req = req
pr.ctx, pr.cncl = context.WithTimeout(context.Background(), time.Second*60)
pr.Ctx, pr.cncl = context.WithTimeout(context.Background(), time.Second*60)
return pr, nil
}

Expand All @@ -163,7 +163,7 @@ func (r *GetRequest) Get() (*GetResponse, error) {

func (r *PostRequest) Post() (*PostResponse, error) {
result := &PostResponse{}
err := httpDo(r.req, r.ctx, r.cncl, func(resp *http.Response, err error) error {
err := httpDo(r.req, r.Ctx, r.cncl, func(resp *http.Response, err error) error {
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/0chain/gosdk
go 1.22.0

require (
github.com/0chain/common v1.18.1
github.com/0chain/common v1.18.2
github.com/0chain/errors v1.0.3
github.com/Luzifer/go-openssl/v3 v3.1.0
github.com/btcsuite/btcd v0.23.4
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ 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 v1.18.1 h1:QKXdEjK6SB3SqzDS/XbK74jy20d3tc+6PA8J8dFpuGw=
github.com/0chain/common v1.18.1/go.mod h1:Lapu2Tj7z5Sm4r+X141e7vsz4NDODTEypeElYAP3iSw=
github.com/0chain/common v1.18.2 h1:VGWfd3Xqio9xbmebPFnUbuk5QN0pK0xzvifaUggJF5g=
github.com/0chain/common v1.18.2/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/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
Expand Down
2 changes: 1 addition & 1 deletion mobilesdk/sdk/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ func (s *StorageSDK) UpdateAllocation(size int64, extend bool, allocationID stri
return "", errors.Errorf("int64 overflow in lock")
}

hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, "", "", "", false, &sdk.FileOptionsParameters{})
hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, "", "", "", "", false, &sdk.FileOptionsParameters{})
return hash, err
}

Expand Down
14 changes: 8 additions & 6 deletions wasmsdk/allocation.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for
"", //addBlobberId,
"", //addBlobberAuthTicket
"", //removeBlobberId,
false, //thirdPartyExtendable,
"", //thirdPartyExtendable,
false, // ownerSigninPublicKey
&sdk.FileOptionsParameters{
ForbidUpload: sdk.FileOptionParam{Changed: forbidupload, Value: forbidupload},
ForbidDelete: sdk.FileOptionParam{Changed: forbiddelete, Value: forbiddelete},
Expand Down Expand Up @@ -196,7 +197,8 @@ func freezeAllocation(allocationID string) (string, error) {
"", //addBlobberId,
"", //addBlobberAuthTicket
"", //removeBlobberId,
false, //thirdPartyExtendable,
"", //thirdPartyExtendable,
false, // ownerSigninPublicKey
&sdk.FileOptionsParameters{
ForbidUpload: sdk.FileOptionParam{Changed: true, Value: true},
ForbidDelete: sdk.FileOptionParam{Changed: true, Value: true},
Expand Down Expand Up @@ -242,7 +244,7 @@ func updateAllocationWithRepair(allocationID string,
size int64,
extend bool,
lock int64,
addBlobberId, addBlobberAuthTicket, removeBlobberId, callbackFuncName string) (string, error) {
addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, callbackFuncName string) (string, error) {
sdk.SetWasm()
allocationObj, err := sdk.GetAllocation(allocationID)
if err != nil {
Expand All @@ -259,7 +261,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, extend, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, false, &sdk.FileOptionsParameters{}, statusBar)
if err != nil {
return hash, err
}
Expand Down Expand Up @@ -295,8 +297,8 @@ func updateAllocationWithRepair(allocationID string,
func updateAllocation(allocationID string,
size 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, extend, allocationID, uint64(lock), addBlobberId, addBlobberAuthTicket, removeBlobberId, ownerSigninPublicKey, setThirdPartyExtendable, &sdk.FileOptionsParameters{})

if err == nil {
clearAllocation(allocationID)
Expand Down
1 change: 1 addition & 0 deletions zboxcore/fileref/fileref.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type FileRef struct {
EncryptedKey string `json:"encrypted_key" mapstructure:"encrypted_key"`
EncryptedKeyPoint string `json:"encrypted_key_point" mapstructure:"encrypted_key_point"`
Collaborators []Collaborator `json:"collaborators" mapstructure:"collaborators"`
SignatureVersion int `json:"signature_version" mapstructure:"signature_version"`
}

func (fRef *FileRef) MetaID() string {
Expand Down
Loading

0 comments on commit e73e12a

Please sign in to comment.