我可以将对象传递给 Hyperledger Fabric 事务吗?

Can I pass objects to a Hyperledger Fabric transaction?

我有一个基于原始示例 fabcar example. Customized the chaincode and the folder structure, and it all seems to compile and fire up just fine. But now, I am trying to find out whether I can use function Contract.submitTransaction() (found in invoke.ts and covered in the docs) or a more applicable function to pass somewhat more complex arguments for custom type Shipment which is based on type Car 的网络设置。在示例中,Car 只是 string 的平面类型,您可以简单地将其传递给 Contract.submitTransaction(),它只接受字符串参数,如下所示:

await contract.submitTransaction('createCar', 'CAR12', 'Honda', 'Accord', 'Black', 'Tom');

对于由多个 "sub-types" 组成的类型 Shipment,这会变得有点困难:

import { TransitStatusEnum } from "../enum/transitstatusenum";
import { FreightContainer } from "./freightcontainer";
import { Company } from "./company";

export class Shipment {
    public docType?: string;
    public id: string;
    public status: TransitStatusEnum;
    public containers: FreightContainer[];
    public shipper?: Company;
    private totalShipmentValue?: number = 0;

    constructor() {
        if (!this.containers) {
            console.log("Shipment does not (yet) contain any containers, shipmentValue is 0");            
            return;
        }

        for (let container of this.containers) {
            this.totalShipmentValue += container.transitAgreement.cargoValue;
        }
    }
}

下面是 Contract.submitTransaction() 应该调用的函数,而不是 CreateCar():

public async createShipment(ctx: Context, id: string, status: TransitStatusEnum, shipper: Company, containers?: FreightContainer[]) {
    console.info('============= START : Create Shipment ===========');

    const shipment: Shipment = {
        docType: 'shipment',
        id,
        status,
        containers,
        shipper
    };

    await ctx.stub.putState(id, Buffer.from(JSON.stringify(shipment)));
    console.info('============= END : Create Shipment ===========');
}

我可以为这些自定义类型创建工厂,并根据 string 值生成类型,而不是传递给 createShipment() 的类型,或者传递一个字符串化对象(objects/arrays,更多 objects/arrays)。但我想知道(尤其是后者,这让我不寒而栗)是否真的有必要。 docs 只提到这个 Contract.submitTransaction() 函数作为向区块链提交交易的一种方式。

我应该使用出厂解决方案吗?我可以使用其他功能来使用类型提交交易吗?或者这不是我构建链代码的方式,我应该考虑完全简化它吗?

Hyperledger Fabric 支持的每种语言的对象都不同。例如,有适用于 JavaScript (Node.js)、Java、Go 和 Python 的 SDK。此外,链代码本身可以用 JavaScript、Java 或 Go.

编写

为了保持语言中立,参数的内部表示只是一个字节数组,它在 protobuf specification which Fabric uses for internal communication. Fabric SDKs also tend to toss in a conversion to a string definition. Your only option is to work with bytes or strings. You could use your own custom parsing or for more advanced use, you could use some type of serialization protocol (see comparison) 中定义。但是,您的应用程序和链代码都需要支持它。

当您需要发送对象时,我建议为您的情况创建一个链代码函数,例如 createShipment,它接受构造对象所需的尽可能多的参数。如果对象本身包含一个对象数组 (FreightContainer),您可以将其注册为一个对象本身 (createFreightContainer),它包含 Shipment.

的 ID