Hyperledger Fabric smart contract data model: protobuf to chaincode state mapping

How specifying world state data model with protocol buffers can help in developing smart contracts

Viktor Nosov
Feb 20, 2019 · 7 min read

Chaincode is a domain-specific program that relates to specific business process. It programmatically accesses two distinct pieces of the ledger — a blockchain, which immutably records the history of all transactions and a world state that holds a cache of the current value of these states. The job of a smart contract developer is to take an existing business process that might govern financial prices or delivery conditions and express it as a smart contract in a programming language. Protobuf (short for Protocol buffers) are the language-neutral, platform-neutral, extensible mechanism for serializing structured data. Using protocol buffers can help to define data model once and then easily write and read structured data to and from a variety of data sources.

Discover and review best Blockchain softwares

Chaincode state

The ledger’s current state data represents the latest values for all keys ever included in the chain transaction log. Since current state represents all latest key values known to the channel, it is sometimes referred to as World State.

Chaincode invocations execute transactions against the current state data. To make these chaincode interactions extremely efficient, the latest values of all keys are stored in a state database.

Smart contracts primarily put, get and delete states in the world state, and can also query the state change history. Chaincode “shim” APIs implements ChaincodeStubInterface which contain methods for access and modify the ledger, and to make invocations between chaincodes. Main methods are:

* GetState(key string) ([]byte, error) performs a query to retrieve information about the current state of a object

* PutState(key string, value []byte) error creates a new object or modifies an existing one in the ledger world state

* DelState(key string) error removes an object from the current state of the ledger, but not its history

* GetStateByPartialCompositeKey(objectType string, keys []string) (StateQueryIteratorInterface, error)queries the state in the ledger based on given partial composite key

* GetHistoryForKey(key string) (HistoryQueryIteratorInterface, error)returns a history of key values across time.

All this methods use string key as record identifier and slice of bytes as state value. Most of examples use serialized to bytes JSON documents as chaincode state value. Hyperledger Fabric supports both LevelDB as CouchDB to serve as state database, holding the latest state of each object. LevelDB is the default key-value state database embedded in every peer. CouchDB is an optional alternative external state database with more features — it supports rich queries against JSON documents in chaincode state, whereas LevelDB only supports queries against keys.

As shown in many examples, assets can be represented as complex structures — Golang structs , which are required to be marshalled to JSON string
before putting into chaincode state and unmarshalled after receiving from state.

With ChaincodeStubInterface methods these operations can looks like
this:

In the example above smart contract code explicitly performs many auxiliary actions:

  • Creating composite key
  • Unmarshalling data after receiving it from state
  • Marshalling data before placing it to state

Chaincode state operations with CCKit

CCKit, library for creating and testing Hyperledger Fabric golang chaincode, contains wrapper on ChaincodeStubInteface methods to working with chaincode state. This methods simplifies chaincode key creation and data transformation during work with chaincode state.

State wrapper allows to automatically marshal golang type to/from slice of bytes. This type can be:

Golang structs automatically marshals/ unmarshals using json.Marshal and
and json.Umarshal methods. proto.Marshal and proto.Unmarshal are used to convert protobuf.

In the chaincode data model we often need to store many instances of one type on the ledger, such as multiple commercial papers, letters of credit, and so on. In this case, the unique key of those instances will be typically constructed from a combination of attributes, for example:

`CommercialPaper` + {Issuer} + {PaperId}

yielding series of chaincode state entries keys

[ `CommercialPaperIssuer1Id1`, `CommercialPaperIssuer2Id2`, …]

The logic of creation primary key of an instance can be customized in the code, constructing a composite key of an instance based on a combination of several attributes. Composite keys can then be used as a normal string key to
record and retrieve values using the PutState() and GetState() functions.

The following snippet shows a list of functions that create and work with composite keys in ChaincodeStubInterface:

When putting or getting data to/from chaincode state you must provide key. CCKit have 3 options for dealing with entries key:

  • Key can be passed explicit to Put method
c.State().Put ( `my-key`, &myStructInstance)
  • Key type can implement Keyer interface
  • Key can be of Key type — is essentially slice of string, this slice will be automatically converted to string using shim.CreateCompositeKey method.

and in chaincode you need to provide only type instance, key will be created automatically:

c.State().Put (&myStructInstance)
  • Entry type can have associate mapping

Mapping defines rules for namespace (prefix for key), primary and other uniq and non uniq keys for an entity. Mapping mainly used with protobuf state schema.

As well as retrieving assets with a unique key, ChaincodeStubInterface offers functions the opportunity to retrieve sets of assets based on a range criteria.
Moreover, composite keys can be constructed to enable queries against multiple components of the key.

The range functions return an iterator StateQueryIteratorInterface over a set of keys matching the query criteria. The returned keys are in lexical order.
Additionally, when a composite key has multiple attributes, the range query function, GetStateByPartialCompositeKey(), can be used to search for keys matching a subset of the attributes.

For example, the key of a CommercialPaper composed of Issuer and PaperId attributes, entries can be searched only from one Issuer.

Protobuf state model example

CCKit protocol buffers example use Commercial paper scenario and
implements same functionality as Node.JS chaincode sample from official documentation. Protobuf is a way of encoding structured data in an efficient and extensible format.

  1. Schema abstraction layer

Encoding the semantics of your business objects once, in .proto format, is enough to help ensure that the message doesn’t get lost between applications,
and that the boundaries you create enforce your business rules.

2. Extensions — validators etc

Protobuf v3 does not support validating required parameters, but there are third party projects for proto validation, for example
https://github.com/mwitkow/go-proto-validators. It allows to encode, at the schema level, the shape of your data structure, and the validation rules.

3. Easy Language Interoperability
Because Protocol Buffers are implemented in a variety of languages, they make interoperability between polyglot applications in your architecture that much simpler. If you’re introducing a new service using Java Fabric SDK or Node.Js Fabric SDK you simply have to hand the .proto file to the code generator written in the target language and you have guarantees about the safety and interoperability between those architectures.

With protocol buffers, you write a .proto description of the data structure you wish to store. From that, the protocol buffer compiler creates a golang struct that implements automatic encoding and parsing of the protocol buffer data with an efficient binary format (or json). The generated class provides getters and setters for the fields that make up a protocol buffer and takes care of the details of reading and writing the protocol buffer as a unit.

In Commercial Paper example first we define messages, that will be stored in chaincode state or used as events:

  • CommercialPaper will be stored in chaincode state
  • CommercialPaperId defines unique id part of commercial paper message
  • IssueCommercialPaper payload for issue transaction and event triggered when new commercial paper issued
  • BuyCommercialPaper payload for buy transaction and event triggered when commercial paper change owner
  • RedeemCommercialPaper payload for redeem transaction and event triggered when commercial paper redeemed

Protocol buffers message to chaincode mapper can be used to store schema instances in chaincode state. Every schema type (protobuf or struct) can have mapping rules:

  • Primary key creation logic
  • Namespace logic
  • Secondary key creation logic

In chaincode we simply use generated from .proto files structures, chaincode state creation predefined in mappings. Chaincode implementation use CCKit routing and middleware features to structure the code.

We can test all chaincode use case scenarios using MockStub:

More about chaincode unit testing and test driven development you can read here:

https://medium.com/coinmonks/test-driven-hyperledger-fabric-golang-chaincode-development-dbec4cb78049

Chaincode also can be implemented as service with IDL specification. This allows to automatically generate SDK, REST API, swagger specification and documentation for chaincode

https://medium.com/coinmonks/service-oriented-hyperledger-fabric-application-development-32e66f578f9a

Get Best Software Deals Directly In Your Inbox

Coinmonks

Coinmonks is a non-profit Crypto educational publication.

Coinmonks

Coinmonks is a non-profit Crypto educational publication. Follow us on Twitter @coinmonks Our other project — https://coincodecap.com

Viktor Nosov

Written by

S7 Airlines, S7 Techlab, Blockchain R&D, https://github.com/vitiko

Coinmonks

Coinmonks is a non-profit Crypto educational publication. Follow us on Twitter @coinmonks Our other project — https://coincodecap.com

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store