Hyperledger面料:查询隐式数据收集

发布于 2025-01-27 09:06:01 字数 3677 浏览 3 评论 0原文

从隐式私有数据收集中查询数据时,我会看到这一点。 请参阅下面的代码段。

当我查询单个键(使用querybidprivate/getPrivatedAta )时,我会获得相应的数据。 但是,如果我查询完整的集合(使用getprivatedatabyrange(collection,“”,“,“”)),我从迭代器中却一无所获。

对等链码查询-C myChannel -n govtoncontract -c'{“ function”:“ querybidprivate”,“ args”:[“ 100”,“ 1035”]}'' {“ bidamt”:100,“ biddate”:“ 2022-05-04”,“ consctionId”:“ 1035”,“盐”:“ 4567AB4567”,“ vendorid”,“ vendorid”:“ 100”}

c myChannel -n govtoncontract -c'{“ function”:“ listallbids”,“ args”:[]}'

无输出

我在这里缺少什么?

// ListAllBids returns all Bids details from private state
func (s *SmartContract) ListAllBids(ctx contractapi.TransactionContextInterface) ([]VendorBid, error) {
 
        // Get client org id and verify it matches peer org id.
        // In this scenario, client is only authorized to read/write private data from its own peer.
        clientOrgID, err := getClientOrgID(ctx, true)
        if err != nil {
                return nil, fmt.Errorf("failed to get verified OrgID: %s", err.Error())
        }
 
        collection := "_implicit_org_" + clientOrgID
 
        BidIterator, err := ctx.GetStub().GetPrivateDataByRange(collection, "", "")
        if err != nil {
                logger.Infof("ListAllBids error: %s", err.Error())
                return nil, fmt.Errorf("failed to read bid list : %s", err.Error())
        }
        if BidIterator == nil {
                logger.Infof("ListAllBids : null iterator ")
                return nil, fmt.Errorf("bid private details does not exist ")
        }
        defer BidIterator.Close()
        logger.Infof("ListAllBids in govtcontract: no error")
 
        var allbids []VendorBid
        myMSPID, err := ctx.GetClientIdentity().GetMSPID()
        logger.Infof("myMSPID: %s", myMSPID)
        for BidIterator.HasNext() {
                logger.Infof("Iterator has element: ")
 
                entrybid, err := BidIterator.Next()
                if err != nil {
                        return nil, err
                }
 
                var bidvar VendorBid
                err = json.Unmarshal(entrybid.Value, &bidvar)
                if err != nil {
                        return nil, err
                }
 
                allbids = append(allbids, bidvar)
                logger.Infof("Iterator element: %s", entrybid.Value)
 
        }
        
 
        return allbids, nil
 
}

=========================================

// QueryBidPrivate returns the Bid details from owner's private data collection
func (s *SmartContract) QueryBidPrivate(ctx contractapi.TransactionContextInterface, vendorId string, contractId string) (string, error) {
 
        // Get client org id and verify it matches peer org id.
        // In this scenario, client is only authorized to read/write private data from its own peer.
        clientOrgID, err := getClientOrgID(ctx, true)
        if err != nil {
                return "", fmt.Errorf("failed to get verified OrgID: %s", err.Error())
        }
 
        collection := "_implicit_org_" + clientOrgID
 
        bidconkey, err := ctx.GetStub().CreateCompositeKey(vendorId, []string{contractId})
 
        bidDetails, err := ctx.GetStub().GetPrivateData(collection, bidconkey)
        if err != nil {
                return "", fmt.Errorf("failed to read bid private properties from client org's collection: %s", err.Error())
        }
        if bidDetails == nil {
                return "", fmt.Errorf("bid private details does not exist in client org's collection: %s", contractId)
        }
 
        return string(bidDetails), nil
}

I am seeing this when querying data from implicit private data collection.
Please see code snippet below.

When I query individual key (using QueryBidPrivate/GetPrivateData), I get corresponding data.
But if I query the complete collection (using GetPrivateDataByRange(collection, "", "")), I get nothing from the Iterator.

peer chaincode query -C mychannel -n govtcontract -c '{"function":"QueryBidPrivate","Args":["100", "1035"]}'
{"bidamt":100,"biddate":"2022-05-04","contractid":"1035","salt":"4567ab4567","vendorid":"100"}

peer chaincode query -C mychannel -n govtcontract -c '{"function":"ListAllBids","Args":[]}'

No output

Is there anything I am missing here ?

// ListAllBids returns all Bids details from private state
func (s *SmartContract) ListAllBids(ctx contractapi.TransactionContextInterface) ([]VendorBid, error) {
 
        // Get client org id and verify it matches peer org id.
        // In this scenario, client is only authorized to read/write private data from its own peer.
        clientOrgID, err := getClientOrgID(ctx, true)
        if err != nil {
                return nil, fmt.Errorf("failed to get verified OrgID: %s", err.Error())
        }
 
        collection := "_implicit_org_" + clientOrgID
 
        BidIterator, err := ctx.GetStub().GetPrivateDataByRange(collection, "", "")
        if err != nil {
                logger.Infof("ListAllBids error: %s", err.Error())
                return nil, fmt.Errorf("failed to read bid list : %s", err.Error())
        }
        if BidIterator == nil {
                logger.Infof("ListAllBids : null iterator ")
                return nil, fmt.Errorf("bid private details does not exist ")
        }
        defer BidIterator.Close()
        logger.Infof("ListAllBids in govtcontract: no error")
 
        var allbids []VendorBid
        myMSPID, err := ctx.GetClientIdentity().GetMSPID()
        logger.Infof("myMSPID: %s", myMSPID)
        for BidIterator.HasNext() {
                logger.Infof("Iterator has element: ")
 
                entrybid, err := BidIterator.Next()
                if err != nil {
                        return nil, err
                }
 
                var bidvar VendorBid
                err = json.Unmarshal(entrybid.Value, &bidvar)
                if err != nil {
                        return nil, err
                }
 
                allbids = append(allbids, bidvar)
                logger.Infof("Iterator element: %s", entrybid.Value)
 
        }
        
 
        return allbids, nil
 
}

=========================================

// QueryBidPrivate returns the Bid details from owner's private data collection
func (s *SmartContract) QueryBidPrivate(ctx contractapi.TransactionContextInterface, vendorId string, contractId string) (string, error) {
 
        // Get client org id and verify it matches peer org id.
        // In this scenario, client is only authorized to read/write private data from its own peer.
        clientOrgID, err := getClientOrgID(ctx, true)
        if err != nil {
                return "", fmt.Errorf("failed to get verified OrgID: %s", err.Error())
        }
 
        collection := "_implicit_org_" + clientOrgID
 
        bidconkey, err := ctx.GetStub().CreateCompositeKey(vendorId, []string{contractId})
 
        bidDetails, err := ctx.GetStub().GetPrivateData(collection, bidconkey)
        if err != nil {
                return "", fmt.Errorf("failed to read bid private properties from client org's collection: %s", err.Error())
        }
        if bidDetails == nil {
                return "", fmt.Errorf("bid private details does not exist in client org's collection: %s", contractId)
        }
 
        return string(bidDetails), nil
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜深人未静 2025-02-03 09:06:01

getPrivatedAtabyPartialCompositeKey()是查询使用复合键存储的一系列私有数据的功能。 GetPrivatedAtabyRange()不会检索使用复合键存储的数据。我认为在上面的代码段中,您必须替换函数调用getPrivatedAtabyrange(collection,“”,“”,“”) getPrivatedAtabyPartialCompositeKey(Collection,collection,vendorid,[] string {] string {})

可以找到示例用法< positekey“ rel =” nofollow noreferrer“>在这里。

GetPrivateDataByPartialCompositeKey() is the function for querying a range of private data that was stored using a composite key. GetPrivateDataByRange() won't retrieve the data stored with a composite key. I think in the above code snippet you have to replace the function call GetPrivateDataByRange(collection, "", "") with GetPrivateDataByPartialCompositeKey(collection, vendorId, []string{})

Sample usage can be found here.

帅哥哥的热头脑 2025-02-03 09:06:01

我在智能合约中遇到了相同的错误。此处的问题是因为将数据存储在复合密钥上。
而不是以下代码:

  for Biditerator.hasnext(){
            logger.infof(“迭代器具有元素:”)

            entrybid,err:= biditerator.next()
            如果err!= nil {
                    返回零,错误
            }

            var bidvar供应商
            err = json.unmarshal(entrybid.value,&amp; bidvar)
            如果err!= nil {
                    返回零,错误
            }

            allbids = append(allbids,bidvar)
            logger.infof(“迭代元素:%s”,entrybid.value)

    }
 

使用以下功能

    func constructQueryResponseFromIterator(resultsIterator    shim.StateQueryIteratorInterface) 

(*bytes.buffer,错误)
{

// buffer is a JSON array containing QueryResults
var buffer bytes.Buffer
buffer.WriteString("[")

bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
    queryResponse, err := resultsIterator.Next()
    if err != nil {
        return nil, err
    }
    // Add a comma before array members, suppress it for the first array member
    if bArrayMemberAlreadyWritten == true {
        buffer.WriteString(",")
    }
    buffer.WriteString("{")
    //buffer.WriteString("{\"Key\":")
    //buffer.WriteString("\"")
    //buffer.WriteString(queryResponse.Key)
    //buffer.WriteString("\"")

    buffer.WriteString(", \"Record\":")
    // Record is a JSON object, so we write as-is
    buffer.WriteString(string(queryResponse.Value))
    buffer.WriteString("}")
    bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")

return &buffer, nil

}

I faced the same error in the smart contract. The issue here is because of storing data on the composite key.
Instead of below code :

         for BidIterator.HasNext() {
            logger.Infof("Iterator has element: ")

            entrybid, err := BidIterator.Next()
            if err != nil {
                    return nil, err
            }

            var bidvar VendorBid
            err = json.Unmarshal(entrybid.Value, &bidvar)
            if err != nil {
                    return nil, err
            }

            allbids = append(allbids, bidvar)
            logger.Infof("Iterator element: %s", entrybid.Value)

    }

Use the below function

    func constructQueryResponseFromIterator(resultsIterator    shim.StateQueryIteratorInterface) 

(*bytes.Buffer, error)
{

// buffer is a JSON array containing QueryResults
var buffer bytes.Buffer
buffer.WriteString("[")

bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
    queryResponse, err := resultsIterator.Next()
    if err != nil {
        return nil, err
    }
    // Add a comma before array members, suppress it for the first array member
    if bArrayMemberAlreadyWritten == true {
        buffer.WriteString(",")
    }
    buffer.WriteString("{")
    //buffer.WriteString("{\"Key\":")
    //buffer.WriteString("\"")
    //buffer.WriteString(queryResponse.Key)
    //buffer.WriteString("\"")

    buffer.WriteString(", \"Record\":")
    // Record is a JSON object, so we write as-is
    buffer.WriteString(string(queryResponse.Value))
    buffer.WriteString("}")
    bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")

return &buffer, nil

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文