Single Blog Title

Between hype and world improvement

10 Jul 2019

Anyone who has been dealing with blockchains in the business environment in recent months knows this: Smart Contracts are almost like magical problem solvers, from the automated billing of solar power and other goods deliveries, to the independent triggering of contract penalties in closely monitored areas such as the agreed maximum temperatures of a cold chain. The potential applications are versatile, and they even seem endless. But how much of it is true and how much is just hype? And above all: What is the actual technology behind it?

On the Technical Background of Smart Contracts

To understand the role of smart contracts, we must first briefly take a look into what a blockchain actually is. On the lowest content-related level, it is a list of signed statements by individual participants. These statements cannot be technically changed or deleted at a later date. In practice, machine-readable transactions are used for this, which, much like a transaction log of a database, determine the current actual state of all data throughout the entire system. Just like a database, each individual node in a blockchain network saves the current actual state in a second format, which makes querying easier.

So far so good. But why would we use a blockchain instead of a replicated database? The short answer lies in the timing of the rule check (both on a technical and business level) and in the error handling. Compared to a database, this timing is pushed forward in a block chain and is carried out early on when the transaction is being recorded, rather than later during replication. That is precisely the job of smart contracts, which run distributed in a blockchain network.

An application suited for blockchain would be the porting of telephone numbers between mobile service providers. An excerpt from this process provides us deeper insight into the underlying processes: Put in simple terms, a central database in Germany maps the assignment of telephone numbers to the respective underlying mobile network operator. What would you need to do if you wanted to manage this information and the underlying processes locally in a blockchain network instead?

Example telephone number porting: the network

For the present case application, it makes sense to establish a private block chain network as an implementation platform. Unlike in a public network, such as Ethereum, access to a private network is allowed only to selected participants. In our example, both the German Federal Network Agency and the larger mobile operators would be participants in the private blockchain network. Each participant operates a complete node in the blockchain network. Smaller providers who do not want incur this expense would use the service by connecting to one of these network participants.

The technical platform for such a private blockchain network could be built on open source tools like Hyperledger Fabric [1] or Parity [2] (an Ethereum derivative), for example. Both infrastructure variants can run in a proof-of-authority configuration. This consensus algorithm works differently than the well-known CPU-intensive proof-of-work mining algorithms that Bitcoin uses, for example. For more information about these algorithms, refer to the “Proof-of-Work, Mining, Consensus and Co.” box.

Proof-of-Work, Mining, Consensus and Co.

All blockchain platforms have a so-called consensus procedure. This technical procedure determines how a network participant recognizes whether or not a transaction (or several such transactions combined in a block) is valid. The most important criterion typically defined there is the selection of the node responsible for generating the next block. This cannot and should not always be the same node, as otherwise the node could assume sole control over the blockchain. Therefore, a rule must be defined that determines a node from a pool of participants.

The best-known consensus procedures are based on a so-called proof-of-work mechanism. It is currently used by Bitcoin or public Ethereum networks, for example. All participating nodes (often also referred to as “miners”) try to solve a cryptographic puzzle. The idea behind this is that all participants are randomly and alternately selected in proportion to their investment (hardware and power consumption) as creators of a block. Since these networks have horrendous (and ecologically barely viable) energy consumption, many projects have been developing alternative procedures in parallel for several years. A promising procedure for public networks is currently the so-called proof-of-stake procedure. Each node deposits monetary collateral that determines the likelihood that it will be selected as the generator of the next block. If a node attempts to misuse its current position to gain control over the blockchain data (for example, through defective blocks), a part of its collateral will be automatically collected (or destroyed, which will also increase the value of the remaining currency for all participants increase in the same ratio).

These two approaches to consensus are often used in public networks where participants do not know each other. Private blockchain networks in the form most commonly encountered in the business environment usually do not need these, because the participants know each other and are typically subject to “real” contracts. Blockchain participants prove their identity to each other by using accepted cryptographic signatures. This type of procedure is often called the proof-of-authority. If a participant behaves improperly (and tries to attack the network), they can automatically be excluded from the network by removing their certificate of trust. Conversely we can say that in the business use of blockchains, there is usually no need to waste CPU cycles and power through mining.

 

 

The authorizations to participate in our example blockchain could ideally be managed by a legitimated body. In the case of telephone number porting, the German Federal Network Agency would be the best option. In other setups where cooperation in a network is voluntary, often democratic or economically motivated decision-making processes play a role in the admission of new participants. The initiators of a closed block chain can independently determine which method is preferred for the granting or deletion of access authorizations. In the case of the tools presented, such decisions can be incorporated into code or configuration information.

 

Transactions and Smart Contracts

In the case of the telephone number assignment example, three types of transactions can be identified in terms of smart contracts (in a very simplified perspective):

 

  • The German Federal Network Agency makes an initial assignment to a provider for a telephone number assigned for the first time.
  • In the process of porting, the new mobile network operator requests a transfer of a number from the previous provider.
  • The previous mobile operator confirms the porting of a number to the new provider or rejects it following information and confirmation by the contracting party.

 

To solve this process in a classic sense using a replicated database, the operator of the database would typically separate the read and write logic. The former would run on replicated read-only duplicates at the respective mobile service provider. All change processes would be handled centrally (e.g. via a web service), which would then write and distribute corresponding transaction logs so that each participant can update its read-only duplicate.

If we were to try – even without blockchains – to reduce the dependency on this central location by allowing multiple sites (or even all participants involved!) to write directly into the database, the question of securing data integrity would quickly surface. How is compliance with the agreed rules checked? Finally, it would be fatal if the code run by a participant would (intentionally or unintentionally), for example, remap the phone numbers of all participants without further security checks.

Smart Contracts: the acceptance rules of a blockchain

Therefore, most blockchain implementations do not allow the creation and replication of the chain of signed statements discussed above so easily, but rather link their execution to specific code in advance of a transaction, which is automatically executed on each node. This code is the smart contract. In most blockchains, the smart contracts has three responsibilities: (1) the examination of a transaction before execution, (2) the construction of the actual view of the data (or of the “world states”) after the transaction and (3) the possible triggering of further transactions. Simply put, the smart contract implements that part of the business logic that is shared among the participants.

In our example of telephone number porting, the smart contract could offer four functions that match the use cases defined above. Each of these functions would be called by the user through a corresponding block chain transaction.

Depending on the blockchain base technology chosen, the smart contracts also enclose the read logic in the respective world state of the smart contract. It should be noted that these methods should only be conducive for convenient read access. Under no circumstances should these read logics include the authorization check for individual reading rights of individual participants. This data has already been replicated by all blockchain participants and therefore basically visible. If such visibility is not desired, encryption or the partial use of point-to-point transmission methods can restrict data distribution accordingly. Some blockchains offer basic tools for this.

Step by step

But let’s go back to the smart contracts. For the examples presented in this article, I will use Solidity – the contracts are therefore executable on any Ethereum derivative for both public and private blockchains. However, the concepts presented can also be applied to most other blockchains. The reason I chose Solidity is the availability of easy-to-use development tools: For example, the Remix [3] open-source development environment provides a way to locally develop, test, and debug Solidity code without the need to connect to a real blockchain network.

As a first step, we need to define a data model that defines the actual state of the smart contract data. Expressed in simplified terms, this basic state in our example case includes the following three aspects:

 

  • Determining the identity of the regulator – in this case the German Federal Network Agency. Transactions sent from there also have the authorization to associate a telephone number with an operator for the first time.
  • Definition of a key/value assignment, comparable to a dictionary, This association allows the identification of the current operator’s identity for each registered telephone number.
  • Definition of another key/value assignment that records the identity of the porting destination (the new mobile operator) for each telephone number currently in a porting.

 

(by the way: the data structure described above is, of course, a great simplification. To make this article more readable, I have allowed myself to disregard some aspects that would also be indispensable in practice. Thus, for example, I have not defined a list of permitted identities (each participant in this network could therefore make up as many mobile operators as they want), nor are escalation processes or time limits taken into account during porting. However, the underlying considerations and technologies allow for easy extension using these parameters.)

The addressed “identities” are each technology-specific sender addresses. In practice, these are all values that correspond to the public key from an asymmetric key pair. This means that by examining the cryptographic signature of a transaction, you can determine which identity this transaction was signed for. This allows us to make sure that, for example, only the mobile phone operator currently responsible for a telephone number may change their data record.

So let’s first take a look at Listing 1 for the base code of our Smart Contract, which implements the data model outlined above.

 

Listing 1

contract PhoneNumberTransfer {

mapping(string => address) allPhoneNumbers;

mapping(string => address) requestedTransfers;

address regulator;

 

constructor() public {regulator = msg.sender;}

}

 

 

The conceptual persistence model of Solidity is relatively simple: All member fields of a smart contract are automatically stored in their persistent world state. In this case, this affects the fields allPhoneNumbers. requestedTransfer and regulator,

The constructor in this code snippet uses another peculiarity of Ethereum derivatives: A smart contract is installed on the network by making its compiled bytecode known to the network with a special block chain transaction. This blockchain transaction (like any other transaction) has a sender, which can be evaluated and stored using msg.sender. As a first step, before a participant of our number porting network could use the smart contract, the network agency would have to send this installation transaction to the network once. In response, the sender then receives an address that references the instance of the smart contract just generated. All further transactions (from all participants) are sent in succession to this concrete instance address.

As I mentioned above, this is a technical peculiarity of blockchain networks based on Ethereum. In networks based on other basic technologies, the installation of smart contracts can look a bit differently. Depending on the platform selected, such as Hyperledger Fabric, for example – the identity of the regulator may also need to be explicitly communicated to the contract, with a one-time function call after installation. (an Ethereum implementation such as Parity behaves similarly to Hyperledger Fabric, much like Microsoft SQL Server behaves like MongoDB: both are manifestations of a technology concept – “database” or “blockchain” – but are interpreted and implemented in completely different ways).

The function of initially assigning a telephone number to a provider could be implemented as shown in Listing 2.

 

Listing 2

contract PhoneNumberTransfer {

 

/* ... as above ... */

 

function createAndAssignNumber(uint phoneNumber, address to) public {

require(regulator == msg.sender);

require(allPhoneNumbers[phoneNumber] == 0);

allPhoneNumbers[phoneNumber] = to;

}

}

 

 

The createAndAssignNumbers function specified in this fragment receives two parameters: the telephone number and the identity of a mobile service provider (in the form of an Ethereum address, as described above) to which the telephone number is to be assigned. The code first checks whether the sender of the transaction is the same as the regulator, because in our example, only the regulator has the authorization to initially create and assign a telephone number. The require function in Solidity leads to the equivalent of an Exception, such that if the condition is not met, the system immediately stops processing the rest of the transaction code and marks it as bad. Then by accessing allPhoneNumbers [phone number], we check whether the desired telephone number has already been assigned. This access to a mapping is defined in Solidity such that unfilled entries are returned as 0. Otherwise, in the last line, we simply assign the address passed as a parameter to the transferred telephone number. Since in transaction processing in a block chain, an absolute time sequence of the individual transactions is fixed by their position in a block, we do not have to pay attention here to simultaneous write access by other transactions.

For the second transaction type – the desire to port a number – we proceed analogously. Such a call would be sent to the network by the new mobile operator and could be performed as shown in Listing 3.

 

Listing 3

function requestTransfer(uint phoneNumber) public {

// Number must exist and be assigned

require(allPhoneNumbers[phoneNumber] != 0);

// Number may not already be assigned to the requestor

require(allPhoneNumbers[phoneNumber] != msg.sender);

// number may not already be in a porting process

require(requestedTransfers[phoneNumber] == 0);

 

requestedTransfers[phoneNumber] = msg.sender;

}

 

 

Again, the code of the smart contract first checks the two entry conditions and, after a positive check, changes the data in the world state to record who had requested the porting of the given number. Typically, the last line of the Smart Contract would now have a notification event (for example, a event in solidity) to which each mobile operator is subscribed using its own program code in its blockchain node. Thus, the smart contract starts the local (blockchain-independent) processing of the porting in the existing backend systems of a participant as soon as another operator requests the porting of a number from its area of influence.

After the mobile service provider to which this number is currently assigned completes its internal check of the porting and has validated the correctness of the porting itself (e.g. through the informed consent of the customer by SMS), it can respond to the query with another transaction. The smart contract code of this transaction could in simplified form look like Listing 4.

 

Listing 4

function confirmTransfer(uint phoneNumber) public  {

// Make sure the number should be ported at all

address destination = requestedTransfers[phoneNumber];

require (destination != 0);

 

// Number must currently be assigned to the sender of the transaction

require (allPhoneNumbers[phoneNumber] == msg.sender);

 

// Update the assignment for the number

allPhoneNumbers [phoneNumber] = destination;

// Delete the open transfer

delete requestedTransfers[phoneNumber];

}

 

 

You can design the rejection of a transfer in a similar manner.♠ Here the difference lies in the fact that the assignment of the telephone number is not updated, but only the porting request will be removed from requestedTransfers. In either case, at the end of the function you would trigger an event again so that the affected counterpart is informed without having to constantly monitor every single transaction of the blockchain.

Why exactly is it all secure?

So far so good. But what about the security of this approach? What would happen if one of the participants simply exchanged the smart contract on the blockchain node controlled by him or her and used a variant that was more advantageous to the participant? (incidentally, depending on the blockchain, the attacker would have to dive relatively deep into the internals of the blockchain platform implementation – but it is still a valid attack vector, which we must at least consider on a theoretical level.)

In our example, an attacker could try to take control of all phone numbers by changing the test conditions in his or her version of the smart contract. But that would mean that the world state is changed only on the node of the attacker: The attacker is the only participant that has the impression of having control over all phone numbers. All other participants would continue to execute the correct version of the contract. If, due to the chosen consensus mechanism between the participants, the attacker is selected by the network itself to generate new blocks, they would immediately be rejected by the other participants. The attacker would lose the status of the block generator again because depending on the configuration of the blockchain, half or two-thirds of all participants must agree to the outcome of a transaction before it is considered correct across the network. Any attack attempt therefore hurts the attacker directly.

It is therefore possible to compare this attack with a situation in which a bank customer crosses out the balance on his or her printed bank statement and writes a higher total. From his or her viewpoint, there is much more money in the account than before. But as soon as this customer tries to access this money, he or she is very quickly brought back to reality: their own view is nothing but wishful thinking, which will be acknowledged by counterparts at best with a chuckle.

How is a smart contract called up?

Having seen how a smart contract is defined technically and knowing that it can trigger events that external (non-blockchain) systems can handle, one last piece of the puzzle is missing: How is the smart contract actually called up?

There are corresponding SDKs in JavaScript, .NET and/or Java for most blockchain platforms. These SDKs allow us to create, sign, and submit transactions to our own nodes or third-party nodes of the blockchain network.

For Ethereum derivatives, a smart contract is called as follows: First, the method name and method arguments are converted to a defined binary format. To do this, helper methods are provided by the SDK that can process the interface description (ABI – Application Binary Interface) of the smart contract and generate the corresponding binary data. Thereafter, a transaction is created using the address created in the instantiation of the smart contract described above as the destination address. This entire operation can either be performed explicitly by the client code in individual steps, or – as shown in Listing 5 – it can look like a normal function call through automatically generated methods. In the listing, we see that we are using the relevant part of the call of the request transfer contract method presented above, the web3.js [4] – the JavaScript SDK for Ethereum.

 

Listing 5

// Contract object is generated on the basis of the ABI and an example destination address

let abi = JSON.parse(fs.readFileSync("demoContract.abi"));

let address = "0xFe363D7030Db8E93517bB6315165B68AC4387DE8";

let demoContract = new web3.eth.Contract(abi, address);

 

// In the background, the method call is translated into an Ethereum transaction, signed with a configured (and explicitly released in advance) default identity, and sent to the network.

let numberToTransfer = "491511234567";

demoContract.methods.requestTransfer(numberToTransfer)

.send({/* Optionen */})

.then(function (receipt) {

// ... further processing

});

 

Smart contracts and cryptocurrencies

We’ve seen that smart contracts are simply a way to run program code distributed across a network to achieve the data integrity guaranteed by each blockchain platform. But how does that fit with the hype in the IoT area (such as automatic cold chain monitoring with penalty payments mentioned in the introduction)? In such cases, smart contracts consistently take on management of the monetary units (cryptocurrencies). For example, a refrigerated container to be transported from Singapore to Amsterdam could be instantiated with a smart contract that implements the monitoring of the maximum allowable temperature fluctuation range (guaranteed by the logistics company) and at the same time an automatic penalty payment system in case of deviations. The contract could be designed such that an IoT sensor reports the temperature to the smart contract hourly during the entire transport time and a deviation from the agreed temperature range immediately provides for another Blockchain transaction to transfer an agreement currency as a penalty payment. Blockchain networks which manage the automatic handling of decentralized electricity deliveries, also have similar combinations of IoT sensors with smart contracts in the background. (basically, the term “smart contract” is based on such concrete preliminary agreements, which do not require any manual or even legal tracking and are implemented in a purely technical and automated manner.)

The really interesting and new thing about blockchains is that they allow us to create completely decentralized structures. Network participants no longer have to agree on a central, trustworthy site, but only on the content of the smart contracts. These then run in the blockchain network in a decentralized manner. The hope is that not only in the logistics sector, but in all market sectors, market participants will be able to implement digitization processes without restricting their autonomy by having to choose a central processing body (possibly a pool of competitors from the same sector).

And personally, I think that is extremely exciting.

 

Links & literature

[1] https://www.hyperledger.org/projects/fabric

[2] https://paritytech.io/ethereum/

[3] https://remix.ethereum.org/

[4] https://github.com/ethereum/web3.js/

STAY TUNED!

BEHIND THE TRACKS

Blockchain Advanced Development

Advanced step-by-step technical guide: Sharing the know-how

Blockchain Impact & Strategy

Experimenting with blockchain technology: Real-world inspiring use cases

Blockchain Technology 101

Principles, tools–frameworks & libraries–and implementation