Skip to content

Commit

Permalink
Merge pull request #140 from rubixchain/feat/allen/pincheck
Browse files Browse the repository at this point in the history
Feat/allen/pincheck
  • Loading branch information
gklps authored Apr 24, 2024
2 parents a9b4b85 + 24e5825 commit 756b357
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 54 deletions.
2 changes: 1 addition & 1 deletion core/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ func (c *Core) migrateNode(reqID string, m *MigrateRequest, didDir string) error
continue
}
}
ok, err := c.w.Pin(t, wallet.OwnerRole, did)
ok, err := c.w.Pin(t, wallet.OwnerRole, did, "Migrated Token", "NA", "NA", float64(1))
if err != nil || !ok {
c.log.Error("Failed to migrate, failed to pin token", "err", err)
return fmt.Errorf("failed to migrate, failed to pin token")
Expand Down
4 changes: 2 additions & 2 deletions core/part_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func (c *Core) createPartToken(dc did.DIDCrypto, did string, tkn string, parts [
}
t, err := c.w.GetToken(tkn, wallet.TokenIsFree)
if err != nil || t == nil {
return nil, fmt.Errorf("failed to get token or tokne does not exist")
return nil, fmt.Errorf("failed to get token or token does not exist")
}
release := true
defer c.relaseToken(&release, tkn)
Expand Down Expand Up @@ -223,7 +223,7 @@ func (c *Core) createPartToken(dc did.DIDCrypto, did string, tkn string, parts [
rtb := rb[0].GetBlock()
td := util.HexToStr(rtb)
fr := bytes.NewBuffer([]byte(td))
pt, err := c.ipfs.Add(fr)
pt, err := c.w.Add(fr, did, wallet.AddFunc)
if err != nil {
c.log.Error("Failed to create part token, failed to add rac token to ipfs", "err", err)
return nil, err
Expand Down
6 changes: 4 additions & 2 deletions core/quorum_initiator.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type ConensusRequest struct {
DeployerPeerID string `json:"deployer_peerd_id"`
SmartContractToken string `json:"smart_contract_token"`
ExecuterPeerID string `json:"executor_peer_id"`
TransactionID string `json:"transaction_id"`
}

type ConensusReply struct {
Expand Down Expand Up @@ -269,6 +270,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc
//getting last character from TID
tid := util.HexToStr(util.CalculateHash(sc.GetBlock(), "SHA3-256"))
lastCharTID := string(tid[len(tid)-1])
cr.TransactionID = tid

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 {
Expand Down Expand Up @@ -381,7 +383,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc
c.log.Debug("String: token is ", token, " issuetype is ", issueType)
issueTypeInt, err1 := strconv.Atoi(issueType)
if err1 != nil {
errMsg := fmt.Sprintf("Consensus failed due to token chain sync issue, issueType string conversion, err %v", err1)
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)
}
Expand All @@ -397,7 +399,7 @@ func (c *Core) initiateConsensus(cr *ConensusRequest, sc *contract.Contract, dc
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, errors.New(br.Message)
}
}
if !br.Status {
Expand Down
38 changes: 20 additions & 18 deletions core/quorum_recv.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (c *Core) quorumRBTConsensus(req *ensweb.Request, did string, qdc didcrypto

// check token ownership

validateTokenOwnershipVar, err := c.validateTokenOwnership(cr, sc)
validateTokenOwnershipVar, err := c.validateTokenOwnership(cr, sc, did)
if err != nil {
validateTokenOwnershipErrorString := fmt.Sprint(err)
if strings.Contains(validateTokenOwnershipErrorString, "parent token is not in burnt stage") {
Expand Down Expand Up @@ -195,7 +195,9 @@ func (c *Core) quorumRBTConsensus(req *ensweb.Request, did string, qdc didcrypto
c.log.Debug("Token", tokenStateCheckResult[i].Token, "Message", tokenStateCheckResult[i].Message)
}
c.log.Debug("Proceeding to pin token state to prevent double spend")
err1 := c.pinTokenState(tokenStateCheckResult, did)
sender := cr.SenderPeerID + "." + sc.GetSenderDID()
receiver := cr.ReceiverPeerID + "." + sc.GetReceiverDID()
err1 := c.pinTokenState(tokenStateCheckResult, did, cr.TransactionID, sender, receiver, float64(0))
if err1 != nil {
crep.Message = "Error Pinning token state" + err.Error()
return c.l.RenderJSON(req, &crep, http.StatusOK)
Expand Down Expand Up @@ -308,7 +310,7 @@ func (c *Core) quorumNFTSaleConsensus(req *ensweb.Request, did string, qdc didcr
}
}
// check token ownership
validateTokenOwnershipVar, err := c.validateTokenOwnership(cr, sc)
validateTokenOwnershipVar, err := c.validateTokenOwnership(cr, sc, did)
if err != nil {
validateTokenOwnershipErrorString := fmt.Sprint(err)
if strings.Contains(validateTokenOwnershipErrorString, "parent token is not in burnt stage") {
Expand Down Expand Up @@ -357,23 +359,23 @@ func (c *Core) quorumNFTSaleConsensus(req *ensweb.Request, did string, qdc didcr
return c.l.RenderJSON(req, &crep, http.StatusOK)
}

func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc didcrypto.DIDCrypto, conensusRequest *ConensusRequest) *ensweb.Result {
func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc didcrypto.DIDCrypto, consensusRequest *ConensusRequest) *ensweb.Result {
consensusReply := ConensusReply{
ReqID: conensusRequest.ReqID,
ReqID: consensusRequest.ReqID,
Status: false,
}
if conensusRequest.ContractBlock == nil {
if consensusRequest.ContractBlock == nil {
c.log.Error("contract block in consensus req is nil")
consensusReply.Message = "contract block in consensus req is nil"
return c.l.RenderJSON(req, &consensusReply, http.StatusOK)
}
consensusContract := contract.InitContract(conensusRequest.ContractBlock, nil)
consensusContract := contract.InitContract(consensusRequest.ContractBlock, nil)
// setup the did to verify the signature
c.log.Debug("VEryfying the deployer signature")

var verifyDID string

if conensusRequest.Mode == SmartContractDeployMode {
if consensusRequest.Mode == SmartContractDeployMode {
c.log.Debug("Fetching Deployer DID")
verifyDID = consensusContract.GetDeployerDID()
c.log.Debug("deployer did ", verifyDID)
Expand All @@ -400,12 +402,12 @@ func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc

var tokenStateCheckResult []TokenStateCheckResult
var wg sync.WaitGroup
if conensusRequest.Mode == SmartContractDeployMode {
if consensusRequest.Mode == SmartContractDeployMode {
//if deployment
commitedTokenInfo := consensusContract.GetCommitedTokensInfo()
//1. check commited token authenticity
c.log.Debug("validation 1 - Authenticity of commited RBT tokens")
validateTokenOwnershipVar, err := c.validateTokenOwnership(conensusRequest, consensusContract)
validateTokenOwnershipVar, err := c.validateTokenOwnership(consensusRequest, consensusContract, did)
if err != nil {
validateTokenOwnershipErrorString := fmt.Sprint(err)
if strings.Contains(validateTokenOwnershipErrorString, "parent token is not in burnt stage") {
Expand All @@ -426,7 +428,7 @@ func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc
results := make([]MultiPinCheckRes, len(commitedTokenInfo))
for i := range commitedTokenInfo {
wg.Add(1)
go c.pinCheck(commitedTokenInfo[i].Token, i, conensusRequest.DeployerPeerID, "", results, &wg)
go c.pinCheck(commitedTokenInfo[i].Token, i, consensusRequest.DeployerPeerID, "", results, &wg)
}
wg.Wait()
for i := range results {
Expand All @@ -447,12 +449,12 @@ func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc
for i, ti := range commitedTokenInfo {
t := ti.Token
wg.Add(1)
go c.checkTokenState(t, did, i, tokenStateCheckResult, &wg, conensusRequest.QuorumList, ti.TokenType)
go c.checkTokenState(t, did, i, tokenStateCheckResult, &wg, consensusRequest.QuorumList, ti.TokenType)
}
wg.Wait()
} else {
//sync the smartcontract tokenchain
address := conensusRequest.ExecuterPeerID + "." + consensusContract.GetExecutorDID()
address := consensusRequest.ExecuterPeerID + "." + consensusContract.GetExecutorDID()
peerConn, err := c.getPeer(address)
if err != nil {
c.log.Error("Failed to get executor peer to sync smart contract token chain", "err", err)
Expand All @@ -472,7 +474,7 @@ func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc
return c.l.RenderJSON(req, &consensusReply, http.StatusOK)
}
wg.Add(1)
go c.checkTokenState(t, did, i, tokenStateCheckResult, &wg, conensusRequest.QuorumList, ti.TokenType)
go c.checkTokenState(t, did, i, tokenStateCheckResult, &wg, consensusRequest.QuorumList, ti.TokenType)
}
wg.Wait()
}
Expand All @@ -491,7 +493,7 @@ func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc
}

c.log.Debug("Proceeding to pin token state to prevent double spend")
err = c.pinTokenState(tokenStateCheckResult, did)
err = c.pinTokenState(tokenStateCheckResult, did, consensusRequest.TransactionID, "NA", "NA", float64(0)) // TODO: Ensure that smart contract trnx id and things are proper
if err != nil {
consensusReply.Message = "Error Pinning token state" + err.Error()
return c.l.RenderJSON(req, &consensusReply, http.StatusOK)
Expand All @@ -507,7 +509,7 @@ func (c *Core) quorumSmartContractConsensus(req *ensweb.Request, did string, qdc
}

consensusReply.Status = true
consensusReply.Message = "Conensus finished successfully"
consensusReply.Message = "Consensus finished successfully"
consensusReply.ShareSig = qsb
consensusReply.PrivSig = ppb
return c.l.RenderJSON(req, &consensusReply, http.StatusOK)
Expand Down Expand Up @@ -750,8 +752,8 @@ func (c *Core) updateReceiverToken(req *ensweb.Request) *ensweb.Result {
}
c.log.Debug("Token", tokenStateCheckResult[i].Token, "Message", tokenStateCheckResult[i].Message)
}

err = c.w.TokensReceived(did, sr.TokenInfo, b)
senderPeerId, _, _ := util.ParseAddress(sr.Address)
err = c.w.TokensReceived(did, sr.TokenInfo, b, senderPeerId, c.peerID)
if err != nil {
c.log.Error("Failed to update token status", "err", err)
crep.Message = "Failed to update token status"
Expand Down
15 changes: 11 additions & 4 deletions core/quorum_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,18 @@ func (c *Core) syncParentToken(p *ipfsport.Peer, pt string) error {
return nil
}

func (c *Core) validateTokenOwnership(cr *ConensusRequest, sc *contract.Contract) (bool, error) {
func (c *Core) validateTokenOwnership(cr *ConensusRequest, sc *contract.Contract, quorumDID string) (bool, error) {

var ti []contract.TokenInfo
var address string
var receiverAddress string
if cr.Mode == SmartContractDeployMode {
ti = sc.GetCommitedTokensInfo()
address = cr.DeployerPeerID + "." + sc.GetDeployerDID()
} else {
ti = sc.GetTransTokenInfo()
address = cr.SenderPeerID + "." + sc.GetSenderDID()
receiverAddress = cr.ReceiverPeerID + "." + sc.GetReceiverDID()
}
for i := range ti {
ids, err := c.GetDHTddrs(ti[i].Token)
Expand Down Expand Up @@ -175,6 +177,11 @@ func (c *Core) validateTokenOwnership(cr *ConensusRequest, sc *contract.Contract
c.log.Error("failed to sync parent token chain", "token", pt)
return false, err
}
_, err = c.w.Pin(pt, wallet.ParentTokenPinByQuorumRole, quorumDID, cr.TransactionID, address, receiverAddress, ti[i].TokenValue)
if err != nil {
c.log.Error("Failed to Pin parent token in Quorum", "err", err)
return false, err
}
}

// Check the token validation
Expand Down Expand Up @@ -393,17 +400,17 @@ func (c *Core) checkTokenState(tokenId, did string, index int, resultArray []Tok
resultArray[index] = result
}

func (c *Core) pinTokenState(tokenStateCheckResult []TokenStateCheckResult, did string) error {
func (c *Core) pinTokenState(tokenStateCheckResult []TokenStateCheckResult, did string, transactionId string, sender string, receiver string, tokenValue float64) error {
var ids []string
for i := range tokenStateCheckResult {
tokenIDTokenStateBuffer := bytes.NewBuffer([]byte(tokenStateCheckResult[i].tokenIDTokenStateData))
tokenIDTokenStateHash, err := c.w.Add(tokenIDTokenStateBuffer, did, wallet.QuorumRole)
tokenIDTokenStateHash, err := c.w.Add(tokenIDTokenStateBuffer, did, wallet.QuorumPinRole)
if err != nil {
c.log.Error("Error triggered while adding token state", err)
return err
}
ids = append(ids, tokenIDTokenStateHash)
_, err = c.w.Pin(tokenIDTokenStateHash, wallet.QuorumRole, did)
_, err = c.w.Pin(tokenIDTokenStateHash, wallet.QuorumPinRole, did, transactionId, sender, receiver, tokenValue)
if err != nil {
c.log.Error("Error triggered while pinning token state", err)
c.unPinTokenState(ids, did)
Expand Down
2 changes: 1 addition & 1 deletion core/smart_contract_token_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (c *Core) deploySmartContractToken(reqID string, deployReq *model.DeploySma
defer c.w.ReleaseTokens(rbtTokensToCommitDetails)

for i := range rbtTokensToCommitDetails {
c.w.Pin(rbtTokensToCommitDetails[i].TokenID, wallet.OwnerRole, did)
c.w.Pin(rbtTokensToCommitDetails[i].TokenID, wallet.OwnerRole, did, "NA", "NA", "NA", float64(0)) //TODO: Ensure whether trnxId should be added ?
rbtTokensToCommit = append(rbtTokensToCommit, rbtTokensToCommitDetails[i].TokenID)
}

Expand Down
6 changes: 3 additions & 3 deletions core/transfer.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest)
}

if req.TokenCount < MinTrnxAmt {
resp.Message = "Input transaction amount is less than minimum transcation amount"
resp.Message = "Input transaction amount is less than minimum transaction amount"
return resp
}

decimalPlaces := strconv.FormatFloat(req.TokenCount, 'f', -1, 64)
decimalPlacesStr := strings.Split(decimalPlaces, ".")
if len(decimalPlacesStr) == 2 && len(decimalPlacesStr[1]) > MaxDecimalPlaces {
c.log.Error("Transcation amount exceeds %d decimal places.\n", MaxDecimalPlaces)
c.log.Error("Transaction amount exceeds %d decimal places.\n", MaxDecimalPlaces)
resp.Message = fmt.Sprintf("Transaction amount exceeds %d decimal places.\n", MaxDecimalPlaces)
return resp
}
Expand Down Expand Up @@ -127,7 +127,7 @@ func (c *Core) initiateRBTTransfer(reqID string, req *model.RBTTransferRequest)
defer c.w.ReleaseTokens(tokensForTxn)

for i := range tokensForTxn {
c.w.Pin(tokensForTxn[i].TokenID, wallet.OwnerRole, did)
c.w.Pin(tokensForTxn[i].TokenID, wallet.OwnerRole, did, "TID-Not Generated", req.Sender, req.Receiver, tokensForTxn[i].TokenValue)
}

// Get the receiver & do sanity check
Expand Down
19 changes: 13 additions & 6 deletions core/wallet/ipfs_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@ const (
DIDRole
StakingRole
PledgingRole
QuorumPinRole
QuorumUnpinRole
ParentTokenPinByQuorumRole
)

// modified pin method that pins token and update in DB with role of the machine pinning
func (w *Wallet) Pin(hash string, role int, did string) (bool, error) {
func (w *Wallet) Pin(hash string, role int, did string, transactionId string, sender string, receiver string, tokenValue float64) (bool, error) {
w.ipfs.Pin(hash)
err := w.AddProviderDetails(hash, did, PinFunc, role)
err := w.AddProviderDetails(TokenProviderMap{Token: hash, Role: role, DID: did, FuncID: PinFunc, TransactionID: transactionId, Sender: sender, Receiver: receiver, TokenValue: tokenValue})
if err != nil {
w.log.Info("Error addding provider details to DB", "error", err)
return false, err
Expand Down Expand Up @@ -57,7 +60,7 @@ func (w *Wallet) Cat(hash string, role int, did string) (string, error) {
w.log.Error("Error formatting ipfs content", "error", err)
return "", err
}
err1 := w.AddProviderDetails(hash, did, CatFunc, role)
err1 := w.AddProviderDetails(TokenProviderMap{Token: hash, Role: role, DID: did, FuncID: CatFunc})
if err1 != nil {
w.log.Info("Error addding provider details to DB", "error", err)
return "", err
Expand All @@ -71,7 +74,7 @@ func (w *Wallet) Get(hash string, did string, role int, path string) error {
w.log.Error("Error while getting file from ipfs", "error", err)
return err
}
err = w.AddProviderDetails(hash, did, GetFunc, role)
err = w.AddProviderDetails(TokenProviderMap{Token: hash, Role: role, DID: did, FuncID: GetFunc})
return err
}

Expand All @@ -81,6 +84,10 @@ func (w *Wallet) Add(r io.Reader, did string, role int) (string, error) {
w.log.Error("Error adding file to ipfs", "error", err)
return "", err
}
err = w.AddProviderDetails(result, did, AddFunc, role)
return result, nil
err = w.AddProviderDetails(TokenProviderMap{Token: result, Role: role, DID: did, FuncID: AddFunc})
if err != nil {
w.log.Error("Error adding provider details", "error", err)
return "", err
}
return result, err
}
30 changes: 15 additions & 15 deletions core/wallet/provider_details.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ package wallet

// struct definition for Mapping token and reason the did is a provider
type TokenProviderMap struct {
Token string `gorm:"column:token;primaryKey"`
DID string `gorm:"column:did"`
FuncID int `gorm:"column:func_id"`
Role int `gorm:"column:role"`
Token string `gorm:"column:token;primaryKey"`
DID string `gorm:"column:did"`
FuncID int `gorm:"column:func_id"`
Role int `gorm:"column:role"`
TransactionID string `gorm:"column:transaction_id"`
Sender string `gorm:"column:sender"`
Receiver string `gorm:"column:receiver"`
TokenValue float64 `gorm:"column:token_value"`
}

// Method takes token hash as input and returns the Provider details
Expand All @@ -26,20 +30,16 @@ func (w *Wallet) GetProviderDetails(token string) (*TokenProviderMap, error) {

// Method to add provider details to DB during ipfs ops
// checks if entry exist for token,did either write or updates
func (w *Wallet) AddProviderDetails(token string, did string, funId int, role int) error {

func (w *Wallet) AddProviderDetails(tokenProviderMap TokenProviderMap) error {
var tpm TokenProviderMap
err := w.s.Read(TokenProvider, &tpm, "token=?", token)
err := w.s.Read(TokenProvider, &tpm, "token=?", tokenProviderMap.Token)
if err != nil || tpm.Token == "" {
tpm.Token = token
tpm.DID = did
tpm.FuncID = funId
tpm.Role = role
return w.s.Write(TokenProvider, &tpm)
w.log.Info("Token Details not found: Creating new Record")
// create new entry
return w.s.Write(TokenProvider, tokenProviderMap)
}
tpm.DID = did
tpm.FuncID = funId
tpm.Role = role
return w.s.Update(TokenProvider, &tpm, "token=?", token)
return w.s.Update(TokenProvider, tokenProviderMap, "token=?", tokenProviderMap.Token)
}

// Method deletes entry ffrom DB during unpin op
Expand Down
Loading

0 comments on commit 756b357

Please sign in to comment.