From 39197417511a9a500a7aa473f1b6588fb3373f83 Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Wed, 16 Oct 2024 18:06:32 +0530 Subject: [PATCH 01/12] Usercreate,tokencreate,rbt/sc trancaction --- core/data_token.go | 2 +- core/did.go | 15 +- core/explorer.go | 177 ++++++++++++++++++++---- core/nft.go | 5 +- core/part_token.go | 9 ++ core/quorum_initiator.go | 130 ++++++++--------- core/smart_contract_token_operations.go | 86 ++++++++---- core/transfer.go | 44 ++++-- 8 files changed, 330 insertions(+), 138 deletions(-) diff --git a/core/data_token.go b/core/data_token.go index 04d631a4..ff696088 100644 --- a/core/data_token.go +++ b/core/data_token.go @@ -322,7 +322,7 @@ func (c *Core) commitDataToken(reqID string, did string, batchID string) *model. SenderPeerID: c.peerID, ContractBlock: sc.GetBlock(), } - td, pl, err := c.initiateConsensus(cr, sc, dc) + td, pl, _, err := c.initiateConsensus(cr, sc, dc) if err != nil { c.log.Error("Consensus failed", "err", err) br.Message = "Consensus failed" + err.Error() diff --git a/core/did.go b/core/did.go index 5818135c..eed7a95f 100644 --- a/core/did.go +++ b/core/did.go @@ -138,8 +138,14 @@ func (c *Core) CreateDID(didCreate *did.DIDCreate) (string, error) { // if err != nil { // return "", err // } + newDID := &ExplorerDID{ + PeerID: c.peerID, + DID: did, + Balance: 0, + DIDType: didCreate.Type, + } if !c.testNet { - c.ec.ExplorerCreateDID(c.peerID, did) + c.ec.ExplorerCreateDID(newDID) } return did, nil } @@ -178,7 +184,12 @@ func (c *Core) AddDID(dc *did.DIDCreate) *model.BasicResponse { br.Message = err.Error() return br } - c.ec.ExplorerCreateDID(c.peerID, ds) + newDID := &ExplorerDID{ + PeerID: c.peerID, + DID: ds, + DIDType: dc.Type, + } + c.ec.ExplorerCreateDID(newDID) br.Status = true br.Message = "DID added successfully" br.Result = ds diff --git a/core/explorer.go b/core/explorer.go index 4f9a32a7..73f9098a 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -2,6 +2,7 @@ package core import ( "fmt" + "io" "net/http" "strings" @@ -14,11 +15,15 @@ import ( const ( ExplorerBasePath string = "/api/v2/services/app/Rubix/" - ExplorerCreateDIDAPI string = "CreateOrUpdateRubixUser" + ExplorerCreateDIDAPI string = "/api/user/create" ExplorerTransactionAPI string = "CreateOrUpdateRubixTransaction" ExplorerCreateDataTransAPI string = "create-datatokens" ExplorerMapDIDAPI string = "map-did" ExplorerURLTable string = "ExplorerURLTable" + ExplorerRBTTransactionAPI string = "/api/transactions/rbt" + ExplorerSCTransactionAPI string = "/api/transactions/sc" + ExplorerTokenCreateAPI string = "/api/token/create" + ExplorerUserDetailsTable string = "ExplorerUserDetails" ) type ExplorerClient struct { @@ -28,10 +33,11 @@ type ExplorerClient struct { } type ExplorerDID struct { - PeerID string `json:"peerid"` + PeerID string `json:"peer_id"` DID string `json:"user_did"` - IPAddress string `json:"ipaddress"` + IPAddress string `json:"ip_addess"` Balance int `json:"balance"` + DIDType int `json:"did_type"` } type ExplorerMapDID struct { @@ -40,18 +46,29 @@ type ExplorerMapDID struct { PeerID string `json:"peer_id"` } -type ExplorerTrans struct { - TID string `json:"transaction_id"` - SenderDID string `json:"sender_did"` - ReceiverDID string `json:"receiver_did"` - TokenTime float64 `json:"token_time"` - TokenIDs []string `json:"token_id"` - Amount float64 `json:"amount"` - TrasnType int `json:"transaction_type"` - QuorumList []string `json:"quorum_list"` - DeployerDID string `json:"deployer_did"` - ExecutorDID string `json:"executor_did"` - //BlockHash string `json:"block_hash"` +// type ExplorerTrans struct { +// TID string `json:"transaction_id"` +// SenderDID string `json:"sender_did"` +// ReceiverDID string `json:"receiver_did"` +// TokenTime float64 `json:"token_time"` +// TokenIDs []string `json:"token_id"` +// Amount float64 `json:"amount"` +// TrasnType int `json:"transaction_type"` +// QuorumList []string `json:"quorum_list"` +// DeployerDID string `json:"deployer_did"` +// ExecutorDID string `json:"executor_did"` +// //BlockHash string `json:"block_hash"` +// } + +type ExplorerCreateToken struct { + TokenID string `json:"token_id"` + TokenValue float64 `json:"token_value"` + Network int `json:"network"` + BlockNumber int `json:"block_num"` + UserDID string `json:"user_did"` + TokenType int `json:"token_type"` + QuorumList []string `json:"quorum_list"` + PledgeInfo *PledgeDetails `json:"pledge_info"` } type ExplorerDataTrans struct { @@ -66,16 +83,55 @@ type ExplorerDataTrans struct { QuorumList map[string]map[string]float64 `json:"quorum_list"` } +type ExplorerRBTTrans struct { + TokenHashes []string `json:"token_hash"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + BlockNumber int32 `json:"block_number"` //it will be different for each token + SenderDID string `json:"sender"` + ReceiverDID string `json:"receiver"` + Amount float64 `json:"amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo *PledgeDetails `json:"pledge_info"` + Comments string `json:"comments"` +} +type ExplorerSCTrans struct { + SCTokenHash string `json:"sc_token_hash"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + BlockNumber int `json:"block_number"` + BlockHash string `json:"block_hash"` + ExecutorDID string `json:"executor"` + DeployerDID string `json:"deployer"` + Creator string `json:"creator"` + PledgeAmount float64 `json:"pledge_amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo *PledgeDetails `json:"pledge_info"` + Comments string `json:"comments"` +} + type ExplorerResponse struct { Message string `json:"Message"` Status bool `json:"Status"` } +type ExplorerUserCreateResponse struct { + Message string `json:"message"` + APIKey string `json:"apiKey"` + Expiration string `json:"expiration"` +} + type ExplorerURL struct { URL string `gorm:"column:url;primaryKey" json:"ExplorerURL"` Port int `gorm:"column:port" json:"Explorerport"` } +type ExplorerUser struct { + DID string `gorm:"column:did;primaryKey" json:"did"` + APIKey string `gorm:"column:apiKey" json:"apiKey"` + Expiration string `gorm:"column:expiration" json:"expiration"` +} + func (c *Core) InitRubixExplorer() error { err := c.s.Init(ExplorerURLTable, &ExplorerURL{}, true) @@ -84,6 +140,12 @@ func (c *Core) InitRubixExplorer() error { return err } + err = c.s.Init(ExplorerUserDetailsTable, &ExplorerUser{}, true) + if err != nil { + c.log.Error("Failed to initialise storage ExplorerUserDetails ", "err", err) + return err + } + url := "deamon-explorer.azurewebsites.net" if c.testNet { url = "rubix-deamon-api.ensurity.com" @@ -119,7 +181,7 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp } for _, url := range urls { - req, err := ec.JSONRequestForExplorer(method, ExplorerBasePath+path, input, url) + req, err := ec.JSONRequestForExplorer(method, path, input, url) if err != nil { ec.log.Error("Request could not be sent to : "+url, "err", err) continue @@ -131,7 +193,8 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - str := fmt.Sprintf("Http Request failed with status %d for "+url, resp.StatusCode) + bodyBytes, _ := io.ReadAll(resp.Body) + str := fmt.Sprintf("Http Request failed with status %d for %s. Response: %s", resp.StatusCode, url, string(bodyBytes)) ec.log.Error(str) continue } @@ -147,20 +210,22 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp return nil } -func (ec *ExplorerClient) ExplorerCreateDID(peerID string, did string) error { - ed := ExplorerDID{ - PeerID: peerID, - DID: did, - } - var er ExplorerResponse +func (ec *ExplorerClient) ExplorerCreateDID(ed *ExplorerDID) error { + // ed := ExplorerDID{ + // PeerID: peerID, + // DID: did, + // } + var er ExplorerUserCreateResponse + ed.IPAddress = "0.0.0.0" err := ec.SendExploerJSONRequest("POST", ExplorerCreateDIDAPI, &ed, &er) if err != nil { return err } - if !er.Status { + if er.Message != "User created successfully!" { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } + ec.AddDIDKey(ed.DID, er) return nil } @@ -182,9 +247,22 @@ func (ec *ExplorerClient) ExplorerMapDID(oldDid string, newDID string, peerID st return nil } -func (ec *ExplorerClient) ExplorerTransaction(et *ExplorerTrans) error { +// func (ec *ExplorerClient) ExplorerTransaction(et *ExplorerTrans) error { +// var er ExplorerResponse +// err := ec.SendExploerJSONRequest("POST", ExplorerTransactionAPI, et, &er) +// if err != nil { +// return err +// } +// if !er.Status { +// ec.log.Error("Failed to update explorer", "msg", er.Message) +// return fmt.Errorf("failed to update explorer") +// } +// return nil +// } + +func (ec *ExplorerClient) ExplorerTokenCreate(et *ExplorerCreateToken) error { var er ExplorerResponse - err := ec.SendExploerJSONRequest("POST", ExplorerTransactionAPI, et, &er) + err := ec.SendExploerJSONRequest("POST", ExplorerTokenCreateAPI, et, &er) if err != nil { return err } @@ -208,6 +286,32 @@ func (ec *ExplorerClient) ExplorerDataTransaction(et *ExplorerDataTrans) error { return nil } +func (ec *ExplorerClient) ExplorerRBTTransaction(et *ExplorerRBTTrans) error { + var er ExplorerResponse + err := ec.SendExploerJSONRequest("POST", ExplorerRBTTransactionAPI, et, &er) + if err != nil { + return err + } + if !er.Status { + ec.log.Error("Failed to update explorer", "msg", er.Message) + return fmt.Errorf("failed to update explorer") + } + return nil +} + +func (ec *ExplorerClient) ExplorerSCTransaction(et *ExplorerSCTrans) error { + var er ExplorerResponse + err := ec.SendExploerJSONRequest("POST", ExplorerSCTransactionAPI, et, &er) + if err != nil { + return err + } + if !er.Status { + ec.log.Error("Failed to update explorer", "msg", er.Message) + return fmt.Errorf("failed to update explorer") + } + return nil +} + func (c *Core) AddExplorer(links []string) error { var eurl []ExplorerURL @@ -270,3 +374,24 @@ func (ec *ExplorerClient) GetAllExplorer() ([]string, error) { } return urls, nil } + +func (ec *ExplorerClient) AddDIDKey(did string, er ExplorerUserCreateResponse) error { + + eu := ExplorerUser{} + err := ec.es.Read(ExplorerUserDetailsTable, eu, "did=?", did) + if err != nil { + eu.DID = did + eu.APIKey = er.APIKey + eu.Expiration = er.Expiration + err = ec.es.Write(ExplorerUserDetailsTable, eu) + if err != nil { + return err + } + } else { + eu.APIKey = er.APIKey + eu.Expiration = er.Expiration + ec.es.Update(ExplorerUserDetailsTable, eu, "did=?", did) + } + + return nil +} diff --git a/core/nft.go b/core/nft.go index 94bfd2a7..6c864e70 100644 --- a/core/nft.go +++ b/core/nft.go @@ -3,7 +3,6 @@ package core import ( "bytes" "encoding/json" - "fmt" "io/ioutil" "os" "strings" @@ -321,10 +320,10 @@ func (c *Core) addNFTSaleContract(reqID string, sr *NFTSaleReq) *model.BasicResp SenderPeerID: c.peerID, ContractBlock: sc.GetBlock(), } - _, _, err = c.initiateConsensus(cr, sc, dc) + _, _, _, err = c.initiateConsensus(cr, sc, dc) c.log.Info("NFTs sale contract added successfully") resp.Status = true - msg := fmt.Sprintf("NFTs sale contract added successfully") + msg := "NFTs sale contract added successfully" resp.Message = msg return resp } diff --git a/core/part_token.go b/core/part_token.go index 094fd4e0..4a0e4f00 100644 --- a/core/part_token.go +++ b/core/part_token.go @@ -269,6 +269,15 @@ func (c *Core) createPartToken(dc did.DIDCrypto, did string, tkn string, parts [ c.log.Error("Failed to create part token, failed to add token chan block", "err", err) return nil, err } + newPartToken := &ExplorerCreateToken{ + TokenID: pt, + TokenValue: parts[i], + BlockNumber: 0, + UserDID: did, + TokenType: c.TokenType(PartString), + QuorumList: []string{}, + } + c.ec.ExplorerTokenCreate(newPartToken) } bti := &block.TransInfo{ Tokens: []block.TransTokens{ diff --git a/core/quorum_initiator.go b/core/quorum_initiator.go index f6c36a73..698d0539 100644 --- a/core/quorum_initiator.go +++ b/core/quorum_initiator.go @@ -295,7 +295,7 @@ func (c *Core) sendQuorumCredit(cr *ConensusRequest) { // c.qlock.Unlock() } -func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc did.DIDCrypto) (*model.TransactionDetails, map[string]map[string]float64, error) { +func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc did.DIDCrypto) (*model.TransactionDetails, map[string]map[string]float64, *PledgeDetails, error) { cs := ConsensusStatus{ Credit: CreditScore{ Credit: make([]CreditSignature, 0), @@ -350,7 +350,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc ql := c.qm.GetQuorum(cr.Type, lastCharTID) //passing lastCharTID as a parameter. Made changes in GetQuorum function to take 2 arguments if ql == nil || len(ql) < MinQuorumRequired { c.log.Error("Failed to get required quorums") - return nil, nil, fmt.Errorf("failed to get required quorums") + return nil, nil, nil, fmt.Errorf("failed to get required quorums") } var finalQl []string @@ -359,12 +359,12 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc finalQl, errFQL = c.GetFinalQuorumList(ql) if errFQL != nil { c.log.Error("unable to get consensus from quorum(s). err: ", errFQL) - return nil, nil, errFQL + return nil, nil, nil, errFQL } cr.QuorumList = finalQl if len(finalQl) < MinQuorumRequired { c.log.Error("quorum(s) are unavailable for this trnx") - return nil, nil, fmt.Errorf("quorum(s) are unavailable for this trnx. retry trnx after some time") + return nil, nil, nil, fmt.Errorf("quorum(s) are unavailable for this trnx. retry trnx after some time") } } else { cr.QuorumList = ql @@ -419,13 +419,13 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if unlockErr != nil { c.log.Error(unlockErr.Error() + "Locked tokens could not be unlocked") } - return nil, nil, err + return nil, nil, nil, err } nb, err := c.pledgeQuorumToken(cr, sc, tid, dc) if err != nil { c.log.Error("Failed to pledge token", "err", err) - return nil, nil, err + return nil, nil, nil, err } ti := sc.GetTransTokenInfo() @@ -452,7 +452,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc rp, err := c.getPeer(cr.ReceiverPeerID+"."+sc.GetReceiverDID(), "") if err != nil { c.log.Error("Receiver not connected", "err", err) - return nil, nil, err + return nil, nil, nil, err } defer rp.Close() sr := SendTokenRequest{ @@ -504,7 +504,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = rp.SendJSONRequest("POST", APISendReceiverToken, nil, &sr, &br, true) if err != nil { c.log.Error("Unable to send tokens to receiver", "err", err) - return nil, nil, err + return nil, nil, nil, err } if strings.Contains(br.Message, "failed to sync tokenchain") { tokenPrefix := "Token: " @@ -523,40 +523,40 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if err1 != nil { errMsg := fmt.Sprintf("Consensus failed due to token chain sync issue, issueType string conversion, err %v", err1) c.log.Error(errMsg) - return nil, nil, fmt.Errorf(errMsg) + return nil, nil, nil, fmt.Errorf(errMsg) } c.log.Debug("issue type in int is ", issueTypeInt) syncIssueTokenDetails, err2 := c.w.ReadToken(token) if err2 != nil { errMsg := fmt.Sprintf("Consensus failed due to tokenchain sync issue, err %v", err2) c.log.Error(errMsg) - return nil, nil, fmt.Errorf(errMsg) + return nil, nil, nil, fmt.Errorf(errMsg) } c.log.Debug("sync issue token details ", syncIssueTokenDetails) if issueTypeInt == TokenChainNotSynced { syncIssueTokenDetails.TokenStatus = wallet.TokenChainSyncIssue c.log.Debug("sync issue token details status updated", syncIssueTokenDetails) c.w.UpdateToken(syncIssueTokenDetails) - return nil, nil, errors.New(br.Message) + return nil, nil, nil, errors.New(br.Message) } } if !br.Status { c.log.Error("Unable to send tokens to receiver", "msg", br.Message) - return nil, nil, fmt.Errorf("unable to send tokens to receiver, " + br.Message) + return nil, nil, nil, fmt.Errorf("unable to send tokens to receiver, " + br.Message) } // br.Result will contain the new token state after sending tokens to receiver as a response to APISendReceiverToken newtokenhashresult, ok := br.Result.([]interface{}) if !ok { c.log.Error("Type assertion to string failed") - return nil, nil, fmt.Errorf("Type assertion to string failed") + return nil, nil, nil, fmt.Errorf("Type assertion to string failed") } var newtokenhashes []string for i, newTokenHash := range newtokenhashresult { statehash, ok := newTokenHash.(string) if !ok { c.log.Error("Type assertion to string failed at index", i) - return nil, nil, fmt.Errorf("Type assertion to string failed at index", i) + return nil, nil, nil, fmt.Errorf("Type assertion to string failed at index", i) } newtokenhashes = append(newtokenhashes, statehash) } @@ -565,12 +565,12 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, newtokenhashes, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } err = c.w.TokensTransferred(sc.GetSenderDID(), ti, nb, rp.IsLocal(), sr.PinningServiceMode) if err != nil { c.log.Error("Failed to transfer tokens", "err", err) - return nil, nil, err + return nil, nil, nil, err } for _, t := range ti { c.w.UnPin(t.Token, wallet.PrevSenderRole, sc.GetSenderDID()) @@ -580,7 +580,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc nbid, err := nb.GetBlockID(ti[0].Token) if err != nil { c.log.Error("Failed to get block id", "err", err) - return nil, nil, err + return nil, nil, nil, err } td := model.TransactionDetails{ @@ -599,10 +599,10 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.initiateUnpledgingProcess(cr, td.TransactionID, td.Epoch) if err != nil { c.log.Error("Failed to store transactiond details with quorum ", "err", err) - return nil, nil, err + return nil, nil, nil, err } - return &td, pl, nil + return &td, pl, pds, nil case PinningServiceMode: c.log.Debug("Mode = PinningServiceMode ") c.log.Debug("Pinning Node PeerId", cr.PinningNodePeerID) @@ -610,7 +610,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc rp, err := c.getPeer(cr.PinningNodePeerID+"."+sc.GetPinningServiceDID(), "") if err != nil { c.log.Error("Pinning Node not connected", "err", err) - return nil, nil, err + return nil, nil, nil, err } defer rp.Close() sr := SendTokenRequest{ @@ -659,7 +659,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = rp.SendJSONRequest("POST", APISendReceiverToken, nil, &sr, &br, true) if err != nil { c.log.Error("Unable to send tokens to receiver", "err", err) - return nil, nil, err + return nil, nil, nil, err } if strings.Contains(br.Message, "failed to sync tokenchain") { @@ -679,41 +679,41 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if err1 != nil { errMsg := fmt.Sprintf("Consensus failed due to token chain sync issue, issueType string conversion, err %v", err1) c.log.Error(errMsg) - return nil, nil, fmt.Errorf(errMsg) + return nil, nil, nil, fmt.Errorf(errMsg) } c.log.Debug("issue type in int is ", issueTypeInt) syncIssueTokenDetails, err2 := c.w.ReadToken(token) if err2 != nil { errMsg := fmt.Sprintf("Consensus failed due to tokenchain sync issue, err %v", err2) c.log.Error(errMsg) - return nil, nil, fmt.Errorf(errMsg) + return nil, nil, nil, fmt.Errorf(errMsg) } c.log.Debug("sync issue token details ", syncIssueTokenDetails) if issueTypeInt == TokenChainNotSynced { syncIssueTokenDetails.TokenStatus = wallet.TokenChainSyncIssue c.log.Debug("sync issue token details status updated", syncIssueTokenDetails) c.w.UpdateToken(syncIssueTokenDetails) - return nil, nil, errors.New(br.Message) + return nil, nil, nil, errors.New(br.Message) } } if !br.Status { c.log.Error("Unable to send tokens to pinning node", "msg", br.Message) - return nil, nil, fmt.Errorf("unable to send tokens to pinning node, " + br.Message) + return nil, nil, nil, fmt.Errorf("unable to send tokens to pinning node, " + br.Message) } // br.Result will contain the new token state after sending tokens to receiver as a response to APISendReceiverToken newtokenhashresult, ok := br.Result.([]interface{}) if !ok { c.log.Error("Type assertion to string failed") - return nil, nil, fmt.Errorf("Type assertion to string failed") + return nil, nil, nil, fmt.Errorf("Type assertion to string failed") } var newtokenhashes []string for i, newTokenHash := range newtokenhashresult { statehash, ok := newTokenHash.(string) if !ok { c.log.Error("Type assertion to string failed at index", i) - return nil, nil, fmt.Errorf("Type assertion to string failed at index", i) + return nil, nil, nil, fmt.Errorf("Type assertion to string failed at index", i) } newtokenhashes = append(newtokenhashes, statehash) } @@ -722,13 +722,13 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, newtokenhashes, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } err = c.w.TokensTransferred(sc.GetSenderDID(), ti, nb, rp.IsLocal(), sr.PinningServiceMode) if err != nil { c.log.Error("Failed to transfer tokens", "err", err) - return nil, nil, err + return nil, nil, nil, err } //Commented out this unpinning part so that the unpin is not done from the sender side // for _, t := range ti { @@ -739,7 +739,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc nbid, err := nb.GetBlockID(ti[0].Token) if err != nil { c.log.Error("Failed to get block id", "err", err) - return nil, nil, err + return nil, nil, nil, err } td := model.TransactionDetails{ @@ -757,9 +757,9 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.initiateUnpledgingProcess(cr, td.TransactionID, td.Epoch) if err != nil { c.log.Error("Failed to store transactiond details with quorum ", "err", err) - return nil, nil, err + return nil, nil, nil, err } - return &td, pl, nil + return &td, pl, pds, nil case SelfTransferMode: var quorumInfo []QuorumDIDPeerMap = make([]QuorumDIDPeerMap, 0) var selfAddress string = cr.ReceiverPeerID + "." + sc.GetReceiverDID() @@ -805,7 +805,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if err != nil { errMsg := fmt.Errorf("failed while update of self transfer tokens, err: %v", err) c.log.Error(errMsg.Error()) - return nil, nil, errMsg + return nil, nil, nil, errMsg } @@ -813,7 +813,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, updatedTokenHashes, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } //Checking prev block details (i.e. the latest block before transferring) by sender. Sender will connect with old quorums, and update about the exhausted token state hashes to quorums for them to unpledge their tokens. @@ -850,7 +850,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc nbid, err := nb.GetBlockID(ti[0].Token) if err != nil { c.log.Error("Failed to get block id", "err", err) - return nil, nil, err + return nil, nil, nil, err } td := model.TransactionDetails{ @@ -869,15 +869,15 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.initiateUnpledgingProcess(cr, td.TransactionID, td.Epoch) if err != nil { c.log.Error("Failed to store transactiond details with quorum ", "err", err) - return nil, nil, err + return nil, nil, nil, err } - return &td, pl, nil + return &td, pl, pds, nil case DTCommitMode: err = c.w.CreateTokenBlock(nb) if err != nil { c.log.Error("Failed to create token block", "err", err) - return nil, nil, err + return nil, nil, nil, err } td := model.TransactionDetails{ TransactionID: tid, @@ -890,46 +890,46 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, nil, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } - return &td, pl, nil + return &td, pl, pds, nil case SmartContractDeployMode: //Create tokechain for the smart contract token and add genesys block err = c.w.AddTokenBlock(cr.SmartContractToken, nb) if err != nil { c.log.Error("smart contract token chain creation failed", "err", err) - return nil, nil, err + return nil, nil, nil, err } //update smart contracttoken status to deployed in DB err = c.w.UpdateSmartContractStatus(cr.SmartContractToken, wallet.TokenIsDeployed) if err != nil { c.log.Error("Failed to update smart contract Token deploy detail in storage", err) - return nil, nil, err + return nil, nil, nil, err } c.log.Debug("creating commited token block") //create new committed block to be updated to the commited RBT tokens err = c.createCommitedTokensBlock(nb, cr.SmartContractToken, dc) if err != nil { c.log.Error("Failed to create commited RBT tokens block ", "err", err) - return nil, nil, err + return nil, nil, nil, err } //update committed RBT token with the new block also and lock the RBT //and change token status to commited, to prevent being used for txn or pledging commitedRbtTokens, err := nb.GetCommitedTokenDetials(cr.SmartContractToken) if err != nil { c.log.Error("Failed to fetch commited rbt tokens", "err", err) - return nil, nil, err + return nil, nil, nil, err } err = c.w.CommitTokens(sc.GetDeployerDID(), commitedRbtTokens) if err != nil { c.log.Error("Failed to update commited RBT tokens in DB ", "err", err) - return nil, nil, err + return nil, nil, nil, err } newBlockId, err := nb.GetBlockID(cr.SmartContractToken) if err != nil { c.log.Error("failed to get new block id ", "err", err) - return nil, nil, err + return nil, nil, nil, err } //Latest Smart contract token hash after being deployed. @@ -942,7 +942,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, []string{newtokenIDTokenStateHash}, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } //Todo pubsub - publish smart contract token details @@ -973,10 +973,10 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.initiateUnpledgingProcess(cr, txnDetails.TransactionID, txnDetails.Epoch) if err != nil { c.log.Error("Failed to store transactiond details with quorum ", "err", err) - return nil, nil, err + return nil, nil, nil, err } - return &txnDetails, pl, nil + return &txnDetails, pl, pds, nil case SmartContractExecuteMode: //Get the latest block details before being executed to get the old signers b := c.w.GetLatestTokenBlock(cr.SmartContractToken, nb.GetTokenType(cr.SmartContractToken)) @@ -986,19 +986,19 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.w.AddTokenBlock(cr.SmartContractToken, nb) if err != nil { c.log.Error("smart contract token chain creation failed", "err", err) - return nil, nil, err + return nil, nil, nil, err } //update smart contracttoken status to deployed in DB err = c.w.UpdateSmartContractStatus(cr.SmartContractToken, wallet.TokenIsExecuted) if err != nil { c.log.Error("Failed to update smart contract Token execute detail in storage", err) - return nil, nil, err + return nil, nil, nil, err } newBlockId, err := nb.GetBlockID(cr.SmartContractToken) if err != nil { c.log.Error("failed to get new block id ", "err", err) - return nil, nil, err + return nil, nil, nil, err } //Latest Smart contract token hash after being executed. @@ -1011,7 +1011,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, []string{newtokenIDTokenStateHash}, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } //Todo pubsub - publish smart contract token details @@ -1056,14 +1056,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.initiateUnpledgingProcess(cr, txnDetails.TransactionID, txnDetails.Epoch) if err != nil { c.log.Error("Failed to store transactiond details with quorum ", "err", err) - return nil, nil, err + return nil, nil, nil, err } - return &txnDetails, pl, nil + return &txnDetails, pl, pds, nil default: err := fmt.Errorf("invalid consensus request mode: %v", cr.Mode) c.log.Error(err.Error()) - return nil, nil, err + return nil, nil, nil, err } } @@ -1503,9 +1503,9 @@ func (c *Core) pledgeQuorumToken(cr *ConensusRequest, sc *contract.Contract, tid deployerSign := &block.InitiatorSignature{ NLSSShare: deployerNLSSShare, PrivateSign: deployerPrivSign, - DID: bti.DeployerDID, - Hash: signData, - SignType: deployerSignType, + DID: bti.DeployerDID, + Hash: signData, + SignType: deployerSignType, } var smartContractTokenValue float64 @@ -1555,9 +1555,9 @@ func (c *Core) pledgeQuorumToken(cr *ConensusRequest, sc *contract.Contract, tid executorSign := &block.InitiatorSignature{ NLSSShare: executorNLSSShare, PrivateSign: executorPrivSign, - DID: bti.ExecutorDID, - Hash: signData, - SignType: executorSignType, + DID: bti.ExecutorDID, + Hash: signData, + SignType: executorSignType, } tcb = block.TokenChainBlock{ @@ -1594,9 +1594,9 @@ func (c *Core) pledgeQuorumToken(cr *ConensusRequest, sc *contract.Contract, tid senderSign := &block.InitiatorSignature{ NLSSShare: senderNLSSShare, PrivateSign: senderPrivSign, - DID: senderdid, - Hash: signData, - SignType: senderSignType, + DID: senderdid, + Hash: signData, + SignType: senderSignType, } bti.SenderDID = sc.GetSenderDID() diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index 7aaf51c2..5fab4d4c 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -2,6 +2,8 @@ package core import ( "fmt" + "strconv" + "strings" "time" "github.com/rubixchain/rubixgoplatform/contract" @@ -147,7 +149,7 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma TransactionEpoch: txEpoch, } - txnDetails, _, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) + txnDetails, _, pds, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) if err != nil { c.log.Error("Consensus failed", "err", err) @@ -161,17 +163,34 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma c.w.AddTransactionHistory(txnDetails) tokens := make([]string, 0) tokens = append(tokens, deployReq.SmartContractToken) - explorerTrans := &ExplorerTrans{ - TID: txnDetails.TransactionID, - DeployerDID: did, - Amount: deployReq.RBTAmount, - TrasnType: conensusRequest.Type, - TokenIDs: tokens, - QuorumList: conensusRequest.QuorumList, - TokenTime: float64(dif.Milliseconds()), - //BlockHash: txnDetails.BlockID, - } - c.ec.ExplorerTransaction(explorerTrans) + // _ = &ExplorerTrans{ + // TID: txnDetails.TransactionID, + // DeployerDID: did, + // Amount: deployReq.RBTAmount, + // TrasnType: conensusRequest.Type, + // TokenIDs: tokens, + // QuorumList: conensusRequest.QuorumList, + // TokenTime: float64(dif.Milliseconds()), + // //BlockHash: txnDetails.BlockID, + // } + blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] + // Convert the string part to an int + blockNoInt, _ := strconv.Atoi(blockNoPart) + + eTrans := &ExplorerSCTrans{ + SCTokenHash: deployReq.SmartContractToken, + TransactionID: txnDetails.TransactionID, + Network: conensusRequest.Type, + BlockHash: txnDetails.BlockID, + BlockNumber: blockNoInt, + DeployerDID: did, + Creator: did, + PledgeAmount: deployReq.RBTAmount, + QuorumList: conensusRequest.QuorumList, + PledgeInfo: pds, + Comments: deployReq.Comment, + } + c.ec.ExplorerSCTransaction(eTrans) c.log.Info("Smart Contract Token Deployed successfully", "duration", dif) resp.Status = true @@ -193,7 +212,7 @@ func (c *Core) ExecuteSmartContractToken(reqID string, executeReq *model.Execute func (c *Core) executeSmartContractToken(reqID string, executeReq *model.ExecuteSmartContractRequest) *model.BasicResponse { st := time.Now() txEpoch := int(st.Unix()) - + resp := &model.BasicResponse{ Status: false, } @@ -291,7 +310,7 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute TransactionEpoch: txEpoch, } - txnDetails, _, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) + txnDetails, _, pds, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) if err != nil { c.log.Error("Consensus failed", "err", err) @@ -303,18 +322,33 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute txnDetails.TotalTime = float64(dif.Milliseconds()) c.w.AddTransactionHistory(txnDetails) - tokens := make([]string, 0) - tokens = append(tokens, executeReq.SmartContractToken) - explorerTrans := &ExplorerTrans{ - TID: txnDetails.TransactionID, - ExecutorDID: did, - TrasnType: conensusRequest.Type, - TokenIDs: tokens, - QuorumList: conensusRequest.QuorumList, - TokenTime: float64(dif.Milliseconds()), - //BlockHash: txnDetails.BlockID, - } - c.ec.ExplorerTransaction(explorerTrans) + + // explorerTrans := &ExplorerTrans{ + // TID: txnDetails.TransactionID, + // ExecutorDID: did, + // TrasnType: conensusRequest.Type, + // TokenIDs: tokens, + // QuorumList: conensusRequest.QuorumList, + // TokenTime: float64(dif.Milliseconds()), + // //BlockHash: txnDetails.BlockID, + // } + blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] + // Convert the string part to an int + blockNoInt, _ := strconv.Atoi(blockNoPart) + + eTrans := &ExplorerSCTrans{ + SCTokenHash: executeReq.SmartContractToken, + TransactionID: txnDetails.TransactionID, + Network: conensusRequest.Type, + BlockHash: strings.Split(txnDetails.BlockID, "-")[1], + BlockNumber: blockNoInt, + ExecutorDID: did, + Creator: smartContractInfo.OwnerDID, + QuorumList: conensusRequest.QuorumList, + PledgeInfo: pds, + Comments: executeReq.Comment, + } + c.ec.ExplorerSCTransaction(eTrans) /* newEvent := model.NewContractEvent{ Contract: executeReq.SmartContractToken, Did: did, diff --git a/core/transfer.go b/core/transfer.go index b9de45fa..65d56515 100644 --- a/core/transfer.go +++ b/core/transfer.go @@ -279,7 +279,7 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) cr := getConsensusRequest(req.Type, c.peerID, rpeerid, sc.GetBlock(), txEpoch, isSelfRBTTransfer) - td, _, err := c.initiateConsensus(cr, sc, dc) + td, _, pds, err := c.initiateConsensus(cr, sc, dc) if err != nil { if c.noBalanceQuorumCount > 2 { resp.Message = "Consensus failed due to insufficient balance in Quorum(s), Retry transaction after sometime" @@ -315,18 +315,20 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) resp.Message = "Consensus failed" + err.Error() return resp } */ - etrans := &ExplorerTrans{ - TID: td.TransactionID, + etrans := &ExplorerRBTTrans{ + TokenHashes: wta, + TransactionID: td.TransactionID, + // BlockNumber: td.BlockID, + Network: req.Type, SenderDID: senderDID, ReceiverDID: receiverdid, Amount: req.TokenCount, - TrasnType: req.Type, - TokenIDs: wta, QuorumList: cr.QuorumList, - TokenTime: float64(dif.Milliseconds()), - //BlockHash: blockHash, + PledgeInfo: pds, + Comments: req.Comment, } - c.ec.ExplorerTransaction(etrans) + + c.ec.ExplorerRBTTransaction(etrans) c.log.Info("Transfer finished successfully", "duration", dif, " trnxid", td.TransactionID) resp.Status = true msg := fmt.Sprintf("Transfer finished successfully in %v with trnxid %v", dif, td.TransactionID) @@ -523,7 +525,7 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ ContractBlock: sc.GetBlock(), Mode: PinningServiceMode, } - td, _, err := c.initiateConsensus(cr, sc, dc) + td, _, pds, err := c.initiateConsensus(cr, sc, dc) if err != nil { c.log.Error("Consensus failed", "err", err) resp.Message = "Consensus failed" + err.Error() @@ -534,17 +536,29 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ td.Amount = req.TokenCount td.TotalTime = float64(dif.Milliseconds()) c.w.AddTransactionHistory(td) - etrans := &ExplorerTrans{ - TID: td.TransactionID, + // etrans := &ExplorerTrans{ + // TID: td.TransactionID, + // SenderDID: did, + // ReceiverDID: pinningNodeDID, + // Amount: req.TokenCount, + // TrasnType: req.Type, + // TokenIDs: wta, + // QuorumList: cr.QuorumList, + // TokenTime: float64(dif.Milliseconds()), + // } Remove comments + etrans := &ExplorerRBTTrans{ + TokenHashes: wta, + TransactionID: td.TransactionID, + // BlockNumber: td.BlockID, + Network: req.Type, SenderDID: did, ReceiverDID: pinningNodeDID, Amount: req.TokenCount, - TrasnType: req.Type, - TokenIDs: wta, QuorumList: cr.QuorumList, - TokenTime: float64(dif.Milliseconds()), + PledgeInfo: pds, + Comments: req.Comment, } - c.ec.ExplorerTransaction(etrans) + c.ec.ExplorerRBTTransaction(etrans) c.log.Info("Pinning finished successfully", "duration", dif, " trnxid", td.TransactionID) resp.Status = true msg := fmt.Sprintf("Pinning finished successfully in %v with trnxid %v", dif, td.TransactionID) From d9a84943ca43f954902b3786195e0199c839d2df Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Fri, 18 Oct 2024 17:57:50 +0530 Subject: [PATCH 02/12] Explorer structure updated for transaction & part token create --- client/explorer.go | 12 ++ command/command.go | 5 + command/explorer.go | 29 +++- core/explorer.go | 210 +++++++++++++++--------- core/part_token.go | 18 +- core/quorum_initiator.go | 7 +- core/smart_contract_token_operations.go | 14 +- core/transfer.go | 54 +++--- server/config.go | 11 ++ server/server.go | 1 + setup/setup.go | 1 + wrapper/ensweb/client.go | 6 +- 12 files changed, 232 insertions(+), 136 deletions(-) diff --git a/client/explorer.go b/client/explorer.go index 6bcd2b17..9a15f51d 100644 --- a/client/explorer.go +++ b/client/explorer.go @@ -37,3 +37,15 @@ func (c *Client) GetAllExplorer() ([]string, string, bool) { } return rm.Result.Links, rm.Message, rm.Status } + +func (c *Client) AddUserAPIKey(did string, apiKey string) (string, bool) { + q := make(map[string]string) + q["did"] = did + q["apiKey"] = apiKey + var rm model.BasicResponse + err := c.sendJSONRequest("POST", setup.APIAddUserAPIKey, q, nil, &rm) + if err != nil { + return err.Error(), false + } + return rm.Message, rm.Status +} diff --git a/command/command.go b/command/command.go index be0cce9c..bdc367f4 100644 --- a/command/command.go +++ b/command/command.go @@ -93,6 +93,7 @@ const ( RecoverTokensCmd string = "recoverToken" ValidateTokenchainCmd string = "validatetokenchain" ValidateTokenCmd string = "validatetoken" + AddUserAPIKeyCmd string = "adduserapikey" ) var commands = []string{VersionCmd, @@ -285,6 +286,7 @@ type Command struct { pinningAddress string blockCount int smartContractChainValidation bool + apiKey string } func showVersion() { @@ -485,6 +487,7 @@ func Run(args []string) { flag.StringVar(&cmd.pinningAddress, "pinningAddress", "", "Pinning address") flag.IntVar(&cmd.blockCount, "blockCount", 0, "Number of blocks of the tokenchain to validate") flag.BoolVar(&cmd.smartContractChainValidation, "sctValidation", false, "Validate smart contract token chain") + flag.StringVar(&cmd.apiKey, "apikey", "", "Give the API Key corresponding to the DID") if len(os.Args) < 2 { fmt.Println("Invalid Command") @@ -664,6 +667,8 @@ func Run(args []string) { cmd.ValidateTokenchain() case ValidateTokenCmd: cmd.ValidateToken() + case AddUserAPIKeyCmd: + cmd.addUserAPIKey() default: cmd.log.Error("Invalid command") } diff --git a/command/explorer.go b/command/explorer.go index 11070427..02ef153d 100644 --- a/command/explorer.go +++ b/command/explorer.go @@ -1,6 +1,10 @@ package command -import "fmt" +import ( + "fmt" + "regexp" + "strings" +) func (cmd *Command) addExplorer() { if len(cmd.links) == 0 { @@ -41,3 +45,26 @@ func (cmd *Command) getAllExplorer() { } } } + +func (cmd *Command) addUserAPIKey() { + isAlphanumeric := regexp.MustCompile(`^[a-zA-Z0-9]*$`).MatchString(cmd.did) + if !isAlphanumeric { + cmd.log.Error("Invalid DID. Please provide valid DID") + return + } + if !strings.HasPrefix(cmd.did, "bafybmi") || len(cmd.did) != 59 { + cmd.log.Error("Invalid DID") + return + } + if cmd.apiKey == "" { + cmd.log.Error("API Key cannot be empty") + return + } + msg, status := cmd.c.AddUserAPIKey(cmd.did, cmd.apiKey) + + if !status { + cmd.log.Error("API Key could not be added, " + msg) + } else { + cmd.log.Info("API Key added successfully") + } +} diff --git a/core/explorer.go b/core/explorer.go index 73f9098a..a71844b8 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -14,16 +14,20 @@ import ( ) const ( - ExplorerBasePath string = "/api/v2/services/app/Rubix/" - ExplorerCreateDIDAPI string = "/api/user/create" - ExplorerTransactionAPI string = "CreateOrUpdateRubixTransaction" - ExplorerCreateDataTransAPI string = "create-datatokens" - ExplorerMapDIDAPI string = "map-did" - ExplorerURLTable string = "ExplorerURLTable" - ExplorerRBTTransactionAPI string = "/api/transactions/rbt" - ExplorerSCTransactionAPI string = "/api/transactions/sc" - ExplorerTokenCreateAPI string = "/api/token/create" - ExplorerUserDetailsTable string = "ExplorerUserDetails" + ExplorerBasePath string = "/api/v2/services/app/Rubix/" + ExplorerTokenCreateAPI string = "/api/token/create" + ExplorerTokenCreatePartsAPI string = "/api/token/create/parts" + ExplorerTokenCreateSCAPI string = "/api/token/create/sc" + ExplorerTokenCreateFTAPI string = "/api/token/create/ft" + ExplorerTokenCreateNFTAPI string = "/api/token/create/nft" + ExplorerCreateDIDAPI string = "/api/user/create" + ExplorerRBTTransactionAPI string = "/api/transactions/rbt" + ExplorerSCTransactionAPI string = "/api/transactions/sc" + ExplorerTransactionAPI string = "CreateOrUpdateRubixTransaction" + ExplorerCreateDataTransAPI string = "create-datatokens" + ExplorerMapDIDAPI string = "map-did" + ExplorerURLTable string = "ExplorerURLTable" + ExplorerUserDetailsTable string = "ExplorerUserDetails" ) type ExplorerClient struct { @@ -46,29 +50,32 @@ type ExplorerMapDID struct { PeerID string `json:"peer_id"` } -// type ExplorerTrans struct { -// TID string `json:"transaction_id"` -// SenderDID string `json:"sender_did"` -// ReceiverDID string `json:"receiver_did"` -// TokenTime float64 `json:"token_time"` -// TokenIDs []string `json:"token_id"` -// Amount float64 `json:"amount"` -// TrasnType int `json:"transaction_type"` -// QuorumList []string `json:"quorum_list"` -// DeployerDID string `json:"deployer_did"` -// ExecutorDID string `json:"executor_did"` -// //BlockHash string `json:"block_hash"` -// } +type Token struct { + TokenID string `json:"token_id"` + TokenValue float64 `json:"token_value"` +} + +type ChildToken struct { + TokenID string `json:"child_token_hash"` + TokenValue float64 `json:"child_token_value"` +} type ExplorerCreateToken struct { - TokenID string `json:"token_id"` - TokenValue float64 `json:"token_value"` - Network int `json:"network"` - BlockNumber int `json:"block_num"` - UserDID string `json:"user_did"` - TokenType int `json:"token_type"` - QuorumList []string `json:"quorum_list"` - PledgeInfo *PledgeDetails `json:"pledge_info"` + TokenID string `json:"token_id"` + TokenValue float64 `json:"token_value"` + Network int `json:"network"` + BlockNumber int `json:"block_num"` + UserDID string `json:"user_did"` + TokenType int `json:"token_type"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` +} + +type ExplorerCreateTokenParts struct { + UserDID string `json:"user_did"` + TokenType string `json:"token_type"` + ParentToken string `json:"parent_token_hash"` + ChildTokenList []ChildToken `json:"child_token_list"` } type ExplorerDataTrans struct { @@ -83,31 +90,37 @@ type ExplorerDataTrans struct { QuorumList map[string]map[string]float64 `json:"quorum_list"` } +type PledgeInfo struct { + PledgeDetails map[string][]string `json:"pledge_details"` + TokenList []Token `json:"pledged_token_list"` +} + type ExplorerRBTTrans struct { - TokenHashes []string `json:"token_hash"` - TransactionID string `json:"transaction_id"` - Network int `json:"network"` - BlockNumber int32 `json:"block_number"` //it will be different for each token - SenderDID string `json:"sender"` - ReceiverDID string `json:"receiver"` - Amount float64 `json:"amount"` - QuorumList []string `json:"quorum_list"` - PledgeInfo *PledgeDetails `json:"pledge_info"` - Comments string `json:"comments"` + TokenHashes []string `json:"token_hash"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + BlockHash string `json:"block_hash"` //it will be different for each token + SenderDID string `json:"sender"` + ReceiverDID string `json:"receiver"` + Amount float64 `json:"amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` + TokenList []Token `json:"token_list"` + Comments string `json:"comments"` } type ExplorerSCTrans struct { - SCTokenHash string `json:"sc_token_hash"` - TransactionID string `json:"transaction_id"` - Network int `json:"network"` - BlockNumber int `json:"block_number"` - BlockHash string `json:"block_hash"` - ExecutorDID string `json:"executor"` - DeployerDID string `json:"deployer"` - Creator string `json:"creator"` - PledgeAmount float64 `json:"pledge_amount"` - QuorumList []string `json:"quorum_list"` - PledgeInfo *PledgeDetails `json:"pledge_info"` - Comments string `json:"comments"` + SCTokenHash string `json:"sc_token_hash"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + BlockNumber int `json:"block_number"` + BlockHash string `json:"block_hash"` + ExecutorDID string `json:"executor"` + DeployerDID string `json:"deployer"` + Creator string `json:"creator"` + PledgeAmount float64 `json:"pledge_amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` + Comments string `json:"comments"` } type ExplorerResponse struct { @@ -127,9 +140,8 @@ type ExplorerURL struct { } type ExplorerUser struct { - DID string `gorm:"column:did;primaryKey" json:"did"` - APIKey string `gorm:"column:apiKey" json:"apiKey"` - Expiration string `gorm:"column:expiration" json:"expiration"` + DID string `gorm:"column:did;primaryKey" json:"did"` + APIKey string `gorm:"column:apiKey" json:"apiKey"` } func (c *Core) InitRubixExplorer() error { @@ -181,7 +193,13 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp } for _, url := range urls { - req, err := ec.JSONRequestForExplorer(method, path, input, url) + apiKeyForHeader := "" + if url == "https://rexplorer.azurewebsites.net" { + apiKeyForHeader = ec.getAPIKey(path, input) + } else { + apiKeyForHeader = "" + } + req, err := ec.JSONRequestForExplorer(method, path, input, url, apiKeyForHeader) if err != nil { ec.log.Error("Request could not be sent to : "+url, "err", err) continue @@ -206,15 +224,12 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp ec.log.Error("Invalid response from the node", "err", err) continue } + ec.log.Info("Details successfully stored in Explorer") } return nil } func (ec *ExplorerClient) ExplorerCreateDID(ed *ExplorerDID) error { - // ed := ExplorerDID{ - // PeerID: peerID, - // DID: did, - // } var er ExplorerUserCreateResponse ed.IPAddress = "0.0.0.0" err := ec.SendExploerJSONRequest("POST", ExplorerCreateDIDAPI, &ed, &er) @@ -225,7 +240,7 @@ func (ec *ExplorerClient) ExplorerCreateDID(ed *ExplorerDID) error { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } - ec.AddDIDKey(ed.DID, er) + ec.AddDIDKey(ed.DID, er.APIKey) return nil } @@ -247,19 +262,6 @@ func (ec *ExplorerClient) ExplorerMapDID(oldDid string, newDID string, peerID st return nil } -// func (ec *ExplorerClient) ExplorerTransaction(et *ExplorerTrans) error { -// var er ExplorerResponse -// err := ec.SendExploerJSONRequest("POST", ExplorerTransactionAPI, et, &er) -// if err != nil { -// return err -// } -// if !er.Status { -// ec.log.Error("Failed to update explorer", "msg", er.Message) -// return fmt.Errorf("failed to update explorer") -// } -// return nil -// } - func (ec *ExplorerClient) ExplorerTokenCreate(et *ExplorerCreateToken) error { var er ExplorerResponse err := ec.SendExploerJSONRequest("POST", ExplorerTokenCreateAPI, et, &er) @@ -273,6 +275,20 @@ func (ec *ExplorerClient) ExplorerTokenCreate(et *ExplorerCreateToken) error { return nil } +func (ec *ExplorerClient) ExplorerTokenCreateParts(et *ExplorerCreateTokenParts) error { + var er ExplorerResponse + fmt.Println("Calling API") + err := ec.SendExploerJSONRequest("POST", ExplorerTokenCreatePartsAPI, et, &er) + if err != nil { + return err + } + if !er.Status { + ec.log.Error("Failed to update explorer", "msg", er.Message) + return fmt.Errorf("failed to update explorer") + } + return nil +} + func (ec *ExplorerClient) ExplorerDataTransaction(et *ExplorerDataTrans) error { var er ExplorerResponse err := ec.SendExploerJSONRequest("POST", ExplorerCreateDataTransAPI, et, &er) @@ -375,23 +391,53 @@ func (ec *ExplorerClient) GetAllExplorer() ([]string, error) { return urls, nil } -func (ec *ExplorerClient) AddDIDKey(did string, er ExplorerUserCreateResponse) error { +func (c *Core) AddDIDKey(did string, apiKey string) error { + err := c.ec.AddDIDKey(did, apiKey) + if err != nil { + return err + } + return nil +} +func (ec *ExplorerClient) AddDIDKey(did string, apiKey string) error { eu := ExplorerUser{} - err := ec.es.Read(ExplorerUserDetailsTable, eu, "did=?", did) + err := ec.es.Read(ExplorerUserDetailsTable, &eu, "did=?", did) if err != nil { eu.DID = did - eu.APIKey = er.APIKey - eu.Expiration = er.Expiration + eu.APIKey = apiKey err = ec.es.Write(ExplorerUserDetailsTable, eu) if err != nil { return err } } else { - eu.APIKey = er.APIKey - eu.Expiration = er.Expiration - ec.es.Update(ExplorerUserDetailsTable, eu, "did=?", did) + eu.APIKey = apiKey + ec.es.Update(ExplorerUserDetailsTable, &eu, "did=?", did) } return nil } + +func (ec *ExplorerClient) getAPIKey(path string, input interface{}) string { + // var apiKey string + eu := ExplorerUser{} + if path != ExplorerCreateDIDAPI { + var did string + switch v := input.(type) { + case *ExplorerRBTTrans: + did = v.SenderDID + case *ExplorerCreateToken: + did = v.UserDID + default: + return "unsupported input type" + } + err := ec.es.Read(ExplorerUserDetailsTable, &eu, "did=?", did) //Include explorer URL? TODO + if err != nil { + return "" + } + if eu.APIKey == "" { + return "" + } + return eu.APIKey + } + return "" +} diff --git a/core/part_token.go b/core/part_token.go index 4a0e4f00..c5966540 100644 --- a/core/part_token.go +++ b/core/part_token.go @@ -193,6 +193,7 @@ func (c *Core) createPartToken(dc did.DIDCrypto, did string, tkn string, parts [ c.log.Error("failed to get parent detials", "err", err) return nil, err } + var ChildTokenList []ChildToken for i := range parts { rt := &rac.RacType{ Type: c.RACPartTokenType(), @@ -269,16 +270,15 @@ func (c *Core) createPartToken(dc did.DIDCrypto, did string, tkn string, parts [ c.log.Error("Failed to create part token, failed to add token chan block", "err", err) return nil, err } - newPartToken := &ExplorerCreateToken{ - TokenID: pt, - TokenValue: parts[i], - BlockNumber: 0, - UserDID: did, - TokenType: c.TokenType(PartString), - QuorumList: []string{}, - } - c.ec.ExplorerTokenCreate(newPartToken) + ChildTokenList = append(ChildTokenList, ChildToken{TokenID: pt, TokenValue: parts[i]}) + } + newPartToken := &ExplorerCreateTokenParts{ + ChildTokenList: ChildTokenList, + UserDID: did, + TokenType: "parts", + ParentToken: tkn, } + c.ec.ExplorerTokenCreateParts(newPartToken) bti := &block.TransInfo{ Tokens: []block.TransTokens{ { diff --git a/core/quorum_initiator.go b/core/quorum_initiator.go index 698d0539..6f02c986 100644 --- a/core/quorum_initiator.go +++ b/core/quorum_initiator.go @@ -85,7 +85,7 @@ type PledgeDetails struct { NumPledgedTokens int PledgedTokens map[string][]string PledgedTokenChainBlock map[string]interface{} - TokenList []string + TokenList []Token } type PledgeRequest struct { @@ -340,7 +340,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc NumPledgedTokens: 0, PledgedTokens: make(map[string][]string), PledgedTokenChainBlock: make(map[string]interface{}), - TokenList: make([]string, 0), + TokenList: make([]Token, 0), } //getting last character from TID tid := util.HexToStr(util.CalculateHash(sc.GetBlock(), "SHA3-256")) @@ -1734,7 +1734,8 @@ func (c *Core) initPledgeQuorumToken(cr *ConensusRequest, p *ipfsport.Peer, qt i pd.RemPledgeTokens = floatPrecision(pd.RemPledgeTokens, MaxDecimalPlaces) pd.PledgedTokenChainBlock[t] = prs.TokenChainBlock[i] pd.PledgedTokens[did] = append(pd.PledgedTokens[did], t) - pd.TokenList = append(pd.TokenList, t) + pd.TokenList = append(pd.TokenList, Token{TokenID: prs.Tokens[i], TokenValue: prs.TokenValue[i]}) + } } c.qlock.Lock() diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index 5fab4d4c..9c20c097 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -181,13 +181,13 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma SCTokenHash: deployReq.SmartContractToken, TransactionID: txnDetails.TransactionID, Network: conensusRequest.Type, - BlockHash: txnDetails.BlockID, + BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt, DeployerDID: did, Creator: did, PledgeAmount: deployReq.RBTAmount, QuorumList: conensusRequest.QuorumList, - PledgeInfo: pds, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, Comments: deployReq.Comment, } c.ec.ExplorerSCTransaction(eTrans) @@ -300,7 +300,7 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute resp.Message = "failed to create consensus contract block" return resp } - conensusRequest := &ConensusRequest{ + consensusRequest := &ConensusRequest{ ReqID: uuid.New().String(), Type: executeReq.QuorumType, ExecuterPeerID: c.peerID, @@ -310,7 +310,7 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute TransactionEpoch: txEpoch, } - txnDetails, _, pds, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) + txnDetails, _, pds, err := c.initiateConsensus(consensusRequest, consensusContract, didCryptoLib) if err != nil { c.log.Error("Consensus failed", "err", err) @@ -339,13 +339,13 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute eTrans := &ExplorerSCTrans{ SCTokenHash: executeReq.SmartContractToken, TransactionID: txnDetails.TransactionID, - Network: conensusRequest.Type, + Network: consensusRequest.Type, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt, ExecutorDID: did, Creator: smartContractInfo.OwnerDID, - QuorumList: conensusRequest.QuorumList, - PledgeInfo: pds, + QuorumList: consensusRequest.QuorumList, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, Comments: executeReq.Comment, } c.ec.ExplorerSCTransaction(eTrans) diff --git a/core/transfer.go b/core/transfer.go index 65d56515..2da45883 100644 --- a/core/transfer.go +++ b/core/transfer.go @@ -238,6 +238,7 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) } tis := make([]contract.TokenInfo, 0) + tokenListForExplorer := []Token{} for i := range tokensForTxn { tts := "rbt" if tokensForTxn[i].TokenValue != 1 { @@ -265,6 +266,8 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) BlockID: bid, } tis = append(tis, ti) + tokenListForExplorer = append(tokenListForExplorer, Token{TokenID: ti.Token, TokenValue: ti.TokenValue}) + } contractType := getContractType(reqID, req, tis, isSelfRBTTransfer) @@ -308,25 +311,20 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) resp.Message = errMsg return resp } - - /* blockHash, err := extractHash(td.BlockID) - if err != nil { - c.log.Error("Consensus failed", "err", err) - resp.Message = "Consensus failed" + err.Error() - return resp - } */ etrans := &ExplorerRBTTrans{ TokenHashes: wta, TransactionID: td.TransactionID, - // BlockNumber: td.BlockID, - Network: req.Type, - SenderDID: senderDID, - ReceiverDID: receiverdid, - Amount: req.TokenCount, - QuorumList: cr.QuorumList, - PledgeInfo: pds, - Comments: req.Comment, - } + BlockHash: strings.Split(td.BlockID, "-")[1], + Network: req.Type, + SenderDID: senderDID, + ReceiverDID: receiverdid, + Amount: req.TokenCount, + QuorumList: cr.QuorumList, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, + TokenList: tokenListForExplorer, + Comments: req.Comment, + } + fmt.Printf("%+v", etrans) c.ec.ExplorerRBTTransaction(etrans) c.log.Info("Transfer finished successfully", "duration", dif, " trnxid", td.TransactionID) @@ -549,14 +547,14 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ etrans := &ExplorerRBTTrans{ TokenHashes: wta, TransactionID: td.TransactionID, - // BlockNumber: td.BlockID, - Network: req.Type, - SenderDID: did, - ReceiverDID: pinningNodeDID, - Amount: req.TokenCount, - QuorumList: cr.QuorumList, - PledgeInfo: pds, - Comments: req.Comment, + BlockHash: strings.Split(td.BlockID, "-")[1], + Network: req.Type, + SenderDID: did, + ReceiverDID: pinningNodeDID, + Amount: req.TokenCount, + QuorumList: cr.QuorumList, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, + Comments: req.Comment, } c.ec.ExplorerRBTTransaction(etrans) c.log.Info("Pinning finished successfully", "duration", dif, " trnxid", td.TransactionID) @@ -565,11 +563,3 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ resp.Message = msg return resp } - -func extractHash(input string) (string, error) { - values := strings.Split(input, "-") - if len(values) != 2 { - return "", fmt.Errorf("invalid format: %s", input) - } - return values[1], nil -} diff --git a/server/config.go b/server/config.go index dfbc9156..093d5693 100644 --- a/server/config.go +++ b/server/config.go @@ -195,3 +195,14 @@ func (s *Server) APIRemoveExplorer(req *ensweb.Request) *ensweb.Result { } return s.BasicResponse(req, true, "explorer removed successfully", nil) } + +func (s *Server) APIAddUserAPIKey(req *ensweb.Request) *ensweb.Result { + did := s.GetQuerry(req, "did") + apiKey := s.GetQuerry(req, "apiKey") + + err := s.c.AddDIDKey(did, apiKey) + if err != nil { + return s.BasicResponse(req, false, "failed to add to table, "+err.Error(), nil) + } + return s.BasicResponse(req, true, "Api Key added successfully", nil) +} diff --git a/server/server.go b/server/server.go index 09dd550a..911ca0e3 100644 --- a/server/server.go +++ b/server/server.go @@ -170,6 +170,7 @@ func (s *Server) RegisterRoutes() { s.AddRoute(setup.APIRecoverRBT, "POST", s.AuthHandle(s.APIRecoverRBT, true, s.AuthError, false)) s.AddRoute(setup.APIValidateTokenChain, "GET", s.AuthHandle(s.APIValidateTokenChain, false, s.AuthError, false)) s.AddRoute(setup.APIValidateToken, "GET", s.AuthHandle(s.APIValidateToken, false, s.AuthError, false)) + s.AddRoute(setup.APIAddUserAPIKey, "POST", s.AuthHandle(s.APIAddUserAPIKey, false, s.AuthError, true)) } func (s *Server) ExitFunc() error { diff --git a/setup/setup.go b/setup/setup.go index eb15787c..8a390765 100644 --- a/setup/setup.go +++ b/setup/setup.go @@ -77,6 +77,7 @@ const ( APIRecoverRBT string = "/api/recover-token" APIValidateTokenChain string = "/api/validate-token-chain" APIValidateToken string = "/api/validate-token" + APIAddUserAPIKey string = "/api/add-user-api-key" ) // jwt.RegisteredClaims diff --git a/wrapper/ensweb/client.go b/wrapper/ensweb/client.go index 31571457..d1dde3d5 100644 --- a/wrapper/ensweb/client.go +++ b/wrapper/ensweb/client.go @@ -128,7 +128,7 @@ func (c *Client) JSONRequest(method string, requestPath string, model interface{ return req, err } -func (c *Client) JSONRequestForExplorer(method string, requestPath string, model interface{}, explorerURL string) (*http.Request, error) { +func (c *Client) JSONRequestForExplorer(method string, requestPath string, model interface{}, explorerURL string, apiKeyForHeader string) (*http.Request, error) { var body *bytes.Buffer if model != nil { j, err := json.Marshal(model) @@ -146,7 +146,9 @@ func (c *Client) JSONRequestForExplorer(method string, requestPath string, model if err != nil { return nil, err } - + if apiKeyForHeader != "" { + req.Header.Set("X-API-Key", apiKeyForHeader) + } req.Header.Set("Content-Type", "application/json") return req, err From 333586b804efe64d5e60ba568b413bedd663e17a Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Tue, 22 Oct 2024 18:13:45 +0530 Subject: [PATCH 03/12] APIKey expire,create and other APIs --- command/command.go | 6 ++ core/did.go | 14 +--- core/explorer.go | 183 ++++++++++++++++++++++++++++++++++++--------- core/part_token.go | 3 +- core/transfer.go | 1 - server/basic.go | 1 + 6 files changed, 158 insertions(+), 50 deletions(-) diff --git a/command/command.go b/command/command.go index bdc367f4..a51d83e5 100644 --- a/command/command.go +++ b/command/command.go @@ -370,6 +370,11 @@ func (cmd *Command) runApp() { cmd.log.Info("Core version : " + version) cmd.log.Info("Starting server...") go s.Start() + cmd.log.Info("Syncing Details...") + dids := c.ExplorerUserCreate() //Checking if all the DIDs are in the ExplorerUserDetailtable or not. + c.UpdateUserInfo(dids) //Updating the balance + c.GenerateUserAPIKey(dids) //Regenerating the API Key for DID + cmd.log.Info("Syncing Complete...") ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGTERM) @@ -380,6 +385,7 @@ func (cmd *Command) runApp() { } s.Shutdown() cmd.log.Info("Shutting down...") + c.ExpireUserAPIKey() } func (cmd *Command) validateOptions() bool { diff --git a/core/did.go b/core/did.go index eed7a95f..e84285cf 100644 --- a/core/did.go +++ b/core/did.go @@ -128,16 +128,6 @@ func (c *Core) CreateDID(didCreate *did.DIDCreate) (string, error) { c.log.Error("Failed to create did in the wallet", "err", err) return "", err } - // exp := model.ExploreModel{ - // Cmd: ExpDIDPeerMapCmd, - // DIDList: []string{did}, - // PeerID: c.peerID, - // Message: "DID Created Successfully", - // } - // err = c.PublishExplorer(&exp) - // if err != nil { - // return "", err - // } newDID := &ExplorerDID{ PeerID: c.peerID, DID: did, @@ -145,7 +135,7 @@ func (c *Core) CreateDID(didCreate *did.DIDCreate) (string, error) { DIDType: didCreate.Type, } if !c.testNet { - c.ec.ExplorerCreateDID(newDID) + c.ec.ExplorerUserCreate(newDID) } return did, nil } @@ -189,7 +179,7 @@ func (c *Core) AddDID(dc *did.DIDCreate) *model.BasicResponse { DID: ds, DIDType: dc.Type, } - c.ec.ExplorerCreateDID(newDID) + c.ec.ExplorerUserCreate(newDID) br.Status = true br.Message = "DID added successfully" br.Result = ds diff --git a/core/explorer.go b/core/explorer.go index a71844b8..3ef65bd6 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/rubixchain/rubixgoplatform/core/storage" + "github.com/rubixchain/rubixgoplatform/core/wallet" "github.com/rubixchain/rubixgoplatform/wrapper/config" "github.com/rubixchain/rubixgoplatform/wrapper/ensweb" "github.com/rubixchain/rubixgoplatform/wrapper/helper/jsonutil" @@ -14,20 +15,24 @@ import ( ) const ( - ExplorerBasePath string = "/api/v2/services/app/Rubix/" - ExplorerTokenCreateAPI string = "/api/token/create" - ExplorerTokenCreatePartsAPI string = "/api/token/create/parts" - ExplorerTokenCreateSCAPI string = "/api/token/create/sc" - ExplorerTokenCreateFTAPI string = "/api/token/create/ft" - ExplorerTokenCreateNFTAPI string = "/api/token/create/nft" - ExplorerCreateDIDAPI string = "/api/user/create" - ExplorerRBTTransactionAPI string = "/api/transactions/rbt" - ExplorerSCTransactionAPI string = "/api/transactions/sc" - ExplorerTransactionAPI string = "CreateOrUpdateRubixTransaction" - ExplorerCreateDataTransAPI string = "create-datatokens" - ExplorerMapDIDAPI string = "map-did" - ExplorerURLTable string = "ExplorerURLTable" - ExplorerUserDetailsTable string = "ExplorerUserDetails" + ExplorerBasePath string = "/api/v2/services/app/Rubix/" + ExplorerTokenCreateAPI string = "/api/token/create" + ExplorerTokenCreatePartsAPI string = "/api/token/part/create" + ExplorerTokenCreateSCAPI string = "/api/token/sc/create" + ExplorerTokenCreateFTAPI string = "/api/token/ft/create" + ExplorerTokenCreateNFTAPI string = "/api/token/nft/create" + ExplorerCreateUserAPI string = "/api/user/create" + ExplorerUpdateUserInfoAPI string = "/api/user/update-user-info" + ExplorerGetUserKeyAPI string = "/api/user/get-api-key" + ExplorerGenerateUserKeyAPI string = "/api/user/generate-api-key" + ExplorerExpireUserKeyAPI string = "/api/user/set-expire-api-key" + ExplorerRBTTransactionAPI string = "/api/transactions/rbt" + ExplorerSCTransactionAPI string = "/api/transactions/sc" + ExplorerUpdatePledgeStatusAPI string = "/api/token/update-pledge-status" + ExplorerCreateDataTransAPI string = "create-datatokens" + ExplorerMapDIDAPI string = "map-did" + ExplorerURLTable string = "ExplorerURLTable" + ExplorerUserDetailsTable string = "ExplorerUserDetails" ) type ExplorerClient struct { @@ -37,11 +42,10 @@ type ExplorerClient struct { } type ExplorerDID struct { - PeerID string `json:"peer_id"` - DID string `json:"user_did"` - IPAddress string `json:"ip_addess"` - Balance int `json:"balance"` - DIDType int `json:"did_type"` + PeerID string `json:"peer_id"` + DID string `json:"user_did"` + Balance float64 `json:"balance"` + DIDType int `json:"did_type"` } type ExplorerMapDID struct { @@ -51,17 +55,21 @@ type ExplorerMapDID struct { } type Token struct { - TokenID string `json:"token_id"` + TokenID string `json:"token_hash"` TokenValue float64 `json:"token_value"` } +type UnpledgeToken struct { + TokenIDs []string `json:"token_hashes"` +} + type ChildToken struct { - TokenID string `json:"child_token_hash"` - TokenValue float64 `json:"child_token_value"` + ChildTokenID string `json:"token_hash"` + TokenValue float64 `json:"token_value"` } type ExplorerCreateToken struct { - TokenID string `json:"token_id"` + TokenID string `json:"token_hash"` TokenValue float64 `json:"token_value"` Network int `json:"network"` BlockNumber int `json:"block_num"` @@ -73,9 +81,8 @@ type ExplorerCreateToken struct { type ExplorerCreateTokenParts struct { UserDID string `json:"user_did"` - TokenType string `json:"token_type"` ParentToken string `json:"parent_token_hash"` - ChildTokenList []ChildToken `json:"child_token_list"` + ChildTokenList []ChildToken `json:"child_tokens"` } type ExplorerDataTrans struct { @@ -120,6 +127,7 @@ type ExplorerSCTrans struct { PledgeAmount float64 `json:"pledge_amount"` QuorumList []string `json:"quorum_list"` PledgeInfo PledgeInfo `json:"pledge_info"` + TokenList []Token `json:"token_list"` Comments string `json:"comments"` } @@ -140,7 +148,7 @@ type ExplorerURL struct { } type ExplorerUser struct { - DID string `gorm:"column:did;primaryKey" json:"did"` + DID string `gorm:"column:did;primaryKey" json:"user_did"` APIKey string `gorm:"column:apiKey" json:"apiKey"` } @@ -224,26 +232,103 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp ec.log.Error("Invalid response from the node", "err", err) continue } - ec.log.Info("Details successfully stored in Explorer") } return nil } -func (ec *ExplorerClient) ExplorerCreateDID(ed *ExplorerDID) error { +func (c *Core) ExplorerUserCreate() []string { + didList := []wallet.DIDType{} + dids := []string{} + + err := c.s.Read(wallet.DIDStorage, &didList, "did!=?", "") + if err != nil { + c.log.Error("Error reading the DID Storage or DID Storage empty") + return nil + } + for _, d := range didList { + eu := ExplorerUser{} + err := c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", d.DID) + if err != nil { + ed := ExplorerDID{} + ed.DID = d.DID + ed.Balance = 0 + ed.PeerID = c.peerID + ed.DIDType = d.Type + err = c.ec.ExplorerUserCreate(&ed) + if err != nil { + c.log.Error("Error creating user for did %v", d.DID) + } + } + dids = append(dids, d.DID) + } + return dids +} + +func (ec *ExplorerClient) ExplorerUserCreate(ed *ExplorerDID) error { var er ExplorerUserCreateResponse - ed.IPAddress = "0.0.0.0" - err := ec.SendExploerJSONRequest("POST", ExplorerCreateDIDAPI, &ed, &er) + err := ec.SendExploerJSONRequest("POST", ExplorerCreateUserAPI, &ed, &er) if err != nil { return err } if er.Message != "User created successfully!" { - ec.log.Error("Failed to update explorer", "msg", er.Message) + ec.log.Error("Failed to update explorer for %v with error message %v", ed.DID, er.Message) return fmt.Errorf("failed to update explorer") } ec.AddDIDKey(ed.DID, er.APIKey) + ec.log.Info(er.Message + " for did " + ed.DID) return nil } +func (c *Core) UpdateUserInfo(dids []string) { + for _, did := range dids { + accInfo, err := c.GetAccountInfo(did) + if err != nil { + c.log.Error("Failed to get account info for DID %v", did) + continue + } + var er ExplorerResponse + ed := ExplorerDID{} + ed.PeerID = c.peerID + ed.Balance = accInfo.RBTAmount + ed.DIDType = 4 + err = c.ec.SendExploerJSONRequest("PUT", ExplorerUpdateUserInfoAPI+"/"+did, &ed, &er) + if err != nil { + c.log.Error(err.Error()) + } + if er.Message != "User balance updated successfully!" { + c.log.Error("Failed to update explorer", "msg", er.Message) + } + c.log.Info(er.Message + " for did " + ed.DID) + } +} + +func (c *Core) GenerateUserAPIKey(dids []string) { + for _, did := range dids { + var er ExplorerUserCreateResponse + eu := ExplorerUser{} + //Read for api key in table, if empty, then regenerate, because before this, after creating the DID, we are generating the API Key + err := c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", did) + if err != nil { + c.log.Error("Failed to read table") + } + if eu.APIKey != "" { + continue + } + err = c.ec.SendExploerJSONRequest("POST", ExplorerGenerateUserKeyAPI, &eu, &er) + if err != nil { + c.log.Error(err.Error()) + } + if er.Message != "API key regenerated successfully!" { + c.log.Error("Failed to generate API Key for %v. The error msg is %v", did, er.Message) + } + c.ec.AddDIDKey(did, er.APIKey) + c.log.Info(er.Message + " for did " + did) + + fmt.Println(er) + + } +} + func (ec *ExplorerClient) ExplorerMapDID(oldDid string, newDID string, peerID string) error { ed := ExplorerMapDID{ OldDID: oldDid, @@ -277,15 +362,15 @@ func (ec *ExplorerClient) ExplorerTokenCreate(et *ExplorerCreateToken) error { func (ec *ExplorerClient) ExplorerTokenCreateParts(et *ExplorerCreateTokenParts) error { var er ExplorerResponse - fmt.Println("Calling API") err := ec.SendExploerJSONRequest("POST", ExplorerTokenCreatePartsAPI, et, &er) if err != nil { return err } - if !er.Status { + if er.Message != "Parts Tokens Create successfully!" { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } + ec.log.Info("Parts created successfully for Parent TokenID %v", et.ParentToken) return nil } @@ -312,6 +397,7 @@ func (ec *ExplorerClient) ExplorerRBTTransaction(et *ExplorerRBTTrans) error { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } + ec.log.Info("Transaction details for TransactionID %v is stored successfully", et.TransactionID) return nil } @@ -325,6 +411,7 @@ func (ec *ExplorerClient) ExplorerSCTransaction(et *ExplorerSCTrans) error { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } + ec.log.Info("Smart contract transaction details for TransactionID %v is stored successfully", et.TransactionID) return nil } @@ -418,9 +505,8 @@ func (ec *ExplorerClient) AddDIDKey(did string, apiKey string) error { } func (ec *ExplorerClient) getAPIKey(path string, input interface{}) string { - // var apiKey string eu := ExplorerUser{} - if path != ExplorerCreateDIDAPI { + if path != ExplorerCreateUserAPI { var did string switch v := input.(type) { case *ExplorerRBTTrans: @@ -441,3 +527,30 @@ func (ec *ExplorerClient) getAPIKey(path string, input interface{}) string { } return "" } + +func (c *Core) ExpireUserAPIKey() { + fmt.Println("Cleaning started...") + eus := []ExplorerUser{} + //Read for api key in table, if not empty, then expire the apiKey and set the field to empty + err := c.s.Read(ExplorerUserDetailsTable, &eus, "apiKey!=?", "") + if err != nil { + c.log.Error("Failed to read table for Expiring the user Key") + } + for _, eu := range eus { + var er ExplorerResponse + err = c.ec.SendExploerJSONRequest("POST", ExplorerExpireUserKeyAPI, &eu, &er) + if err != nil { + c.log.Error(err.Error()) + } + if er.Message != "API key expired successfully!" { + c.log.Error("Failed to expire API Key for %v. The error msg is %v", eu.DID, er.Message) + } + eu.APIKey = "" + err = c.s.Update(ExplorerUserDetailsTable, &eu, "did=?", eu.DID) + if err != nil { + c.log.Error(err.Error()) + } + c.log.Info("%v for DID %v", er.Message, eu.DID) + fmt.Println("Cleaning completed...") + } +} diff --git a/core/part_token.go b/core/part_token.go index c5966540..d12c01ee 100644 --- a/core/part_token.go +++ b/core/part_token.go @@ -270,12 +270,11 @@ func (c *Core) createPartToken(dc did.DIDCrypto, did string, tkn string, parts [ c.log.Error("Failed to create part token, failed to add token chan block", "err", err) return nil, err } - ChildTokenList = append(ChildTokenList, ChildToken{TokenID: pt, TokenValue: parts[i]}) + ChildTokenList = append(ChildTokenList, ChildToken{ChildTokenID: pt, TokenValue: parts[i]}) } newPartToken := &ExplorerCreateTokenParts{ ChildTokenList: ChildTokenList, UserDID: did, - TokenType: "parts", ParentToken: tkn, } c.ec.ExplorerTokenCreateParts(newPartToken) diff --git a/core/transfer.go b/core/transfer.go index 2da45883..16086b1b 100644 --- a/core/transfer.go +++ b/core/transfer.go @@ -324,7 +324,6 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) TokenList: tokenListForExplorer, Comments: req.Comment, } - fmt.Printf("%+v", etrans) c.ec.ExplorerRBTTransaction(etrans) c.log.Info("Transfer finished successfully", "duration", dif, " trnxid", td.TransactionID) diff --git a/server/basic.go b/server/basic.go index 4b760a37..bb19e381 100644 --- a/server/basic.go +++ b/server/basic.go @@ -36,6 +36,7 @@ func (s *Server) APIStart(req *ensweb.Request) *ensweb.Result { // APIStart will setup the core func (s *Server) APIShutdown(req *ensweb.Request) *ensweb.Result { go s.shutDown() + s.c.ExpireUserAPIKey() return s.BasicResponse(req, true, "Shutting down...", nil) } From a89533fbe3469ee974f1beaa9dc369c0ff5e185d Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Wed, 23 Oct 2024 18:01:08 +0530 Subject: [PATCH 04/12] Update pledge status --- core/explorer.go | 39 ++++++++++++++++++------- core/quorum_initiator.go | 2 +- core/smart_contract_token_operations.go | 16 +++++----- core/transfer.go | 2 +- core/unpledge.go | 15 ++++------ 5 files changed, 45 insertions(+), 29 deletions(-) diff --git a/core/explorer.go b/core/explorer.go index 3ef65bd6..5afc2f74 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -55,12 +55,12 @@ type ExplorerMapDID struct { } type Token struct { - TokenID string `json:"token_hash"` + TokenHash string `json:"token_hash"` TokenValue float64 `json:"token_value"` } type UnpledgeToken struct { - TokenIDs []string `json:"token_hashes"` + TokenHashes []string `json:"token_hashes"` } type ChildToken struct { @@ -68,6 +68,12 @@ type ChildToken struct { TokenValue float64 `json:"token_value"` } +type SCToken struct { + SCTokenHash string `json:"token_hash"` + SCBlockHash string `json:"block_hash"` + SCBlockNumber int `json:"block_number"` +} + type ExplorerCreateToken struct { TokenID string `json:"token_hash"` TokenValue float64 `json:"token_value"` @@ -116,11 +122,9 @@ type ExplorerRBTTrans struct { Comments string `json:"comments"` } type ExplorerSCTrans struct { - SCTokenHash string `json:"sc_token_hash"` + SCBlockHash []SCToken `json:"sc_block_hash"` TransactionID string `json:"transaction_id"` Network int `json:"network"` - BlockNumber int `json:"block_number"` - BlockHash string `json:"block_hash"` ExecutorDID string `json:"executor"` DeployerDID string `json:"deployer"` Creator string `json:"creator"` @@ -247,7 +251,7 @@ func (c *Core) ExplorerUserCreate() []string { } for _, d := range didList { eu := ExplorerUser{} - err := c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", d.DID) + err = c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", d.DID) if err != nil { ed := ExplorerDID{} ed.DID = d.DID @@ -271,8 +275,8 @@ func (ec *ExplorerClient) ExplorerUserCreate(ed *ExplorerDID) error { return err } if er.Message != "User created successfully!" { - ec.log.Error("Failed to update explorer for %v with error message %v", ed.DID, er.Message) - return fmt.Errorf("failed to update explorer") + ec.log.Error("Failed to create user for %v with error message %v", ed.DID, er.Message) + return fmt.Errorf("failed to create user") } ec.AddDIDKey(ed.DID, er.APIKey) ec.log.Info(er.Message + " for did " + ed.DID) @@ -293,10 +297,10 @@ func (c *Core) UpdateUserInfo(dids []string) { ed.DIDType = 4 err = c.ec.SendExploerJSONRequest("PUT", ExplorerUpdateUserInfoAPI+"/"+did, &ed, &er) if err != nil { - c.log.Error(err.Error()) + c.log.Error("Failed to update user info, " + err.Error()) } if er.Message != "User balance updated successfully!" { - c.log.Error("Failed to update explorer", "msg", er.Message) + c.log.Error("Failed to update user info, ", "msg", er.Message) } c.log.Info(er.Message + " for did " + ed.DID) } @@ -550,7 +554,20 @@ func (c *Core) ExpireUserAPIKey() { if err != nil { c.log.Error(err.Error()) } - c.log.Info("%v for DID %v", er.Message, eu.DID) + c.log.Info(fmt.Sprintf("%v for DID %v", er.Message, eu.DID)) fmt.Println("Cleaning completed...") } } + +func (c *Core) UpdatePledgeStatus(tokenHashes []string, did string) { + var er ExplorerResponse + ut := UnpledgeToken{TokenHashes: tokenHashes} + err := c.ec.SendExploerJSONRequest("PUT", ExplorerUpdatePledgeStatusAPI+"/"+did, &ut, &er) + if err != nil { + c.log.Error(err.Error()) + } + if er.Message != "Updated Successfully!" { + c.log.Error("Failed to update explorer", "msg", er.Message) + } + c.log.Info(fmt.Sprintf("Pledge status updated successfully for did %v and token hashes %v", did, tokenHashes)) +} diff --git a/core/quorum_initiator.go b/core/quorum_initiator.go index 6f02c986..6d695a08 100644 --- a/core/quorum_initiator.go +++ b/core/quorum_initiator.go @@ -1734,7 +1734,7 @@ func (c *Core) initPledgeQuorumToken(cr *ConensusRequest, p *ipfsport.Peer, qt i pd.RemPledgeTokens = floatPrecision(pd.RemPledgeTokens, MaxDecimalPlaces) pd.PledgedTokenChainBlock[t] = prs.TokenChainBlock[i] pd.PledgedTokens[did] = append(pd.PledgedTokens[did], t) - pd.TokenList = append(pd.TokenList, Token{TokenID: prs.Tokens[i], TokenValue: prs.TokenValue[i]}) + pd.TokenList = append(pd.TokenList, Token{TokenHash: prs.Tokens[i], TokenValue: prs.TokenValue[i]}) } } diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index 9c20c097..d0d5e3fb 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -61,7 +61,6 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma } rbtTokensToCommit := make([]string, 0) - defer c.w.ReleaseTokens(rbtTokensToCommitDetails) for i := range rbtTokensToCommitDetails { @@ -71,6 +70,7 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma rbtTokenInfoArray := make([]contract.TokenInfo, 0) smartContractInfoArray := make([]contract.TokenInfo, 0) + tokenListForExplorer := []Token{} for i := range rbtTokensToCommitDetails { tokenTypeString := "rbt" if rbtTokensToCommitDetails[i].TokenValue != 1 { @@ -97,6 +97,7 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma BlockID: blockId, } rbtTokenInfoArray = append(rbtTokenInfoArray, tokenInfo) + tokenListForExplorer = append(tokenListForExplorer, Token{TokenHash: tokenInfo.Token, TokenValue: tokenInfo.TokenValue}) } smartContractInfo := contract.TokenInfo{ @@ -178,16 +179,16 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCTokenHash: deployReq.SmartContractToken, + SCBlockHash: []SCToken{{SCTokenHash: deployReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, TransactionID: txnDetails.TransactionID, Network: conensusRequest.Type, - BlockHash: strings.Split(txnDetails.BlockID, "-")[1], - BlockNumber: blockNoInt, + ExecutorDID: "", DeployerDID: did, Creator: did, PledgeAmount: deployReq.RBTAmount, QuorumList: conensusRequest.QuorumList, PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, + TokenList: tokenListForExplorer, Comments: deployReq.Comment, } c.ec.ExplorerSCTransaction(eTrans) @@ -337,15 +338,16 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCTokenHash: executeReq.SmartContractToken, + SCBlockHash: []SCToken{{SCTokenHash: executeReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, TransactionID: txnDetails.TransactionID, Network: consensusRequest.Type, - BlockHash: strings.Split(txnDetails.BlockID, "-")[1], - BlockNumber: blockNoInt, ExecutorDID: did, + DeployerDID: smartContractInfo.OwnerDID, Creator: smartContractInfo.OwnerDID, QuorumList: consensusRequest.QuorumList, + PledgeAmount: 0, PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, + TokenList: []Token{}, Comments: executeReq.Comment, } c.ec.ExplorerSCTransaction(eTrans) diff --git a/core/transfer.go b/core/transfer.go index 16086b1b..715c8d83 100644 --- a/core/transfer.go +++ b/core/transfer.go @@ -266,7 +266,7 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) BlockID: bid, } tis = append(tis, ti) - tokenListForExplorer = append(tokenListForExplorer, Token{TokenID: ti.Token, TokenValue: ti.TokenValue}) + tokenListForExplorer = append(tokenListForExplorer, Token{TokenHash: ti.Token, TokenValue: ti.TokenValue}) } diff --git a/core/unpledge.go b/core/unpledge.go index 3001797e..cca8d508 100644 --- a/core/unpledge.go +++ b/core/unpledge.go @@ -33,7 +33,7 @@ func (c *Core) ForceUnpledgePOWBasedPledgedTokens() error { if err != nil { return fmt.Errorf("failed to unpledge POW based pledge token %v, err: %v", pledgeToken, err) } - + _, _, err = unpledgeToken(c, pledgeToken, pledgeTokenType, pledgeTokenOwner) if err != nil { c.log.Error("failed to unpledge POW based pledge token %v, err: %v", pledgeToken, err) @@ -99,7 +99,6 @@ func (c *Core) InititateUnpledgeProcess() (string, error) { return "", err } - creditStorageErr := c.w.StoreCredit(info.TransactionID, info.QuorumDID, pledgeInformation) if creditStorageErr != nil { errMsg := fmt.Errorf("failed while storing credits, err: %v", creditStorageErr.Error()) @@ -111,8 +110,8 @@ func (c *Core) InititateUnpledgeProcess() (string, error) { if removeUnpledgeSequenceInfoErr != nil { errMsg := fmt.Errorf("failed to remove unpledgeSequenceInfo record for transaction: %v, error: %v", info.TransactionID, removeUnpledgeSequenceInfoErr) c.log.Error(errMsg.Error()) - - // Remove the corresponding stored credit + + // Remove the corresponding stored credit creditRemovalErr := c.w.RemoveCredit(info.TransactionID) if creditRemovalErr != nil { errMsg := fmt.Errorf("failed to remove credit for transaction ID: %v", creditRemovalErr) @@ -122,7 +121,7 @@ func (c *Core) InititateUnpledgeProcess() (string, error) { return "", errMsg } - + c.UpdatePledgeStatus(strings.Split(info.PledgeTokens, ","), info.QuorumDID) unpledgeAmountForTransaction, err := c.getTotalAmountFromTokenHashes(strings.Split(info.PledgeTokens, ",")) if err != nil { return "", fmt.Errorf("failed while getting total pledge amount for transaction id: %v, err: %v", info.TransactionID, err) @@ -222,7 +221,7 @@ func unpledgeToken(c *Core, pledgeToken string, pledgeTokenType int, quorumDID s func getTokenType(w *wallet.Wallet, tokenHash string, isTestnet bool) (int, error) { var tokenType int = -1 - + walletToken, err := w.ReadToken(tokenHash) if err != nil { return tokenType, err @@ -245,7 +244,6 @@ func getTokenType(w *wallet.Wallet, tokenHash string, isTestnet bool) (int, erro return tokenType, nil } - func getTokenOwner(w *wallet.Wallet, tokenHash string) (string, error) { walletToken, err := w.ReadToken(tokenHash) if err != nil { @@ -255,10 +253,9 @@ func getTokenOwner(w *wallet.Wallet, tokenHash string) (string, error) { return walletToken.DID, nil } - func unpledgeAllTokens(c *Core, transactionID string, pledgeTokens string, quorumDID string) ([]*wallet.PledgeInformation, error) { c.log.Debug(fmt.Sprintf("Executing Callback for tx for unpledging: %v", transactionID)) - + var pledgeInfoList []*wallet.PledgeInformation = make([]*wallet.PledgeInformation, 0) pledgeTokensList := strings.Split(pledgeTokens, ",") From 4f6a87f18fa0dfc1b6659a3dd3acb911d466cf95 Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Fri, 25 Oct 2024 17:55:18 +0530 Subject: [PATCH 05/12] Updated fiend names --- core/explorer.go | 80 ++++++++++++++----------- core/smart_contract_token_operations.go | 44 +++++++------- core/transfer.go | 24 ++++---- 3 files changed, 78 insertions(+), 70 deletions(-) diff --git a/core/explorer.go b/core/explorer.go index 5afc2f74..dbff564b 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -54,6 +54,20 @@ type ExplorerMapDID struct { PeerID string `json:"peer_id"` } +// type TokenDetails struct { +// TokenHash string `json:"token_hash"` +// TokenValue float64 `json:"token_value"` +// CurrentOwner string +// PreviousOwner string +// Miner string +// BlockIDs []string +// PledgeDetails PledgeInfo //from latest block if available +// TokenType int +// TokenLevel int +// TokenNumber int +// TokenStatus int +// } + type Token struct { TokenHash string `json:"token_hash"` TokenValue float64 `json:"token_value"` @@ -104,35 +118,35 @@ type ExplorerDataTrans struct { } type PledgeInfo struct { - PledgeDetails map[string][]string `json:"pledge_details"` - TokenList []Token `json:"pledged_token_list"` + PledgeDetails map[string][]string `json:"pledge_details"` + PledgedTokenList []Token `json:"pledged_token_list"` } type ExplorerRBTTrans struct { - TokenHashes []string `json:"token_hash"` - TransactionID string `json:"transaction_id"` - Network int `json:"network"` - BlockHash string `json:"block_hash"` //it will be different for each token - SenderDID string `json:"sender"` - ReceiverDID string `json:"receiver"` - Amount float64 `json:"amount"` - QuorumList []string `json:"quorum_list"` - PledgeInfo PledgeInfo `json:"pledge_info"` - TokenList []Token `json:"token_list"` - Comments string `json:"comments"` + TokenHashes []string `json:"token_hash"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + BlockHash string `json:"block_hash"` //it will be different for each token + SenderDID string `json:"sender"` + ReceiverDID string `json:"receiver"` + Amount float64 `json:"amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` + TransTokenList []Token `json:"token_list"` + Comments string `json:"comments"` } type ExplorerSCTrans struct { - SCBlockHash []SCToken `json:"sc_block_hash"` - TransactionID string `json:"transaction_id"` - Network int `json:"network"` - ExecutorDID string `json:"executor"` - DeployerDID string `json:"deployer"` - Creator string `json:"creator"` - PledgeAmount float64 `json:"pledge_amount"` - QuorumList []string `json:"quorum_list"` - PledgeInfo PledgeInfo `json:"pledge_info"` - TokenList []Token `json:"token_list"` - Comments string `json:"comments"` + SCBlockHash []SCToken `json:"sc_block_hash"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + ExecutorDID string `json:"executor"` + DeployerDID string `json:"deployer"` + Creator string `json:"creator"` + PledgeAmount float64 `json:"pledge_amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` + CommittedTokenList []Token `json:"token_list"` + Comments string `json:"comments"` } type ExplorerResponse struct { @@ -169,11 +183,7 @@ func (c *Core) InitRubixExplorer() error { c.log.Error("Failed to initialise storage ExplorerUserDetails ", "err", err) return err } - - url := "deamon-explorer.azurewebsites.net" - if c.testNet { - url = "rubix-deamon-api.ensurity.com" - } + url := "rexplorer.azurewebsites.net" err = c.s.Read(ExplorerURLTable, &ExplorerURL{}, "url=?", url) if err != nil { @@ -184,7 +194,7 @@ func (c *Core) InitRubixExplorer() error { return err } - cl, err := ensweb.NewClient(&config.Config{ServerAddress: url, ServerPort: "443", Production: "true"}, c.log) + cl, err := ensweb.NewClient(&config.Config{ServerAddress: url, ServerPort: "0", Production: "true"}, c.log) if err != nil { return err } @@ -302,7 +312,7 @@ func (c *Core) UpdateUserInfo(dids []string) { if er.Message != "User balance updated successfully!" { c.log.Error("Failed to update user info, ", "msg", er.Message) } - c.log.Info(er.Message + " for did " + ed.DID) + c.log.Info(fmt.Sprintf("%v for did %v", er.Message, did)) } } @@ -328,8 +338,6 @@ func (c *Core) GenerateUserAPIKey(dids []string) { c.ec.AddDIDKey(did, er.APIKey) c.log.Info(er.Message + " for did " + did) - fmt.Println(er) - } } @@ -374,7 +382,7 @@ func (ec *ExplorerClient) ExplorerTokenCreateParts(et *ExplorerCreateTokenParts) ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } - ec.log.Info("Parts created successfully for Parent TokenID %v", et.ParentToken) + ec.log.Info(fmt.Sprintf("Parts created successfully for Parent TokenID %v", et.ParentToken)) return nil } @@ -397,7 +405,7 @@ func (ec *ExplorerClient) ExplorerRBTTransaction(et *ExplorerRBTTrans) error { if err != nil { return err } - if !er.Status { + if er.Message != "RBT transaction created successfully!" { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } @@ -411,7 +419,7 @@ func (ec *ExplorerClient) ExplorerSCTransaction(et *ExplorerSCTrans) error { if err != nil { return err } - if !er.Status { + if er.Message != "SC transaction created successfully!" { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index d0d5e3fb..ba3b81cb 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -179,17 +179,17 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCBlockHash: []SCToken{{SCTokenHash: deployReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, - TransactionID: txnDetails.TransactionID, - Network: conensusRequest.Type, - ExecutorDID: "", - DeployerDID: did, - Creator: did, - PledgeAmount: deployReq.RBTAmount, - QuorumList: conensusRequest.QuorumList, - PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, - TokenList: tokenListForExplorer, - Comments: deployReq.Comment, + SCBlockHash: []SCToken{{SCTokenHash: deployReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, + TransactionID: txnDetails.TransactionID, + Network: conensusRequest.Type, + ExecutorDID: "", + DeployerDID: did, + Creator: did, + PledgeAmount: deployReq.RBTAmount, + QuorumList: conensusRequest.QuorumList, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, + CommittedTokenList: tokenListForExplorer, + Comments: deployReq.Comment, } c.ec.ExplorerSCTransaction(eTrans) @@ -338,17 +338,17 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCBlockHash: []SCToken{{SCTokenHash: executeReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, - TransactionID: txnDetails.TransactionID, - Network: consensusRequest.Type, - ExecutorDID: did, - DeployerDID: smartContractInfo.OwnerDID, - Creator: smartContractInfo.OwnerDID, - QuorumList: consensusRequest.QuorumList, - PledgeAmount: 0, - PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, - TokenList: []Token{}, - Comments: executeReq.Comment, + SCBlockHash: []SCToken{{SCTokenHash: executeReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, + TransactionID: txnDetails.TransactionID, + Network: consensusRequest.Type, + ExecutorDID: did, + DeployerDID: smartContractInfo.OwnerDID, + Creator: smartContractInfo.OwnerDID, + QuorumList: consensusRequest.QuorumList, + PledgeAmount: 0, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, + CommittedTokenList: []Token{}, + Comments: executeReq.Comment, } c.ec.ExplorerSCTransaction(eTrans) /* newEvent := model.NewContractEvent{ diff --git a/core/transfer.go b/core/transfer.go index 715c8d83..9e84b334 100644 --- a/core/transfer.go +++ b/core/transfer.go @@ -312,17 +312,17 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) return resp } etrans := &ExplorerRBTTrans{ - TokenHashes: wta, - TransactionID: td.TransactionID, - BlockHash: strings.Split(td.BlockID, "-")[1], - Network: req.Type, - SenderDID: senderDID, - ReceiverDID: receiverdid, - Amount: req.TokenCount, - QuorumList: cr.QuorumList, - PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, - TokenList: tokenListForExplorer, - Comments: req.Comment, + TokenHashes: wta, + TransactionID: td.TransactionID, + BlockHash: strings.Split(td.BlockID, "-")[1], + Network: req.Type, + SenderDID: senderDID, + ReceiverDID: receiverdid, + Amount: req.TokenCount, + QuorumList: cr.QuorumList, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, + TransTokenList: tokenListForExplorer, + Comments: req.Comment, } c.ec.ExplorerRBTTransaction(etrans) @@ -552,7 +552,7 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ ReceiverDID: pinningNodeDID, Amount: req.TokenCount, QuorumList: cr.QuorumList, - PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, TokenList: pds.TokenList}, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, Comments: req.Comment, } c.ec.ExplorerRBTTransaction(etrans) From e60b638eed7389d6aa46d63fb5235983af461163 Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Wed, 30 Oct 2024 11:05:40 +0530 Subject: [PATCH 06/12] Added token details struct for explorer --- block/block.go | 15 +++- command/command.go | 1 + core/explorer.go | 166 +++++++++++++++++++++++++++++++++++++++---- core/wallet/token.go | 1 + 4 files changed, 168 insertions(+), 15 deletions(-) diff --git a/block/block.go b/block/block.go index 6d51d58b..76205a31 100644 --- a/block/block.go +++ b/block/block.go @@ -702,7 +702,6 @@ func (b *Block) GetCommitedTokenDetials(t string) ([]string, error) { // if !ok { // return nil // } - // result := make(map[string]interface{}) // for k, v := range tokenPledgeMap { // kStr, kOk := k.(string) @@ -711,7 +710,6 @@ func (b *Block) GetCommitedTokenDetials(t string) ([]string, error) { // } // result[kStr] = v // } - // return result // } @@ -815,3 +813,16 @@ func (b *Block) CalculateBlockHash() (string, error) { return blockHash, nil } + +func (b *Block) GetTokenLevel(token string) (int, int) { + gtm := b.getGenesisTokenMap(token) + tokenLevel := util.GetIntFromMap(gtm, GITokenLevelKey) + tokenNum := util.GetIntFromMap(gtm, GITokenNumberKey) + return tokenLevel, tokenNum +} + +func (b *Block) GetPledgedTokens() { + pledgedInfo := util.GetFromMap(b.bm, TCPledgeDetailsKey) + fmt.Println(pledgedInfo) + // return +} diff --git a/command/command.go b/command/command.go index a51d83e5..0ad0da7d 100644 --- a/command/command.go +++ b/command/command.go @@ -374,6 +374,7 @@ func (cmd *Command) runApp() { dids := c.ExplorerUserCreate() //Checking if all the DIDs are in the ExplorerUserDetailtable or not. c.UpdateUserInfo(dids) //Updating the balance c.GenerateUserAPIKey(dids) //Regenerating the API Key for DID + c.UpdateTokenInfo() cmd.log.Info("Syncing Complete...") ch := make(chan os.Signal, 1) diff --git a/core/explorer.go b/core/explorer.go index dbff564b..4c6e5a93 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -6,6 +6,7 @@ import ( "net/http" "strings" + "github.com/rubixchain/rubixgoplatform/block" "github.com/rubixchain/rubixgoplatform/core/storage" "github.com/rubixchain/rubixgoplatform/core/wallet" "github.com/rubixchain/rubixgoplatform/wrapper/config" @@ -23,6 +24,7 @@ const ( ExplorerTokenCreateNFTAPI string = "/api/token/nft/create" ExplorerCreateUserAPI string = "/api/user/create" ExplorerUpdateUserInfoAPI string = "/api/user/update-user-info" + ExplorerUpdateTokenInfoAPI string = "/api/token/update-token-info" ExplorerGetUserKeyAPI string = "/api/user/get-api-key" ExplorerGenerateUserKeyAPI string = "/api/user/generate-api-key" ExplorerExpireUserKeyAPI string = "/api/user/set-expire-api-key" @@ -54,19 +56,20 @@ type ExplorerMapDID struct { PeerID string `json:"peer_id"` } -// type TokenDetails struct { -// TokenHash string `json:"token_hash"` -// TokenValue float64 `json:"token_value"` -// CurrentOwner string -// PreviousOwner string -// Miner string -// BlockIDs []string -// PledgeDetails PledgeInfo //from latest block if available -// TokenType int -// TokenLevel int -// TokenNumber int -// TokenStatus int -// } +// TODO +type TokenDetails struct { + TokenHash string `json:"token_hash"` + TokenValue float64 `json:"token_value"` + CurrentOwner string + PreviousOwner string + Miner string + BlockIDs []string + PledgeDetails PledgeInfo //from latest block if available + TokenType int + TokenLevel int + TokenNumber int + TokenStatus int +} type Token struct { TokenHash string `json:"token_hash"` @@ -316,6 +319,143 @@ func (c *Core) UpdateUserInfo(dids []string) { } } +func (c *Core) UpdateTokenInfo() { + tokenList := []wallet.Token{} + // dids := []string{} + + err := c.s.Read(wallet.TokenStorage, &tokenList, "token_id!=?", "") + if err != nil { + c.log.Error("Error reading the DID Storage or DID Storage empty") + return + } + tokensToSend := []TokenDetails{} + count := 0 + l := len(tokenList) + for i, token := range tokenList { + if token.Added { + continue + } + td := c.populateTokenDetail(token) + //populate td + tokensToSend = append(tokensToSend, td) + count += 1 + + if count != 10 && i != (l-1) { + continue + } + var er ExplorerResponse + err = c.ec.SendExploerJSONRequest("POST", ExplorerUpdateTokenInfoAPI, &tokensToSend, &er) + if err != nil { + c.log.Error("Failed to update user info, " + err.Error()) + } + if !er.Status { + c.log.Error("Failed to update user info, ", "msg", er.Message) + return + } + + tokensUpdated := strings.Split(er.Message, ",") + for _, t := range tokensUpdated { + t1 := wallet.Token{} + err := c.s.Read(wallet.TokenStorage, &t1, "token_id=?", t) + if err != nil { + c.log.Error("Error reading the DID Storage or DID Storage empty") + return + } + t1.Added = true + err = c.s.Update(wallet.TokenStorage, &t1, "token_id=?", t) + if err != nil { + c.log.Error("Error reading the DID Storage or DID Storage empty") + return + } + } + count = 0 + tokensToSend = []TokenDetails{} + } +} + +func (c *Core) populateTokenDetail(token wallet.Token) TokenDetails { + td := TokenDetails{} + td.TokenHash = token.TokenID + td.TokenValue = token.TokenValue + td.TokenStatus = token.TokenStatus + td.CurrentOwner = "" + td.Miner = "" + td.PreviousOwner = "" + td.BlockIDs = []string{} + td.PledgeDetails = PledgeInfo{} + td.TokenLevel = -1 + td.TokenNumber = -1 + //Get token type + typeString := RBTString + if token.TokenValue < 1.0 { + typeString = PartString + } + td.TokenType = c.TokenType(typeString) + var blocks [][]byte + var nextBlockID string + blockId := "" + var err error + //This for loop ensures that we fetch all the blocks in the token chain + //starting from genesis block to latest block + for { + //GetAllTokenBlocks returns next 100 blocks and nextBlockID of the 100th block, starting from the given block Id, in the direction: genesis to latest block + blocks, nextBlockID, err = c.w.GetAllTokenBlocks(token.TokenID, td.TokenType, blockId) + if err != nil { + return TokenDetails{} + } + //the nextBlockID of the latest block is empty string + blockId = nextBlockID + if nextBlockID == "" { + break + } + } + + //Once we have all the blocks, we traverse each block and get the details from each block. If there is a next block after the current block + //which is of type transaction block, then we get the pledge details from next one. We update the details as we go forward in traversing the + //token chain blocks 0,1,2,3,4 - 4 + + for i := 0; i < len(blocks); i++ { + b := block.InitBlock(blocks[i], nil) + var nb *block.Block + nb = nil + if i < len(blocks)-1 { + nb = block.InitBlock(blocks[i+1], nil) + } + + if b != nil { + txnType := b.GetTransType() + switch txnType { + case block.TokenGeneratedType: + td.Miner = b.GetOwner() + bid, _ := b.GetBlockID(token.TokenID) + td.BlockIDs = append(td.BlockIDs, bid) + td.TokenLevel, td.TokenNumber = b.GetTokenLevel(token.TokenID) + if nb != nil && nb.GetTransType() == block.TokenTransferredType { + continue + } + td.CurrentOwner = b.GetOwner() + fmt.Printf("TD Genesys %+v: ", td) + //TODO : add pledge details for mined tokens + case block.TokenTransferredType: + bid, _ := b.GetBlockID(token.TokenID) + td.BlockIDs = append(td.BlockIDs, bid) + if nb != nil && nb.GetTransType() == block.TokenTransferredType { + continue + } + td.CurrentOwner = b.GetOwner() + td.PreviousOwner = b.GetSenderDID() + b.GetPledgedTokens() + fmt.Printf("TD Else %+v: ", td) + // // td.PledgeDetails = b. + } + + } else { + c.log.Error("Invalid block") + } + } + return td +} + func (c *Core) GenerateUserAPIKey(dids []string) { for _, did := range dids { var er ExplorerUserCreateResponse diff --git a/core/wallet/token.go b/core/wallet/token.go index 56286758..ed923c41 100644 --- a/core/wallet/token.go +++ b/core/wallet/token.go @@ -49,6 +49,7 @@ type Token struct { TokenStatus int `gorm:"column:token_status;"` TokenStateHash string `gorm:"column:token_state_hash"` TransactionID string `gorm:"column:transaction_id"` + Added bool `gorm:"column:added"` } func (w *Wallet) CreateToken(t *Token) error { From 21c0ebc4133d1244eb45956f2cf1677771ffb9bb Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Mon, 4 Nov 2024 11:28:05 +0530 Subject: [PATCH 07/12] passing quorum DID --- core/quorum_validation.go | 2 +- core/smart_contract_token_operations.go | 4 ++-- core/transfer.go | 17 +++++++++++++++-- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/core/quorum_validation.go b/core/quorum_validation.go index 0de9e897..7db899e8 100644 --- a/core/quorum_validation.go +++ b/core/quorum_validation.go @@ -177,7 +177,7 @@ func (c *Core) validateTokenOwnership(cr *ConensusRequest, sc *contract.Contract fb := c.w.GetGenesisTokenBlock(ti[i].Token, ti[i].TokenType) if fb == nil { c.log.Error("Failed to get first token chain block") - return false, fmt.Errorf("failed to get first token chain block", ti[i].Token) + return false, fmt.Errorf("failed to get first token chain block %v", ti[i].Token) } if c.TokenType(PartString) == ti[i].TokenType { pt, _, err := fb.GetParentDetials(ti[i].Token) diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index ba3b81cb..38f8326b 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -186,7 +186,7 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma DeployerDID: did, Creator: did, PledgeAmount: deployReq.RBTAmount, - QuorumList: conensusRequest.QuorumList, + QuorumList: extractQuorumDID(conensusRequest.QuorumList), PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, CommittedTokenList: tokenListForExplorer, Comments: deployReq.Comment, @@ -344,7 +344,7 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute ExecutorDID: did, DeployerDID: smartContractInfo.OwnerDID, Creator: smartContractInfo.OwnerDID, - QuorumList: consensusRequest.QuorumList, + QuorumList: extractQuorumDID(consensusRequest.QuorumList), PledgeAmount: 0, PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, CommittedTokenList: []Token{}, diff --git a/core/transfer.go b/core/transfer.go index 9e84b334..f0ed6061 100644 --- a/core/transfer.go +++ b/core/transfer.go @@ -319,7 +319,7 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest) SenderDID: senderDID, ReceiverDID: receiverdid, Amount: req.TokenCount, - QuorumList: cr.QuorumList, + QuorumList: extractQuorumDID(cr.QuorumList), PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, TransTokenList: tokenListForExplorer, Comments: req.Comment, @@ -551,7 +551,7 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ SenderDID: did, ReceiverDID: pinningNodeDID, Amount: req.TokenCount, - QuorumList: cr.QuorumList, + QuorumList: extractQuorumDID(cr.QuorumList), PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, Comments: req.Comment, } @@ -562,3 +562,16 @@ func (c *Core) completePinning(st time.Time, reqID string, req *model.RBTPinRequ resp.Message = msg return resp } + +func extractQuorumDID(quorumList []string) []string { + var quorumListDID []string + for _, quorum := range quorumList { + parts := strings.Split(quorum, ".") + if len(parts) > 1 { + quorumListDID = append(quorumListDID, parts[1]) + } else { + quorumListDID = append(quorumListDID, parts[0]) + } + } + return quorumListDID +} From 913191196252a355714cf8a0ea03aaaf77fd5226 Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Tue, 24 Dec 2024 12:01:02 +0530 Subject: [PATCH 08/12] updated for FT --- core/ft.go | 30 +++++++++++++++--------------- core/quorum_initiator.go | 39 +++++++++++++++++++-------------------- 2 files changed, 34 insertions(+), 35 deletions(-) diff --git a/core/ft.go b/core/ft.go index d91da732..f87a81a6 100644 --- a/core/ft.go +++ b/core/ft.go @@ -477,7 +477,7 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model ContractBlock: sc.GetBlock(), FTinfo: FTData, } - td, _, err := c.initiateConsensus(cr, sc, dc) + td, _, _, err := c.initiateConsensus(cr, sc, dc) if err != nil { c.log.Error("Consensus failed ", "err", err) resp.Message = "Consensus failed " + err.Error() @@ -490,20 +490,20 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model c.w.AddTransactionHistory(td) //TODO : Extra details regarding the FT need to added in the explorer - etrans := &ExplorerTrans{ - TID: td.TransactionID, - SenderDID: did, - ReceiverDID: rdid, - Amount: float64(req.FTCount), - TrasnType: req.QuorumType, - TokenIDs: FTTokenIDs, - QuorumList: cr.QuorumList, - TokenTime: float64(dif.Milliseconds()), - } - explorerErr := c.ec.ExplorerTransaction(etrans) - if explorerErr != nil { - c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) - } + // etrans := &ExplorerTrans{ + // TID: td.TransactionID, + // SenderDID: did, + // ReceiverDID: rdid, + // Amount: float64(req.FTCount), + // TrasnType: req.QuorumType, + // TokenIDs: FTTokenIDs, + // QuorumList: cr.QuorumList, + // TokenTime: float64(dif.Milliseconds()), + // } + // explorerErr := c.ec.ExplorerTransaction(etrans) + // if explorerErr != nil { + // c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) + // } updateFTTableErr := c.updateFTTable(did) if updateFTTableErr != nil { diff --git a/core/quorum_initiator.go b/core/quorum_initiator.go index b9d24d6d..5788505a 100644 --- a/core/quorum_initiator.go +++ b/core/quorum_initiator.go @@ -662,7 +662,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc rp, err := c.getPeer(cr.ReceiverPeerID+"."+sc.GetReceiverDID(), "") if err != nil { c.log.Error("Receiver not connected", "err", err) - return nil, nil, err + return nil, nil, nil, err } defer rp.Close() @@ -716,7 +716,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = rp.SendJSONRequest("POST", APISendFTToken, nil, &sr, &br, true) if err != nil { c.log.Error("Unable to send tokens to receiver", "err", err) - return nil, nil, err + return nil, nil, nil, err } if strings.Contains(br.Message, "failed to sync tokenchain") { tokenPrefix := "Token: " @@ -735,33 +735,33 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if err1 != nil { errMsg := fmt.Sprintf("Consensus failed due to token chain sync issue, issueType string conversion, err %v", err1) c.log.Error(errMsg) - return nil, nil, fmt.Errorf(errMsg) + return nil, nil, nil, fmt.Errorf(errMsg) } c.log.Debug("issue type in int is ", issueTypeInt) syncIssueTokenDetails, err2 := c.w.ReadToken(token) if err2 != nil { errMsg := fmt.Sprintf("Consensus failed due to tokenchain sync issue, err %v", err2) c.log.Error(errMsg) - return nil, nil, fmt.Errorf(errMsg) + return nil, nil, nil, fmt.Errorf(errMsg) } c.log.Debug("sync issue token details ", syncIssueTokenDetails) if issueTypeInt == TokenChainNotSynced { syncIssueTokenDetails.TokenStatus = wallet.TokenChainSyncIssue c.log.Debug("Token sync issue details updated:", syncIssueTokenDetails) c.w.UpdateToken(syncIssueTokenDetails) - return nil, nil, errors.New(br.Message) + return nil, nil, nil, errors.New(br.Message) } } if !br.Status { c.log.Error("Unable to send FT tokens to receiver", "msg", br.Message) - return nil, nil, fmt.Errorf("unable to send FT tokens to receiver, " + br.Message) + return nil, nil, nil, fmt.Errorf("unable to send FT tokens to receiver, " + br.Message) } // Extract new token state hashes from response newTokenHashResult, ok := br.Result.([]interface{}) if !ok { c.log.Error("Failed to assert type for new token hashes") - return nil, nil, fmt.Errorf("Type assertion to string failed") + return nil, nil, nil, fmt.Errorf("Type assertion to string failed") } var newTokenHashes []string @@ -769,7 +769,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc stateHash, ok := newTokenHash.(string) if !ok { c.log.Error("Type assertion to string failed at index", i) - return nil, nil, fmt.Errorf("Type assertion to string failed at index %d", i) + return nil, nil, nil, fmt.Errorf("Type assertion to string failed at index %d", i) } newTokenHashes = append(newTokenHashes, stateHash) } @@ -778,14 +778,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc pledgeFinalityError := c.quorumPledgeFinality(cr, nb, newTokenHashes, tid) if pledgeFinalityError != nil { c.log.Error("Pledge finlaity not achieved", "err", err) - return nil, nil, pledgeFinalityError + return nil, nil, nil, pledgeFinalityError } //Checking prev block details (i.e. the latest block before transferring) by sender. Sender will connect with old quorums, and update about the exhausted token state hashes to quorums for them to unpledge their tokens. for _, tokeninfo := range ti { b := c.w.GetLatestTokenBlock(tokeninfo.Token, tokeninfo.TokenType) previousQuorumDIDs, err := b.GetSigner() if err != nil { - return nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) } //if signer is similar to sender did skip this token, as the block is the genesis block @@ -796,7 +796,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //concat tokenId and BlockID bid, errBlockID := b.GetBlockID(tokeninfo.Token) if errBlockID != nil { - return nil, nil, fmt.Errorf("unable to fetch current block id for Token %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch current block id for Token %v, err: %v", tokeninfo.Token, err) } prevtokenIDTokenStateData := tokeninfo.Token + bid prevtokenIDTokenStateBuffer := bytes.NewBuffer([]byte(prevtokenIDTokenStateData)) @@ -804,7 +804,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //add to ipfs get only the hash of the token+tokenstate. This is the hash just before transferring i.e. the exhausted token state hash, and updating in Sender side prevtokenIDTokenStateHash, errIpfsAdd := c.ipfs.Add(prevtokenIDTokenStateBuffer, ipfsnode.Pin(false), ipfsnode.OnlyHash(true)) if errIpfsAdd != nil { - return nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) + return nil, nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) } //send this exhausted hash to old quorums to unpledge for _, previousQuorumDID := range previousQuorumDIDs { @@ -816,7 +816,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if previousQuorumPeerID == "" { _, err := c.w.GetDID(previousQuorumDID) if err != nil { - return nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) + return nil, nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) } else { previousQuorumPeerID = c.peerID } @@ -825,21 +825,21 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc previousQuorumAddress := previousQuorumPeerID + "." + previousQuorumDID previousQuorumPeer, errGetPeer := c.getPeer(previousQuorumAddress, "") if errGetPeer != nil { - return nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) + return nil, nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) } updateTokenHashDetailsQuery := make(map[string]string) updateTokenHashDetailsQuery["tokenIDTokenStateHash"] = prevtokenIDTokenStateHash err := previousQuorumPeer.SendJSONRequest("POST", APIUpdateTokenHashDetails, updateTokenHashDetailsQuery, nil, nil, true) if err != nil { - return nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) + return nil, nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) } } } err = c.w.FTTokensTransffered(sc.GetSenderDID(), ti, nb) if err != nil { c.log.Error("Failed to transfer tokens", "err", err) - return nil, nil, err + return nil, nil, nil, err } for _, t := range ti { c.w.UnPin(t.Token, wallet.PrevSenderRole, sc.GetSenderDID()) @@ -849,7 +849,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc nbid, err := nb.GetBlockID(ti[0].Token) if err != nil { c.log.Error("Failed to get block id", "err", err) - return nil, nil, err + return nil, nil, nil, err } td := model.TransactionDetails{ @@ -868,11 +868,10 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc err = c.initiateUnpledgingProcess(cr, td.TransactionID, td.Epoch) if err != nil { c.log.Error("Failed to store transactiond details with quorum ", "err", err) - return nil, nil, err + return nil, nil, nil, err } - return &td, pl, nil - + return &td, pl, pds, nil case PinningServiceMode: c.log.Debug("Mode = PinningServiceMode ") c.log.Debug("Pinning Node PeerId", cr.PinningNodePeerID) From 1d79dcc60b600b78508f27286433ce90298b4cf3 Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Thu, 26 Dec 2024 13:38:07 +0530 Subject: [PATCH 09/12] Updated FT and NFT explorer structure --- core/explorer.go | 56 ++++++++++++++++++++++--- core/ft.go | 21 +++++++++- core/nft.go | 42 ++++++++++++++++++- core/smart_contract_token_operations.go | 4 +- 4 files changed, 113 insertions(+), 10 deletions(-) diff --git a/core/explorer.go b/core/explorer.go index 4c6e5a93..63f6ae74 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -85,10 +85,11 @@ type ChildToken struct { TokenValue float64 `json:"token_value"` } -type SCToken struct { - SCTokenHash string `json:"token_hash"` - SCBlockHash string `json:"block_hash"` - SCBlockNumber int `json:"block_number"` +// Smart contract, +type AllToken struct { + TokenHash string `json:"token_hash"` + BlockHash string `json:"block_hash"` + BlockNumber int `json:"block_number"` } type ExplorerCreateToken struct { @@ -139,7 +140,7 @@ type ExplorerRBTTrans struct { Comments string `json:"comments"` } type ExplorerSCTrans struct { - SCBlockHash []SCToken `json:"sc_block_hash"` + SCBlockHash []AllToken `json:"sc_block_hash"` TransactionID string `json:"transaction_id"` Network int `json:"network"` ExecutorDID string `json:"executor"` @@ -152,6 +153,51 @@ type ExplorerSCTrans struct { Comments string `json:"comments"` } +type ExplorerNFTDeploy struct { + NFTBlockHash []AllToken `json:"nft_block_hash"` + NFTValue float64 `json:"nft_value"` + TransactionID string `json:"transaction_id"` + Network int `json:"network"` + OwnerDID string `json:"owner"` + DeployerDID string `json:"deployer"` + PledgeAmount float64 `json:"pledge_amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` + Comments string `json:"comments"` +} + +type ExplorerNFTExecute struct { + NFT string `json:"nft"` + ExecutorDID string `json:"owner"` + ReceiverDID string `json:"receiver"` + Network int `json:"network"` + Comments string `json:"comments"` + NFTValue float64 `json:"nft_value"` + NFTData string `json:"nft_data"` + NFTBlockHash []AllToken `json:"sc_block_hash"` + PledgeAmount float64 `json:"pledge_amount"` + TransactionID string `json:"transaction_id"` + Amount float64 `json:"amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` +} + +type ExplorerFTTrans struct { + CreatorDID string `json:"creator"` + SenderDID string `json:"sender"` + ReceiverDID string `json:"receiver"` + FTName string `json:"ft_name"` + FTSymbol string `json:"ft_symbol"` + FTTransferCount int `json:"ft_transfer_count"` + Network int `json:"network"` + Comments string `json:"comments"` + FTTokenList []string `json:"ft_token_list"` + TransactionID string `json:"transaction_id"` + Amount float64 `json:"amount"` + QuorumList []string `json:"quorum_list"` + PledgeInfo PledgeInfo `json:"pledge_info"` +} + type ExplorerResponse struct { Message string `json:"Message"` Status bool `json:"Status"` diff --git a/core/ft.go b/core/ft.go index f87a81a6..4085abaf 100644 --- a/core/ft.go +++ b/core/ft.go @@ -367,6 +367,7 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model resp.Message = "Failed to setup DID, " + err.Error() return resp } + var creatorDID string if req.CreatorDID == "" { // Checking for same FTs with different creators info, err := c.GetFTInfo(did) @@ -390,10 +391,12 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model return resp } } + creatorDID = info[0].CreatorDID } var AllFTs []wallet.FTToken if req.CreatorDID != "" { AllFTs, err = c.w.GetFreeFTsByNameAndCreatorDID(req.FTName, did, req.CreatorDID) + creatorDID = req.CreatorDID } else { AllFTs, err = c.w.GetFreeFTsByNameAndDID(req.FTName, did) } @@ -477,7 +480,7 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model ContractBlock: sc.GetBlock(), FTinfo: FTData, } - td, _, _, err := c.initiateConsensus(cr, sc, dc) + td, _, pds, err := c.initiateConsensus(cr, sc, dc) if err != nil { c.log.Error("Consensus failed ", "err", err) resp.Message = "Consensus failed " + err.Error() @@ -505,6 +508,22 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model // c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) // } + _ = &ExplorerFTTrans{ + CreatorDID: creatorDID, + SenderDID: did, + ReceiverDID: rdid, + FTName: req.FTName, + FTTransferCount: req.FTCount, + Network: req.QuorumType, + FTSymbol: "TODO", + Comments: req.Comment, + TransactionID: td.TransactionID, + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, + QuorumList: extractQuorumDID(cr.QuorumList), + Amount: FTsForTxn[0].TokenValue * float64(req.FTCount), + FTTokenList: FTTokenIDs, + } + updateFTTableErr := c.updateFTTable(did) if updateFTTableErr != nil { c.log.Error("Failed to update FT table after transfer ", "err", updateFTTableErr) diff --git a/core/nft.go b/core/nft.go index 4d79bb6f..647f5fbf 100644 --- a/core/nft.go +++ b/core/nft.go @@ -6,6 +6,8 @@ import ( "fmt" "io" "os" + "strconv" + "strings" "time" "github.com/rubixchain/rubixgoplatform/contract" @@ -206,7 +208,7 @@ func (c *Core) deployNFT(reqID string, deployReq model.DeployNFTRequest) *model. TransactionEpoch: txEpoch, } - txnDetails, _, _, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) + txnDetails, _, pds, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) if err != nil { c.log.Error("Consensus failed", "err", err) @@ -233,6 +235,23 @@ func (c *Core) deployNFT(reqID string, deployReq model.DeployNFTRequest) *model. // //BlockHash: txnDetails.BlockID, // } // c.ec.ExplorerTransaction(explorerTrans) + blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] + // Convert the string part to an int + blockNoInt, _ := strconv.Atoi(blockNoPart) + //Rename : TODO + _ = &ExplorerNFTDeploy{ + NFTBlockHash: []AllToken{{TokenHash: deployReq.NFT, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, + TransactionID: txnDetails.TransactionID, + Network: conensusRequest.Type, + NFTValue: nftInfo.TokenValue, + DeployerDID: did, + OwnerDID: nftInfo.OwnerDID, + PledgeAmount: consensusContractDetails.TotalRBTs, + QuorumList: extractQuorumDID(conensusRequest.QuorumList), + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, + Comments: txnDetails.Comment, + } + // c.ec.ExplorerSCTransaction(eTrans) c.log.Info("NFT Deployed successfully", "duration", dif) resp.Status = true @@ -388,7 +407,7 @@ func (c *Core) executeNFT(reqID string, executeReq *model.ExecuteNFTRequest) *mo TransactionEpoch: txEpoch, } - txnDetails, _, _, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) + txnDetails, _, pds, err := c.initiateConsensus(conensusRequest, consensusContract, didCryptoLib) if err != nil { c.log.Error("Consensus failed", "err", err) resp.Message = "Consensus failed" + err.Error() @@ -411,6 +430,25 @@ func (c *Core) executeNFT(reqID string, executeReq *model.ExecuteNFTRequest) *mo // TokenTime: float64(dif.Milliseconds()), // //BlockHash: txnDetails.BlockID, // } + blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] + // Convert the string part to an int + blockNoInt, _ := strconv.Atoi(blockNoPart) + //Rename : TODO + _ = &ExplorerNFTExecute{ + NFT: NFTString, + ExecutorDID: currentOwner, + ReceiverDID: receiver, + Network: executeReq.QuorumType, + Comments: executeReq.Comment, + NFTValue: executeReq.NFTValue, + NFTData: executeReq.NFTData, + NFTBlockHash: []AllToken{{TokenHash: executeReq.NFT, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, + PledgeAmount: consensusContractDetails.TotalRBTs, + TransactionID: txnDetails.TransactionID, + QuorumList: extractQuorumDID(conensusRequest.QuorumList), + PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, + } + receiverPeerId := c.w.GetPeerID(executeReq.Receiver) local := false if receiverPeerId == c.peerID || receiverPeerId == "" { diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index 2a28aa6b..fb2015c2 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -184,7 +184,7 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCBlockHash: []SCToken{{SCTokenHash: deployReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, + SCBlockHash: []AllToken{{TokenHash: deployReq.SmartContractToken, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, TransactionID: txnDetails.TransactionID, Network: conensusRequest.Type, ExecutorDID: "", @@ -343,7 +343,7 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCBlockHash: []SCToken{{SCTokenHash: executeReq.SmartContractToken, SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], SCBlockNumber: blockNoInt}}, + SCBlockHash: []AllToken{{TokenHash: executeReq.SmartContractToken, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, TransactionID: txnDetails.TransactionID, Network: consensusRequest.Type, ExecutorDID: did, From 7dd6f789bd76e1bacd9f42d88aac6fd05d56082d Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Mon, 6 Jan 2025 12:33:01 +0530 Subject: [PATCH 10/12] updating return values --- core/quorum_initiator.go | 68 ++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/core/quorum_initiator.go b/core/quorum_initiator.go index 8b02a0b5..5ca8d4ee 100644 --- a/core/quorum_initiator.go +++ b/core/quorum_initiator.go @@ -503,10 +503,10 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if qpid == "" { _, err := c.w.GetDID(qdid) if err != nil { - return nil, nil, fmt.Errorf("unable to fetch peerID for quorum DID: %v which fetching quorum information", qdid) + return nil, nil, nil, fmt.Errorf("unable to fetch peerID for quorum DID: %v which fetching quorum information", qdid) } else { qpid = c.peerID - } + } } var qrmInfo QuorumDIDPeerMap @@ -516,7 +516,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if strings.Contains(err.Error(), "no records found") { didInfo, err := c.w.GetDID(qdid) if err != nil { - return nil, nil, err + return nil, nil, nil, err } else { qDidType = didInfo.Type } @@ -616,7 +616,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc b := c.w.GetLatestTokenBlock(tokeninfo.Token, tokeninfo.TokenType) previousQuorumDIDs, err := b.GetSigner() if err != nil { - return nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) } //if signer is similar to sender did skip this token, as the block is the genesis block @@ -627,7 +627,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //concat tokenId and BlockID bid, errBlockID := b.GetBlockID(tokeninfo.Token) if errBlockID != nil { - return nil, nil, fmt.Errorf("unable to fetch current block id for Token %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch current block id for Token %v, err: %v", tokeninfo.Token, err) } prevtokenIDTokenStateData := tokeninfo.Token + bid prevtokenIDTokenStateBuffer := bytes.NewBuffer([]byte(prevtokenIDTokenStateData)) @@ -635,7 +635,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //add to ipfs get only the hash of the token+tokenstate. This is the hash just before transferring i.e. the exhausted token state hash, and updating in Sender side prevtokenIDTokenStateHash, errIpfsAdd := c.ipfs.Add(prevtokenIDTokenStateBuffer, ipfsnode.Pin(false), ipfsnode.OnlyHash(true)) if errIpfsAdd != nil { - return nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) + return nil, nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) } //send this exhausted hash to old quorums to unpledge for _, previousQuorumDID := range previousQuorumDIDs { @@ -647,7 +647,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if previousQuorumPeerID == "" { _, err := c.w.GetDID(previousQuorumDID) if err != nil { - return nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) + return nil, nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) } else { previousQuorumPeerID = c.peerID } @@ -656,14 +656,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc previousQuorumAddress := previousQuorumPeerID + "." + previousQuorumDID previousQuorumPeer, errGetPeer := c.getPeer(previousQuorumAddress, "") if errGetPeer != nil { - return nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) + return nil, nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) } updateTokenHashDetailsQuery := make(map[string]string) updateTokenHashDetailsQuery["tokenIDTokenStateHash"] = prevtokenIDTokenStateHash err := previousQuorumPeer.SendJSONRequest("POST", APIUpdateTokenHashDetails, updateTokenHashDetailsQuery, nil, nil, true) if err != nil { - return nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) + return nil, nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) } } } @@ -1046,7 +1046,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc b := c.w.GetLatestTokenBlock(tokeninfo.Token, tokeninfo.TokenType) previousQuorumDIDs, err := b.GetSigner() if err != nil { - return nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) } //if signer is similar to sender did skip this token, as the block is the genesis block @@ -1057,7 +1057,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //concat tokenId and BlockID bid, errBlockID := b.GetBlockID(tokeninfo.Token) if errBlockID != nil { - return nil, nil, fmt.Errorf("unable to fetch current block id for Token %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch current block id for Token %v, err: %v", tokeninfo.Token, err) } prevtokenIDTokenStateData := tokeninfo.Token + bid prevtokenIDTokenStateBuffer := bytes.NewBuffer([]byte(prevtokenIDTokenStateData)) @@ -1065,7 +1065,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //add to ipfs get only the hash of the token+tokenstate. This is the hash just before transferring i.e. the exhausted token state hash, and updating in Sender side prevtokenIDTokenStateHash, errIpfsAdd := c.ipfs.Add(prevtokenIDTokenStateBuffer, ipfsnode.Pin(false), ipfsnode.OnlyHash(true)) if errIpfsAdd != nil { - return nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) + return nil, nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) } //send this exhausted hash to old quorums to unpledge for _, previousQuorumDID := range previousQuorumDIDs { @@ -1077,7 +1077,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if previousQuorumPeerID == "" { _, err := c.w.GetDID(previousQuorumDID) if err != nil { - return nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) + return nil, nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) } else { previousQuorumPeerID = c.peerID } @@ -1086,14 +1086,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc previousQuorumAddress := previousQuorumPeerID + "." + previousQuorumDID previousQuorumPeer, errGetPeer := c.getPeer(previousQuorumAddress, "") if errGetPeer != nil { - return nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) + return nil, nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) } updateTokenHashDetailsQuery := make(map[string]string) updateTokenHashDetailsQuery["tokenIDTokenStateHash"] = prevtokenIDTokenStateHash err := previousQuorumPeer.SendJSONRequest("POST", APIUpdateTokenHashDetails, updateTokenHashDetailsQuery, nil, nil, true) if err != nil { - return nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) + return nil, nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) } } } @@ -1194,7 +1194,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc b := c.w.GetLatestTokenBlock(tokeninfo.Token, tokeninfo.TokenType) previousQuorumDIDs, err := b.GetSigner() if err != nil { - return nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", tokeninfo.Token, err) } //if signer is similar to sender did skip this token, as the block is the genesys block @@ -1206,7 +1206,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc // the previous block ID bid, errBlockID := b.GetPrevBlockID(tokeninfo.Token) if errBlockID != nil { - return nil, nil, fmt.Errorf("unable to fetch previous block id for Token %v, err: %v", tokeninfo.Token, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous block id for Token %v, err: %v", tokeninfo.Token, err) } prevtokenIDTokenStateData := tokeninfo.Token + bid @@ -1215,9 +1215,9 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //add to ipfs get only the hash of the token+tokenstate. This is the hash just before transferring i.e. the exhausted token state hash, and updating in Sender side prevtokenIDTokenStateHash, errIpfsAdd := c.ipfs.Add(prevtokenIDTokenStateBuffer, ipfsnode.Pin(false), ipfsnode.OnlyHash(true)) if errIpfsAdd != nil { - return nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) + return nil, nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", tokeninfo.Token, errIpfsAdd) } - + //send this exhausted hash to old quorums to unpledge for _, previousQuorumDID := range previousQuorumDIDs { previousQuorumPeerID := c.w.GetPeerID(previousQuorumDID) @@ -1228,23 +1228,23 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if previousQuorumPeerID == "" { _, err := c.w.GetDID(previousQuorumDID) if err != nil { - return nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) + return nil, nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) } else { previousQuorumPeerID = c.peerID } } - + previousQuorumAddress := previousQuorumPeerID + "." + previousQuorumDID previousQuorumPeer, errGetPeer := c.getPeer(previousQuorumAddress, "") if errGetPeer != nil { - return nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) + return nil, nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) } updateTokenHashDetailsQuery := make(map[string]string) updateTokenHashDetailsQuery["tokenIDTokenStateHash"] = prevtokenIDTokenStateHash err := previousQuorumPeer.SendJSONRequest("POST", APIUpdateTokenHashDetails, updateTokenHashDetailsQuery, nil, nil, true) if err != nil { - return nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) + return nil, nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", prevtokenIDTokenStateHash, previousQuorumPeerID, err) } } } @@ -1385,7 +1385,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc previousQuorumDIDs, err := b.GetSigner() if err != nil { - return nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", cr.SmartContractToken, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", cr.SmartContractToken, err) } //Create tokechain for the smart contract token and add genesys block @@ -1436,14 +1436,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc //inform old quorums about exhausted smart contract token hash prevBlockId, errBlockID := nb.GetPrevBlockID((cr.SmartContractToken)) if errBlockID != nil { - return nil, nil, fmt.Errorf("unable to fetch previous block id for Token %v, err: %v", cr.SmartContractToken, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous block id for Token %v, err: %v", cr.SmartContractToken, err) } scTokenStateDataOld := cr.SmartContractToken + prevBlockId scTokenStateDataOldBuffer := bytes.NewBuffer([]byte(scTokenStateDataOld)) oldsctokenIDTokenStateHash, errIpfsAdd := c.ipfs.Add(scTokenStateDataOldBuffer, ipfsnode.Pin(false), ipfsnode.OnlyHash(true)) if errIpfsAdd != nil { - return nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", cr.SmartContractToken, errIpfsAdd) + return nil, nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", cr.SmartContractToken, errIpfsAdd) } for _, previousQuorumDID := range previousQuorumDIDs { @@ -1455,7 +1455,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if previousQuorumPeerID == "" { _, err := c.w.GetDID(previousQuorumDID) if err != nil { - return nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) + return nil, nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) } else { previousQuorumPeerID = c.peerID } @@ -1464,14 +1464,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc previousQuorumAddress := previousQuorumPeerID + "." + previousQuorumDID previousQuorumPeer, errGetPeer := c.getPeer(previousQuorumAddress, "") if errGetPeer != nil { - return nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) + return nil, nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) } updateTokenHashDetailsQuery := make(map[string]string) updateTokenHashDetailsQuery["tokenIDTokenStateHash"] = oldsctokenIDTokenStateHash err := previousQuorumPeer.SendJSONRequest("POST", APIUpdateTokenHashDetails, updateTokenHashDetailsQuery, nil, nil, true) if err != nil { - return nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", oldsctokenIDTokenStateHash, previousQuorumPeerID, err) + return nil, nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", oldsctokenIDTokenStateHash, previousQuorumPeerID, err) } } @@ -1556,7 +1556,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc b := c.w.GetLatestTokenBlock(cr.NFT, nb.GetTokenType(cr.NFT)) previousQuorumDIDs, err := b.GetSigner() if err != nil { - return nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", cr.NFT, err) + return nil, nil, nil, fmt.Errorf("unable to fetch previous quorum's DIDs for token: %v, err: %v", cr.NFT, err) } err = c.w.AddTokenBlock(cr.NFT, nb) @@ -1602,7 +1602,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc nftTokenStateDataOldBuffer := bytes.NewBuffer([]byte(nftTokenStateDataOld)) oldnfttokenIDTokenStateHash, errIpfsAdd := c.ipfs.Add(nftTokenStateDataOldBuffer, ipfsnode.Pin(false), ipfsnode.OnlyHash(true)) if errIpfsAdd != nil { - return nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", nftTokenStateDataOldBuffer, errIpfsAdd) + return nil, nil, nil, fmt.Errorf("unable to get previous token state hash for token: %v, err: %v", nftTokenStateDataOldBuffer, errIpfsAdd) } for _, previousQuorumDID := range previousQuorumDIDs { @@ -1614,7 +1614,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc if previousQuorumPeerID == "" { _, err := c.w.GetDID(previousQuorumDID) if err != nil { - return nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) + return nil, nil, nil, fmt.Errorf("unable to get peerID for signer DID: %v. It is likely that either the DID is not created anywhere or ", previousQuorumDID) } else { previousQuorumPeerID = c.peerID } @@ -1623,14 +1623,14 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc previousQuorumAddress := previousQuorumPeerID + "." + previousQuorumDID previousQuorumPeer, errGetPeer := c.getPeer(previousQuorumAddress, "") if errGetPeer != nil { - return nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) + return nil, nil, nil, fmt.Errorf("unable to retrieve peer information for %v, err: %v", previousQuorumPeerID, errGetPeer) } updateTokenHashDetailsQuery := make(map[string]string) updateTokenHashDetailsQuery["tokenIDTokenStateHash"] = oldnfttokenIDTokenStateHash err := previousQuorumPeer.SendJSONRequest("POST", APIUpdateTokenHashDetails, updateTokenHashDetailsQuery, nil, nil, true) if err != nil { - return nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", oldnfttokenIDTokenStateHash, previousQuorumPeerID, err) + return nil, nil, nil, fmt.Errorf("unable to send request to remove token hash details for state hash: %v to peer: %v, err: %v", oldnfttokenIDTokenStateHash, previousQuorumPeerID, err) } } From 01928c84236ec3d6556b93db1d5a696558c7f0bc Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Mon, 6 Jan 2025 17:19:54 +0530 Subject: [PATCH 11/12] updated Structure and URL --- command/command.go | 2 +- core/did.go | 4 +- core/explorer.go | 129 ++++++++++++++++-------- core/ft.go | 30 +++++- core/nft.go | 40 ++------ core/smart_contract_token_operations.go | 8 +- 6 files changed, 135 insertions(+), 78 deletions(-) diff --git a/command/command.go b/command/command.go index 8cd5e11a..1a56dc44 100644 --- a/command/command.go +++ b/command/command.go @@ -410,7 +410,7 @@ func (cmd *Command) runApp() { dids := c.ExplorerUserCreate() //Checking if all the DIDs are in the ExplorerUserDetailtable or not. c.UpdateUserInfo(dids) //Updating the balance c.GenerateUserAPIKey(dids) //Regenerating the API Key for DID - c.UpdateTokenInfo() + // c.UpdateTokenInfo() cmd.log.Info("Syncing Complete...") ch := make(chan os.Signal, 1) diff --git a/core/did.go b/core/did.go index e84285cf..573a33ca 100644 --- a/core/did.go +++ b/core/did.go @@ -134,9 +134,7 @@ func (c *Core) CreateDID(didCreate *did.DIDCreate) (string, error) { Balance: 0, DIDType: didCreate.Type, } - if !c.testNet { - c.ec.ExplorerUserCreate(newDID) - } + c.ec.ExplorerUserCreate(newDID) return did, nil } diff --git a/core/explorer.go b/core/explorer.go index 705357d8..f8ca0a1b 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -19,8 +19,6 @@ const ( ExplorerBasePath string = "/api/v2/services/app/Rubix/" ExplorerTokenCreateAPI string = "/api/token/create" ExplorerTokenCreatePartsAPI string = "/api/token/part/create" - ExplorerTokenCreateSCAPI string = "/api/token/sc/create" - ExplorerTokenCreateFTAPI string = "/api/token/ft/create" ExplorerTokenCreateNFTAPI string = "/api/token/nft/create" ExplorerCreateUserAPI string = "/api/user/create" ExplorerUpdateUserInfoAPI string = "/api/user/update-user-info" @@ -30,6 +28,8 @@ const ( ExplorerExpireUserKeyAPI string = "/api/user/set-expire-api-key" ExplorerRBTTransactionAPI string = "/api/transactions/rbt" ExplorerSCTransactionAPI string = "/api/transactions/sc" + ExplorerFTTransactionAPI string = "/api/transactions/ft" + ExplorerNFTTransactionAPI string = "/api/transactions/nft" ExplorerUpdatePledgeStatusAPI string = "/api/token/update-pledge-status" ExplorerCreateDataTransAPI string = "create-datatokens" ExplorerMapDIDAPI string = "map-did" @@ -85,11 +85,11 @@ type ChildToken struct { TokenValue float64 `json:"token_value"` } -// Smart contract, +// NFT and FT type AllToken struct { - TokenHash string `json:"token_hash"` - BlockHash string `json:"block_hash"` - BlockNumber int `json:"block_number"` + TokenHash string `json:"tokenHash"` + BlockHash string `json:"blockHash"` + BlockNumber int `json:"blockNumber"` } type ExplorerCreateToken struct { @@ -140,7 +140,9 @@ type ExplorerRBTTrans struct { Comments string `json:"comments"` } type ExplorerSCTrans struct { - SCBlockHash []AllToken `json:"sc_block_hash"` + SCTokenHash string `json:"sc_token_hash"` + SCBlockHash string `json:"block_hash"` + SCBlockNumber int `json:"block_number"` TransactionID string `json:"transaction_id"` Network int `json:"network"` ExecutorDID string `json:"executor"` @@ -154,47 +156,48 @@ type ExplorerSCTrans struct { } type ExplorerNFTDeploy struct { - NFTBlockHash []AllToken `json:"nft_block_hash"` - NFTValue float64 `json:"nft_value"` - TransactionID string `json:"transaction_id"` + NFTBlockHash []AllToken `json:"nftBlockHash"` + NFTValue float64 `json:"nftValue"` + TransactionID string `json:"transactionID"` Network int `json:"network"` - OwnerDID string `json:"owner"` - DeployerDID string `json:"deployer"` - PledgeAmount float64 `json:"pledge_amount"` - QuorumList []string `json:"quorum_list"` - PledgeInfo PledgeInfo `json:"pledge_info"` + OwnerDID string `json:"ownerDID"` + DeployerDID string `json:"deployerDID"` + PledgeAmount float64 `json:"pledgeAmount"` + QuorumList []string `json:"quorumList"` + PledgeInfo PledgeInfo `json:"pledgeInfo"` Comments string `json:"comments"` } type ExplorerNFTExecute struct { + NFTBlockHash []AllToken `json:"nftBlockHash"` NFT string `json:"nft"` - ExecutorDID string `json:"owner"` - ReceiverDID string `json:"receiver"` + ExecutorDID string `json:"executorDID"` + ReceiverDID string `json:"receiverDID"` Network int `json:"network"` Comments string `json:"comments"` - NFTValue float64 `json:"nft_value"` - NFTData string `json:"nft_data"` - NFTBlockHash []AllToken `json:"sc_block_hash"` - PledgeAmount float64 `json:"pledge_amount"` - TransactionID string `json:"transaction_id"` + NFTValue float64 `json:"nftValue"` + NFTData string `json:"nftData"` + PledgeAmount float64 `json:"pledgeAmount"` + TransactionID string `json:"transactionID"` Amount float64 `json:"amount"` - QuorumList []string `json:"quorum_list"` - PledgeInfo PledgeInfo `json:"pledge_info"` + QuorumList []string `json:"quorumList"` + PledgeInfo PledgeInfo `json:"pledgeInfo"` } type ExplorerFTTrans struct { + FTBlockHash []AllToken `json:"ftBlockHash"` CreatorDID string `json:"creator"` - SenderDID string `json:"sender"` - ReceiverDID string `json:"receiver"` - FTName string `json:"ft_name"` - FTSymbol string `json:"ft_symbol"` - FTTransferCount int `json:"ft_transfer_count"` + SenderDID string `json:"senderDID"` + ReceiverDID string `json:"receiverDID"` + FTName string `json:"ftName"` + FTSymbol string `json:"ftSymbol"` + FTTransferCount int `json:"ftTransferCount"` Network int `json:"network"` Comments string `json:"comments"` - FTTokenList []string `json:"ft_token_list"` - TransactionID string `json:"transaction_id"` + FTTokenList []string `json:"ftTokenList"` + TransactionID string `json:"transactionID"` Amount float64 `json:"amount"` - QuorumList []string `json:"quorum_list"` + QuorumList []string `json:"quorumList"` PledgeInfo PledgeInfo `json:"pledge_info"` } @@ -234,17 +237,21 @@ func (c *Core) InitRubixExplorer() error { return err } url := "rexplorer.azurewebsites.net" + protocol := "https" + if c.testNet { + url = "98.70.52.158:8080" + protocol = "http" + } err = c.s.Read(ExplorerURLTable, &ExplorerURL{}, "url=?", url) if err != nil { - err = c.s.Write(ExplorerURLTable, &ExplorerURL{URL: url, Port: 443, Protocol: "https"}) + err = c.s.Write(ExplorerURLTable, &ExplorerURL{URL: url, Port: 443, Protocol: protocol}) } - if err != nil { return err } - cl, err := ensweb.NewClient(&config.Config{ServerAddress: url, ServerPort: "0", Production: "true"}, c.log) + cl, err := ensweb.NewClient(&config.Config{ServerAddress: url, ServerPort: "0", Production: fmt.Sprintf("%t", !c.testNet)}, c.log) if err != nil { return err } @@ -266,7 +273,7 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp for _, url := range urls { apiKeyForHeader := "" - if url == "https://rexplorer.azurewebsites.net" { + if url == "https://rexplorer.azurewebsites.net" || url == "http://98.70.52.158:8080" { apiKeyForHeader = ec.getAPIKey(path, input) } else { apiKeyForHeader = "" @@ -393,10 +400,10 @@ func (c *Core) UpdateTokenInfo() { var er ExplorerResponse err = c.ec.SendExploerJSONRequest("POST", ExplorerUpdateTokenInfoAPI, &tokensToSend, &er) if err != nil { - c.log.Error("Failed to update user info, " + err.Error()) + c.log.Error("Failed to update token info, " + err.Error()) } if !er.Status { - c.log.Error("Failed to update user info, ", "msg", er.Message) + c.log.Error("Failed to update token info, ", "msg", er.Message) return } @@ -596,7 +603,7 @@ func (ec *ExplorerClient) ExplorerRBTTransaction(et *ExplorerRBTTrans) error { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } - ec.log.Info("Transaction details for TransactionID %v is stored successfully", et.TransactionID) + ec.log.Info(fmt.Sprintf("Transaction details for TransactionID %v is stored successfully", et.TransactionID)) return nil } @@ -610,7 +617,49 @@ func (ec *ExplorerClient) ExplorerSCTransaction(et *ExplorerSCTrans) error { ec.log.Error("Failed to update explorer", "msg", er.Message) return fmt.Errorf("failed to update explorer") } - ec.log.Info("Smart contract transaction details for TransactionID %v is stored successfully", et.TransactionID) + ec.log.Info(fmt.Sprintf("Smart contract transaction details for TransactionID %v is stored successfully", et.TransactionID)) + return nil +} + +func (ec *ExplorerClient) ExplorerNFTDeploy(et *ExplorerNFTDeploy) error { + var er ExplorerResponse + err := ec.SendExploerJSONRequest("POST", ExplorerNFTTransactionAPI, et, &er) + if err != nil { + return err + } + if er.Message != "NFT transaction created successfully!" { + ec.log.Error("Failed to update explorer", "msg", er.Message) + return fmt.Errorf("failed to update explorer") + } + ec.log.Info(fmt.Sprintf("Smart contract transaction details for TransactionID %v is stored successfully", et.TransactionID)) + return nil +} + +func (ec *ExplorerClient) ExplorerNFTTransaction(et *ExplorerNFTExecute) error { + var er ExplorerResponse + err := ec.SendExploerJSONRequest("POST", ExplorerNFTTransactionAPI, et, &er) + if err != nil { + return err + } + if er.Message != "NFT transaction created successfully!" { + ec.log.Error("Failed to update explorer", "msg", er.Message) + return fmt.Errorf("failed to update explorer") + } + ec.log.Info(fmt.Sprintf("Smart contract transaction details for TransactionID %v is stored successfully", et.TransactionID)) + return nil +} + +func (ec *ExplorerClient) ExplorerFTTransaction(et *ExplorerFTTrans) error { + var er ExplorerResponse + err := ec.SendExploerJSONRequest("POST", ExplorerFTTransactionAPI, et, &er) + if err != nil { + return err + } + if er.Message != "FT transaction created successfully!" { + ec.log.Error("Failed to update explorer", "msg", er.Message) + return fmt.Errorf("failed to update explorer") + } + ec.log.Info(fmt.Sprintf("Smart contract transaction details for TransactionID %v is stored successfully", et.TransactionID)) return nil } diff --git a/core/ft.go b/core/ft.go index cbbab6ad..e7fda493 100644 --- a/core/ft.go +++ b/core/ft.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "fmt" + "log" "math" "regexp" "strconv" @@ -414,7 +415,7 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model } FTsForTxn := AllFTs[:req.FTCount] //TODO: Pinning of tokens - + rpeerid = c.w.GetPeerID(req.Receiver) if rpeerid == "" { // Check if DID is present in the DIDTable as the @@ -529,8 +530,29 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model // if explorerErr != nil { // c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) // } + AllTokens := make([]AllToken, len(FTsForTxn)) + for i := range FTsForTxn { + tokenDetail := AllToken{} + tokenDetail.TokenHash = FTsForTxn[i].TokenID + tt := c.TokenType(FTString) + blk := c.w.GetLatestTokenBlock(FTsForTxn[i].TokenID, tt) + bid, _ := blk.GetBlockID(FTsForTxn[i].TokenID) + + blockNoPart := strings.Split(bid, "-")[0] + // Convert the string part to an int + blockNoInt, err := strconv.Atoi(blockNoPart) + if err != nil { + log.Printf("Error getting BlockID: %v", err) + continue + } + tokenDetail.BlockNumber = blockNoInt + tokenDetail.BlockHash = strings.Split(bid, "-")[1] - _ = &ExplorerFTTrans{ + AllTokens[i] = tokenDetail + } + + eTrans := &ExplorerFTTrans{ + FTBlockHash: AllTokens, CreatorDID: creatorDID, SenderDID: did, ReceiverDID: rdid, @@ -552,6 +574,10 @@ func (c *Core) initiateFTTransfer(reqID string, req *model.TransferFTReq) *model resp.Message = "Failed to update FT table after transfer" return resp } + explorerErr := c.ec.ExplorerFTTransaction(eTrans) + if explorerErr != nil { + c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) + } c.log.Info("FT Transfer finished successfully", "duration", dif, " trnxid", td.TransactionID) msg := fmt.Sprintf("FT Transfer finished successfully in %v with trnxid %v", dif, td.TransactionID) resp.Status = true diff --git a/core/nft.go b/core/nft.go index dc648d09..df0d9227 100644 --- a/core/nft.go +++ b/core/nft.go @@ -228,25 +228,11 @@ func (c *Core) deployNFT(reqID string, deployReq model.DeployNFTRequest) *model. txnDetails.TotalTime = float64(dif.Milliseconds()) c.w.AddTransactionHistory(txnDetails) - //TODO : Explorer NFT update - // tokens := make([]string, 0) - // //tokens = append(tokens, deployReq.SmartContractToken) - // explorerTrans := &ExplorerTrans{ - // TID: txnDetails.TransactionID, - // DeployerDID: did, - // //Amount: deployReq.RBTAmount, - // TrasnType: conensusRequest.Type, - // TokenIDs: tokens, - // QuorumList: conensusRequest.QuorumList, - // TokenTime: float64(dif.Milliseconds()), - // //BlockHash: txnDetails.BlockID, - // } - // c.ec.ExplorerTransaction(explorerTrans) blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] // Convert the string part to an int blockNoInt, _ := strconv.Atoi(blockNoPart) //Rename : TODO - _ = &ExplorerNFTDeploy{ + eTrans := &ExplorerNFTDeploy{ NFTBlockHash: []AllToken{{TokenHash: deployReq.NFT, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, TransactionID: txnDetails.TransactionID, Network: conensusRequest.Type, @@ -258,7 +244,10 @@ func (c *Core) deployNFT(reqID string, deployReq model.DeployNFTRequest) *model. PledgeInfo: PledgeInfo{PledgeDetails: pds.PledgedTokens, PledgedTokenList: pds.TokenList}, Comments: txnDetails.Comment, } - // c.ec.ExplorerSCTransaction(eTrans) + explorerErr := c.ec.ExplorerNFTDeploy(eTrans) + if explorerErr != nil { + c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) + } c.log.Info("NFT Deployed successfully", "duration", dif) resp.Status = true @@ -425,23 +414,11 @@ func (c *Core) executeNFT(reqID string, executeReq *model.ExecuteNFTRequest) *mo txnDetails.TotalTime = float64(dif.Milliseconds()) c.w.AddTransactionHistory(txnDetails) - //TODO : Explorer NFT Update - // tokens := make([]string, 0) - // tokens = append(tokens, executeReq.NFT) - // explorerTrans := &ExplorerTrans{ - // TID: txnDetails.TransactionID, - // ExecutorDID: did, - // TrasnType: conensusRequest.Type, - // TokenIDs: tokens, - // QuorumList: conensusRequest.QuorumList, - // TokenTime: float64(dif.Milliseconds()), - // //BlockHash: txnDetails.BlockID, - // } blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] // Convert the string part to an int blockNoInt, _ := strconv.Atoi(blockNoPart) //Rename : TODO - _ = &ExplorerNFTExecute{ + eTrans := &ExplorerNFTExecute{ NFT: NFTString, ExecutorDID: currentOwner, ReceiverDID: receiver, @@ -467,7 +444,10 @@ func (c *Core) executeNFT(reqID string, executeReq *model.ExecuteNFTRequest) *mo c.log.Error("Failed to update NFT status after transferring", err) } - // c.ec.ExplorerTransaction(explorerTrans) + explorerErr := c.ec.ExplorerNFTTransaction(eTrans) + if explorerErr != nil { + c.log.Error("Failed to send FT transaction to explorer ", "err", explorerErr) + } c.log.Info("NFT Executed successfully", "duration", dif) resp.Status = true diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index fb2015c2..a215315e 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -184,7 +184,9 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCBlockHash: []AllToken{{TokenHash: deployReq.SmartContractToken, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, + SCTokenHash: deployReq.SmartContractToken, + SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], + SCBlockNumber: blockNoInt, TransactionID: txnDetails.TransactionID, Network: conensusRequest.Type, ExecutorDID: "", @@ -343,7 +345,9 @@ func (c *Core) executeSmartContractToken(reqID string, executeReq *model.Execute blockNoInt, _ := strconv.Atoi(blockNoPart) eTrans := &ExplorerSCTrans{ - SCBlockHash: []AllToken{{TokenHash: executeReq.SmartContractToken, BlockHash: strings.Split(txnDetails.BlockID, "-")[1], BlockNumber: blockNoInt}}, + SCTokenHash: executeReq.SmartContractToken, + SCBlockHash: strings.Split(txnDetails.BlockID, "-")[1], + SCBlockNumber: blockNoInt, TransactionID: txnDetails.TransactionID, Network: consensusRequest.Type, ExecutorDID: did, From 7977d50d26ec4935d27c0a7d18b255ed0a1a3941 Mon Sep 17 00:00:00 2001 From: Ashita Gupta Date: Tue, 7 Jan 2025 17:22:25 +0530 Subject: [PATCH 12/12] Updated URL and explorer fuctions --- command/command.go | 6 +- core/explorer.go | 185 +++++++++++++++--------- core/smart_contract_token_operations.go | 12 -- 3 files changed, 120 insertions(+), 83 deletions(-) diff --git a/command/command.go b/command/command.go index 1a56dc44..e5ad8ec2 100644 --- a/command/command.go +++ b/command/command.go @@ -408,8 +408,10 @@ func (cmd *Command) runApp() { go s.Start() cmd.log.Info("Syncing Details...") dids := c.ExplorerUserCreate() //Checking if all the DIDs are in the ExplorerUserDetailtable or not. - c.UpdateUserInfo(dids) //Updating the balance - c.GenerateUserAPIKey(dids) //Regenerating the API Key for DID + if len(dids) != 0 { + c.UpdateUserInfo(dids) //Updating the balance + c.GenerateUserAPIKey(dids) //Regenerating the API Key for DID + } // c.UpdateTokenInfo() cmd.log.Info("Syncing Complete...") diff --git a/core/explorer.go b/core/explorer.go index f8ca0a1b..0934e41c 100644 --- a/core/explorer.go +++ b/core/explorer.go @@ -5,6 +5,7 @@ import ( "io" "net/http" "strings" + "sync" "github.com/rubixchain/rubixgoplatform/block" "github.com/rubixchain/rubixgoplatform/core/storage" @@ -237,21 +238,19 @@ func (c *Core) InitRubixExplorer() error { return err } url := "rexplorer.azurewebsites.net" - protocol := "https" if c.testNet { - url = "98.70.52.158:8080" - protocol = "http" + url = "testnet-core-api.rubixexplorer.com" } err = c.s.Read(ExplorerURLTable, &ExplorerURL{}, "url=?", url) if err != nil { - err = c.s.Write(ExplorerURLTable, &ExplorerURL{URL: url, Port: 443, Protocol: protocol}) + err = c.s.Write(ExplorerURLTable, &ExplorerURL{URL: url, Port: 443, Protocol: "https"}) } if err != nil { return err } - cl, err := ensweb.NewClient(&config.Config{ServerAddress: url, ServerPort: "0", Production: fmt.Sprintf("%t", !c.testNet)}, c.log) + cl, err := ensweb.NewClient(&config.Config{ServerAddress: url, ServerPort: "0", Production: "true"}, c.log) if err != nil { return err } @@ -273,7 +272,7 @@ func (ec *ExplorerClient) SendExploerJSONRequest(method string, path string, inp for _, url := range urls { apiKeyForHeader := "" - if url == "https://rexplorer.azurewebsites.net" || url == "http://98.70.52.158:8080" { + if url == "https://rexplorer.azurewebsites.net" || url == "https://testnet-core-api.rubixexplorer.com" { apiKeyForHeader = ec.getAPIKey(path, input) } else { apiKeyForHeader = "" @@ -311,26 +310,53 @@ func (c *Core) ExplorerUserCreate() []string { didList := []wallet.DIDType{} dids := []string{} + //Read all DIDs from the DB. err := c.s.Read(wallet.DIDStorage, &didList, "did!=?", "") if err != nil { c.log.Error("Error reading the DID Storage or DID Storage empty") return nil } + + var wg sync.WaitGroup + var mu sync.Mutex + // Channel to collect errors + errChan := make(chan string, len(didList)) + for _, d := range didList { - eu := ExplorerUser{} - err = c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", d.DID) - if err != nil { - ed := ExplorerDID{} - ed.DID = d.DID - ed.Balance = 0 - ed.PeerID = c.peerID - ed.DIDType = d.Type - err = c.ec.ExplorerUserCreate(&ed) + wg.Add(1) + go func(d wallet.DIDType) { + defer wg.Done() + + //Checking if user already exists + eu := ExplorerUser{} + err = c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", d.DID) + if err != nil { - c.log.Error("Error creating user for did %v", d.DID) + ed := ExplorerDID{ + DID: d.DID, + Balance: 0, + PeerID: c.peerID, + DIDType: d.Type, + } + err := c.ec.ExplorerUserCreate(&ed) + if err != nil { + errChan <- fmt.Sprintf("Error creating user for DID %v: %v", d.DID, err) + return + } } - } - dids = append(dids, d.DID) + // Append to the result slice + mu.Lock() + dids = append(dids, d.DID) + mu.Unlock() + }(d) + } + // Wait for all goroutines to complete + wg.Wait() + close(errChan) + + // Log errors from the channel + for e := range errChan { + c.log.Error(e) } return dids } @@ -352,24 +378,32 @@ func (ec *ExplorerClient) ExplorerUserCreate(ed *ExplorerDID) error { func (c *Core) UpdateUserInfo(dids []string) { for _, did := range dids { - accInfo, err := c.GetAccountInfo(did) - if err != nil { - c.log.Error("Failed to get account info for DID %v", did) - continue - } - var er ExplorerResponse - ed := ExplorerDID{} - ed.PeerID = c.peerID - ed.Balance = accInfo.RBTAmount - ed.DIDType = 4 - err = c.ec.SendExploerJSONRequest("PUT", ExplorerUpdateUserInfoAPI+"/"+did, &ed, &er) - if err != nil { - c.log.Error("Failed to update user info, " + err.Error()) - } - if er.Message != "User balance updated successfully!" { - c.log.Error("Failed to update user info, ", "msg", er.Message) - } - c.log.Info(fmt.Sprintf("%v for did %v", er.Message, did)) + go func(did string) { + didList := wallet.DIDType{} + + accInfo, err := c.GetAccountInfo(did) + if err != nil { + c.log.Error("Failed to get account info for DID %v", did) + return + } + _ = c.s.Read(wallet.DIDStorage, &didList, "did=?", did) + var er ExplorerResponse + ed := ExplorerDID{ + PeerID: c.peerID, + Balance: accInfo.RBTAmount, + DIDType: didList.Type, + } + err = c.ec.SendExploerJSONRequest("PUT", ExplorerUpdateUserInfoAPI+"/"+did, &ed, &er) + if err != nil { + c.log.Error("Failed to send request for user DID, " + did + " Error : " + err.Error()) + return + } + if er.Message != "User balance updated successfully!" { + c.log.Error("Failed to update user info for ", "DID", did, "msg", er.Message) + } else { + c.log.Info(fmt.Sprintf("%v for did %v", er.Message, did)) + } + }(did) } } @@ -512,25 +546,33 @@ func (c *Core) populateTokenDetail(token wallet.Token) TokenDetails { func (c *Core) GenerateUserAPIKey(dids []string) { for _, did := range dids { - var er ExplorerUserCreateResponse - eu := ExplorerUser{} - //Read for api key in table, if empty, then regenerate, because before this, after creating the DID, we are generating the API Key - err := c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", did) - if err != nil { - c.log.Error("Failed to read table") - } - if eu.APIKey != "" { - continue - } - err = c.ec.SendExploerJSONRequest("POST", ExplorerGenerateUserKeyAPI, &eu, &er) - if err != nil { - c.log.Error(err.Error()) - } - if er.Message != "API key regenerated successfully!" { - c.log.Error("Failed to generate API Key for %v. The error msg is %v", did, er.Message) - } - c.ec.AddDIDKey(did, er.APIKey) - c.log.Info(er.Message + " for did " + did) + + go func(did string) { + var er ExplorerUserCreateResponse + eu := ExplorerUser{} + //Read for api key in table, if empty, then regenerate, because before this, after creating the DID, we are generating the API Key + err := c.s.Read(ExplorerUserDetailsTable, &eu, "did=?", did) + if err != nil { + c.log.Error(fmt.Sprintf("Failed to read table for DID %v", did)) + return + + } + if eu.APIKey != "" { + return + } + err = c.ec.SendExploerJSONRequest("POST", ExplorerGenerateUserKeyAPI, &eu, &er) + if err != nil { + c.log.Error(fmt.Sprintf("Failed to send request for DID %v: %v", did, err.Error())) + return + } + if er.Message != "API key regenerated successfully!" { + c.log.Error(fmt.Sprintf("Failed to generate API Key for %v. The error msg is %v", did, er.Message)) + return + } + c.ec.AddDIDKey(did, er.APIKey) + c.log.Info(er.Message + " for DID " + did) + + }(did) } } @@ -791,20 +833,25 @@ func (c *Core) ExpireUserAPIKey() { c.log.Error("Failed to read table for Expiring the user Key") } for _, eu := range eus { - var er ExplorerResponse - err = c.ec.SendExploerJSONRequest("POST", ExplorerExpireUserKeyAPI, &eu, &er) - if err != nil { - c.log.Error(err.Error()) - } - if er.Message != "API key expired successfully!" { - c.log.Error("Failed to expire API Key for %v. The error msg is %v", eu.DID, er.Message) - } - eu.APIKey = "" - err = c.s.Update(ExplorerUserDetailsTable, &eu, "did=?", eu.DID) - if err != nil { - c.log.Error(err.Error()) - } - c.log.Info(fmt.Sprintf("%v for DID %v", er.Message, eu.DID)) + go func(eu ExplorerUser) { + var er ExplorerResponse + err = c.ec.SendExploerJSONRequest("POST", ExplorerExpireUserKeyAPI, &eu, &er) + if err != nil { + c.log.Error(fmt.Sprintf("Failed to send request for DID %v: %v", eu.DID, err.Error())) + return + } + if er.Message != "API key expired successfully!" { + c.log.Error(fmt.Sprintf("Failed to expire API Key for %v. The error msg is %v", eu.DID, er.Message)) + return + } + eu.APIKey = "" + err = c.s.Update(ExplorerUserDetailsTable, &eu, "did=?", eu.DID) + if err != nil { + c.log.Error("Failed to update database for DID %v: %v", eu.DID, err.Error()) + return + } + c.log.Info(fmt.Sprintf("%v for DID %v", er.Message, eu.DID)) + }(eu) fmt.Println("Cleaning completed...") } } diff --git a/core/smart_contract_token_operations.go b/core/smart_contract_token_operations.go index a215315e..6ff7592c 100644 --- a/core/smart_contract_token_operations.go +++ b/core/smart_contract_token_operations.go @@ -167,18 +167,6 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma txnDetails.Amount = deployReq.RBTAmount txnDetails.TotalTime = float64(dif.Milliseconds()) c.w.AddTransactionHistory(txnDetails) - tokens := make([]string, 0) - tokens = append(tokens, deployReq.SmartContractToken) - // _ = &ExplorerTrans{ - // TID: txnDetails.TransactionID, - // DeployerDID: did, - // Amount: deployReq.RBTAmount, - // TrasnType: conensusRequest.Type, - // TokenIDs: tokens, - // QuorumList: conensusRequest.QuorumList, - // TokenTime: float64(dif.Milliseconds()), - // //BlockHash: txnDetails.BlockID, - // } blockNoPart := strings.Split(txnDetails.BlockID, "-")[0] // Convert the string part to an int blockNoInt, _ := strconv.Atoi(blockNoPart)