Ethereum Usecase: Identity Management (Take 2)

Identity verification is one of the hottest usecases for the blockchain. I already wrote on this topic few months ago with the idea of a fictive government binding hashed identity data to citizen’s ethereum address.

Recently, I ran into ShoCard, a mobile app which is able to locally store user’s identities (driver’s license, passport, tickets, credits cards, online accounts, …) on the mobile phone and seal this data by putting the hashes via the BlockCypher API on the blockchain. Furthermore, institutions, like banks for instance, can verify user’s identities and store this fact on blockchain too, effectively confirming that the sealed id record is correct.

I did the experiment of implementing ShoCard’s concept on the Ethereum blockchain. A very interesting point is that we only need one simple contract for the implementation of the concept. It simply binds a hash value to an address:

contract DataSeal {
address owner;
uint256 dataHash;
function DataSeal(uint256 _dataHash) {
owner = msg.sender;
dataHash = _dataHash;
}
}

First, for every user’s identity record of the form

idRecord = {idData_1, ..., idData_n, randomValue} 

we create in Ethereum a DataSeal instance storing idRecord‘s hash value.

idRecordSeal = new DataSeal(<idRecord hash>)

From now on, idRecord can not be modified without breaking idRecordSeal.

If we want to prove to X that our idRecord has been sealed by us, we will send to X the idRecordSeal address and idRecord signed with the private key of the Ethereum account used to instantiate idRecordSeal. Having this informaton, X can verify that idRecord matches the hash value in idRecordSeal contract and that the signature matches its owner.

So far, we have the proof that idRecord was created and sealed by us, but we have no proof yet that idRecord matches our real identity as documented on our id card. For instance, we could steal the id card from someone else and  seal it on the blockchain. In order to make the idRecord trustworthy, we need a trustworthy witness verifying our idRecord and committing the proof to the blockchain.

The most direct witness for this proof would be the public authority issuing the id cards to the citizens. The next best instance, could be a commonly accepted institution like the mailing company (see POSTIDENT solution of Deutsche Post AG) or a bank.

If the user has been successfully authenticated, the witness will produce

witnessRecord = {idRecordSeal, secretKey}

and create a new instance of the DataSeal contract with the hash of it:

witnessRecordSeal = new DataSeal(<witnessRecord hash>)

Finally the witness shares the following record with the user:

{witnessPublicAddress, witnessRecordSeal, secretKey}

Assuming that X is trusting W, and that we already were authenticated by W, we can pass to X

  1. the witness data {witnessPublicAddress, witnessRecordSeal, secretKey}
  2. our idRecord signed with the corresponding private key
  3. our idRecordSeal address

Now X, can check that idRecord hasn’t been modified, that we’re the owner of the record and it’s blockchain seal, and that we already were successfully authenticated by W. If X trusts W, then he doesn’t need any further verification of our identity and he can do business with us.

The concept is universal and it works with any kind of document. There are also usecases where no witness is needed at all. For instance I can seal my credit card data like this:

creditCardDataSeal = new DataSeal(<hashed credit card data>)

Every time I purchase something, I also sign my purchase with my Ethereum private key and the merchant can verify that credit card data is in my ownership. So even if someone steals my credit card, he won’t be able to purchase something with it, because the thief can not prove he’s the owner of the credit card.

Static Type Safety for DApps without JavaScript

DApps, starting professionally…

You might not be aware, but despite its similarities to JavaScript, Solidity is actually a statically, strongly typed language, more similar to Java than to JavaScript.

solidity
static type check in browsersolidity

…and ending in frontend-chaos

Sadly, for a long time, there has only be one interface to Ethereum nodes, web3.js (besides JSON/RPC), which is, as its name implies, written in JavaScript.

Though providing this API in a web-native language is really a brilliant idea in terms of fast development, seperation of concerns and ease of use, it is a nightmare for professional, multi-developer, multi-year, enterprise products.

You may not agree with me here, but as there are currently no 10 year old 1.000.000 LoC enterprise projects in node.js/JavaScript out there, you should at least consider that such projects are nearly impossible to maintain with a dynamically, weakly typed language like JavaScript (JS).

So, we have this situation, where JS defines the lowest common denominator (dynamically, weakly typed

JavaScript_1 (2)

when we really would like to have this situation, where Java (C#, Haskell) defines the lowest common denominator (statically, strongly typed)

JavaScript_2 (2)

Removing chaos

The problem is was, that up to now only web3.js existed. However, today there is also a web3.py (which is Python and therefore at least strongly typed, but still dynamically) and, brandnew, web3j.

With the latter, we can easily model the call chain above, where we only use statically, strongly typed Java and omit JavaScript altogether. Welcome to hassle-free integration into existing Java/JEE-environments without workarounds. Finally: using the Ethereum Blockchain with Java.

If you want to actually get deeper and use Java with no RPC at all, you can also switch to EthereumJ, which is a Ethereum Node implemented in Java, like Eth (C++), Geth (Go), PyEthApp (Python) or Parity (Rust). It is crucial to understand the difference between web3j and EthereumJ. If you just want to use some Ethereum Node from a Java application, web3j is your choice, you are limited to the Web DApp API then, which should be enough for all “Ethereum user” use cases.

We will not explain in detail how to use web3j, it should be familiar to any Java developer how this library can be used just by adding Maven-dependencies to your project.

Fixing the front-end

We could stop here, since using JavaScript for the frontend is not really problematic and a common use today.

However, if you use JavaScript in your frontend, it might really make more sense to stay with web3.js. So, we want to go further: how are we going to create the GUI if we want to have no JavaScript at all?

This is just a PoC, but if you think of any other client to the Ethereum Blockchain other than a web site (let’s say: Batchjobs, Web Services, Message Queues, Databases, other proprietary software with Java adapters (there are some!)), this should make sense to you – you really wouldn’t want to use them from web3.js (hopefully).

Using templates: Thymeleaf and Spring Boot for slim enterprisy software

We will do a step-by-step guide for creating a No-JS-Dapp. Even without any Java experience, you will be able to follow without problems. Java is not that complicated anymore!

  • Get an infura.io account and key, so you don’t have to mess around with starting your own Ethereum node
  • Clone this repo: https://hellokoding.com/spring-boot-hello-world-example-with-thymeleaf/
  • Install Maven
  • Edit these files:

    pom.xml (add these dependency to section dependencies and add the repo, beware that web3j is a fast moving target, check for new versions)

    <dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>0.2.0</version>
    </dependency>

 

<repositories>
<repository>
<id>oss.jfrog.org</id>
<url>http://dl.bintray.com/web3j/maven</url>
</repository>
</repositories>

src/main/resources/templates/hello.html (change name to balance.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Your Static Strongly Typed Wallet</title>
</head>
<body>
<p th:text="'The balance of account ' + ${address} + ' is ' + ${balance}" />
</body>
</html>

src/main/java/com/hellokoding/springboot/HelloController.java (change name to EthereumController.java)

@Controller
public class EthereumController {

@RequestMapping("/balance")
public String balance(Model model, @RequestParam(value="address", required=false, defaultValue="0xe1f0a3D696031E1F8ae7823581BB38C600aFF2BE") String address) throws IOException {
Web3j web3 = Web3j.build(new HttpService("https://consensysnet.infura.io/{YOUR_INFURA_KEY}"));
EthGetBalance web3ClientVersion = web3.ethGetBalance(address, DefaultBlockParameter.valueOf("latest")).send();
String balance = web3ClientVersion.getBalance().toString();
model.addAttribute("address", address);
model.addAttribute("balance", balance);
return "balance";
}

}

…that’s it. Start with mvn spring-boot:run

If you encounter an connection/handshake error, you may have to import the infura certificate into your local Java keystore (I didn’t have to)

$JAVA_HOME/Contents/Home/jre/bin/keytool -import -noprompt -trustcacerts -alias morden.infura.io -file ~/Downloads/morden.infura.io -keystore $JAVA_HOME/Contents/Home/jre/lib/security/cacerts -storepass changeit

Look Ma! Displaying the wallet balance with no JavaScript!

You can call the spring-boot web application with http://localhost:8080/balance (then the defined default argument is used) or with your address (in the consensys testnet) as parameter address= 

walletOf course, you can change the Ethereum net like you want in file EthereumController to morden or mainnet, just read the welcome mail from infura.io. Or you can just use a local Ethereum node like geth with RPC enabled (geth –rpc) and http://localhost:8545 as the constructor for HttpService of the Web3j-Factory in EthereumController.

Have fun, with or without JavaScript!

KW 33.16 – Weekly Blockchainers Recap

The number of blockchain news post is growing exponentially. Nearly every company or government does some research projects based on blockchain and DLT technologies. Let’s try to filter the stuff wich could be interesting for us blockchainers.  

Last year I saw a well written paper from the world economy forum about fintechs. This year they published “The future of financial infrastructure” witch focused on blockchain. The paper describes in detail a set of financial use  cases and how they can be improved using blockchain tech. It’s one of the best papers we have seen so far. 

The next big thing is Raiden from Heiko Hees. See also International Business Timer. Every time you discuss the opportunities of blockchain and smart contracts with business people, very soon they come up with the scalability issue. Based on my IT project experience, I can tell that there is always a solution for every performance issue. Heiko’s Raiden is the solution for Ethereum.

Finally we have to mention Steem – a blockchain database that supports community building and social interaction with cryptocurrency rewards. You can think of it as Facebook/Reddit like Plattform where content contributors and content curators are monetary rewarded for their work. It is questionable if the model is sustainable or not, anyway it’s the first application of the DLT tech with a nice front-end and with the potential to go viral. 

Distributing Business Processes using Finite State Machines in the Blockchain

Having disctinct, even competing organisations with a common goal and no shared technical infrastructure represent a perfect use case pattern for blockchain usage.

The quest for the holy business use case

As many blockchain enthusiasts we are constantly searching for use cases for establishing Distributed Ledger Technology (DLT) or even real blockchain technology in enterprises as solutions for common business problems.

21666276190_40647d8327_z
[Business *]

This turns out to be difficult, since each single aspect of this technology is already solved by several – established and well known – products. 

In this post we will present a use case, or even a use case pattern, which we think is ubiquitous and can best be solved by blockchain technology.

For these type of use cases the other technologies, even though being more mature, seem themselves like workarounds for the natural technological solution, which is blockchain-based.

Our definition is the use case pattern is:

Several distinct, competing organisations have a common goal and don't share technical infrastructure.

distinct, even competing organisations

Distinct organisations are not related to each other and therefore have no existing technical or organisational processes. To pursue a common goal, these processes would have to be established first, which is costly and time-consuming.

5882566863_ce0ccf745d_z
[Competing teams *]

The second aspect, competition, implies that there is no mutual trust. Obviously, this aspect is a crucial one. Blockchain technology might even make sense if just the other aspects of the pattern match, but it only is a perfect fit if this aspect is important, since the blockchain itself is inherently trust-less.

common goal

This is the fundamental requirement, if there is no common goal, there is no need to establish any collaboration. It is important to note, that the common goal is most likely not related to the core competence of the organisations, but to some crosscutting concerns, which have to be addressed by all organisations, but are just cost factors.

no existing shared technical infrastructure

To put it contrary: if there already exists a shared technical infrastructure, also organisational processes exist to establish new technology. Given this, there are several great technology products which implement each aspect of the blockchain technology (namely distributed data storage, immutability, security), and most likely even more performant, more mature, with less maintenance and evident responsibilities.

Ok, this is quite abstract and complex, let’s find an easy example.

…want a securities account with your new account?

There is one universal retail bank, FriendlyBank, which wants people to open accounts. And there are three deposit banks, FriendlyDeposit, EasyDeposit and NiceDeposit. There is also the Regulator, who must be able to audit all transactions between the parties.

Requirement

common goal: make money

The common goal of universal and deposit banks is to open accounts. The universal bank can be intermediary to deposit account opening, so you can open a securities account at one of the three deposit banks with your new account at FriendlyBank. This way, it is a win-win-situation for both parties, the intermediary gets commissions, the deposit banks get new customers.

FriendlyBank and FriendlyDeposit are related to each other, they have the same ownership structure, but are separated entities. Since the deposit banks are in competition with each other, the other deposit banks besides FriendlyBank want to be sure that not very valuable customers are transferred to FriendlyDeposit or the deposit account opening is “accidentally forgotten”, if not FriendlyDeposit is chosen.
Since the parties do not really trust each other, a trust-less (ie. no trust necessary) solution is needed.

the wonderful world of finance IT today

As we said, the depicted scenario exists quite often. Also, technical “solutions” for these scenarios exist.

They look similar to this one:

Flatfilesolution_crop

We wan’t go in detail what all this means, but to become trust-less, as well as assure that the data is in sync in each organisation, a lot has to be implemented and still, shortcomings of these solutions are quite common:

  • reconciliation processes are always necessary, but still, due to missing transaction support in flat file exchange, which is almost always chosen as the “simplest” integration pattern, errors occur.
  • adapters have to be built for each party, so there will soon exist a many-to-many problem.
  • special adapters have to be built for regulators.
  • crosscutting concerns have to be implemented: security, authentication, auditing, transaction support

Compared to a natural solution in the blockchain

Below is the blockchain solution, it fits naturally and implements all requirements.bcsample

Abstracting from the use case

Why is this solution matching so well, what is the pattern “behind”?

Different actors change the state of a business process on some event in a transactional way.

2645030_8e2b2269
[Old cigarette machine *]

You certainly know this pattern, it is describing a finite state machine, more exactly a distributed, secured by cryptoeconomics finite state machine, which events are transactions.

After all, the blockchain itself is a state transition system, it somes quite naturally to implement a simple state machine on the Ethereum EVM, it even is mentioned as a common pattern in the Solidity docs.

 

Approaching the finite state machine

How would the organisations collaborate? This could look like this informally:

 

process_v1

or like this (more) formally:

Blockchainsolution_FSM

so we actually can built this state machine and its transitions really easy using the blockchain, here in pseudo-Solidity, derived from the common pattern in the Solidity docs:

contract AccountDepositStateMachine {
enum Stages { Init, AccountOpened, DepositOpened, DepositConfirmed, AccountConfirmed } Stages public stage = Stages.Init; modifier atStage(Stages _stage) { if (stage != _stage) throw; _ } function nextStage() internal { stage = Stages(uint(stage) + 1); } // Order of the modifiers matters here! function openAccount() atStage(Stages.Init)
transitionNext
{ if (msg.sender != FRIENDLY_BANK) throw; } function openDeposit() atStage(Stages.AccountOpened)
transitionNext
{
if (msg.sender != FRIENDLY_BANK) throw;
}
function confirmDeposit()
atStage(Stages.DepositOpened)
transitionNext
{
if (msg.sender != DEPOSIT_BANK) throw;
}
modifier transitionNext() { _ nextStage(); } }

Great, so that’s it, we can build any business process using the blockchain, QED.

Leaving the ivory tower

As you might guess, it is not that simple. Let’s review the actual process:

  1. Account is opened 
  2. Deposit Account is opened
  3. Deposit Confirmed
  4. Account Confirmed

Ever saw an IT-process in real life? Exactly, it’s not like this, not even close. Let’s see a more real life example:

  1. Account is opened
  2. An Email is send to whoever feels responsible
  3. The Product Owner’s Excel has to be updated
  4. The new reporting engine must have its data updated, it is runnig with MongoDB, which has to be updated
  5. Revision wants to have it’s auditing data in their Oracle DB (must use 2PC)
  6. … (ok, you got it already…)

None of the tasks in bold red can be accomplished from the Ethereum blockchain, since calls from “inside” to “outside” are prohibited. Let’s hope this will never change, the separation of “inside” and “outside” is essential for the stability and security of the Ethereum blockchain

We could use Oracles for this, but it would be a kind of usage which is highly inappropriate for this type of external information retrieval.

Teaser: “Mastering the Flow: Blending Reality with the Blockchain”

This post is way too long already, so here comes a teaser for two posts next to come: “Mastering the Flow: Blending Reality with the Blockchain”

The idea is really simple: let’s just recentralize the business process (we are in eager anticipation for the comments to come…)

But we think this can make sense. Look at the sample above, illustrated as a flow:

nodered

The flow was created with Node-RED, an excellent and highly undervalued tool of IBM Emerging Technologies for flows in IoT. It could be very easily adapted to Ethereum with smart contract access by usage of web3.js, which itself can be integrated in node.js, which is the basis of Node-RED, hence the name.

We make the following assertion:

More than 80% of all use cases can be realized by a centralized business process engine as a first layer, eg. implemented in Node-RED, and a state machine implemented in the blockchain as a second layer

The business process engine is the glue between the transactional blockchain state transitions and the secondary business processes.

What do you think of it? Please let us know in the comments, we really appreciate feedback, positive or negative.

And stay tuned for the next episode, we will get to the nitty-gritty there.

images:
[Business] Business by Christophe BENOIT under CC
[Competing teams] Competing teams by Denis De Mesmaeker under CC
[Old cigarette machine] Old cigarette machine by Walter Baxter under CC

KW 24.16 – Weekly Blockchainers Recap

The DAO under attack 
Today it was a really importand day for the DAO and Ethereum. The DAO was hacked and everything looks a little bit like the Mt.Gox horror. The positiv view of this event is, the community works fast and constructive on this exception. At the moment not all facts are on the table, but it looks like the situation is under control. 

IMG_2016-06-17 21:08:48

See also the reddit thread for this event. 
Ethereum is not the DOA, but the trust in Ether as a currency was reduced.  

Allianz Blockchain experiments 
The German Insurance bets on blockchain for catastrophe bond trading. It sounds macabre and logical. It should only be used with institutional customers, nothing for retail customers. 

 

 

 

 

Gambling with Oracles

[casino kurhaus*]
[casino kurhaus*]

 

How to create a provably-fair high risk financial product with live data feeds provided by oracles.

Introducing Binary Options

This time, we gonna gamble. We will construct a financial product, more specifcally: a binary option, European style, cash-or-nothing.

[binary*]

Binary options are “a type of option in which the payoff is structured to be either a fixed amount of compensation if the option expires in the money, or nothing at all if the option expires out of the money” [1], therefore cash-or-nothing. European style means the option “can only be exercised at the end of its life, at its maturity” [2].

This is a high risk product which is “most likely traded over the Internet on platforms existing outside of regulations” [1], so “the customer is betting against the broker, who is acting as a bucket shop.” [3]

In general, this means that “because these platforms operate outside of regulations, investors are at greater risk of fraud” [1] and “manipulation of price data to cause customers to lose is common” [1].

BinaryOption (3)So, in contrast to common regulated financial products we have a really comprehensible option, which is mostly valued as high-risk, because there is a real clash of interests if the broker also evaluates the stock against the strike price and thus is highly motivated to manipulate this evaluation.

Smart Contracts to the Rescue

So, can smart contracts help here? You bet! The blockchain is trust-less, so you just don’t have to trust anyone, be it broker or bucket shop or both, but you can just prove if everything’s ok.

If a smart contract guarantees you that you will get 195% if you predict correctly and 0% if not, this rule has to be implemented in the contract.

Meeting the Oracle

Given that we can trust the contract, it should be easy to implement a binary option like this:

After deploying the contract, you have 1 hour to invest Ether on calls or puts on the contracts conditions (eg. DAX is above the strike price in 1 hour). After the 1 hour offering period, it's rien ne va plus, no purchase of calls or puts are possible. At this point of time, the current value of the DAX is stored. After exactly 1 hour the DAX is evaluated against the stored DAX value.
  • if the value is above or equal to the stored value, all calls are returned 195% of their investment, all puts lose all invested money
  • if the value is below the stored value, all puts are returned 195% of their investment, all calls lose all invested money

Sounds simple? It is!

[oracle*]
[oracle*]

You can easily prove that the contract actually implements the described rules, but there are two problems: how does the contract know the DAX spot? Contracts in Ethereum intentionally cannot connect to the outside world, therefore the outside world has to call the contract and provide the necessary data. Who tells the contract the exact time it has to retrieve the DAX spot? There must be some callback mechanism, since Ethereum smart contracts are not able to call themselves, have a Daemon, Threading etc.

Let’s gonna oraclize.it

There is a startup solving this problems in a elegant way: oraclize.it

You should look up and understand how oraclize.it works and helps us to solve our problems. In short, callbacks are used by oraclize.it and you can determine the exact data feed of the data which oraclize.it will provide at a certain point of time to our contract.BinaryOptionOrale (1)Here the two problems are addressed:

  1. The contract has to provide a callback for the oracle to call. The data feed is configured when the callback is provided, as well as the time interval.
  2. The oracle facilitates a scheduling to call the provided smart contract callback at the configured time interval.

Both solutions require the user and the contract owner to actually trust the “trusted datasource” (the contract’s user can decide if he trusts this datasource) and the oracle itself to have a working scheduling and not to manipulate the data. In contrast to the “broker” above, the oracle has no interest in manipulating the data.

However, oraclize.it not only offers a service, but even more defines a protocol, so there will most likely be more than one oracle to choose from to offer redundancy in the future.

Building Binary Options in Ethereum Studio

…in the next post.

Realizing how long this post already is, we decided to split the tutorial and the theoretical part. The tutorial will follow soon! Please let us know in the comments if you’d like to have this tutorial and what you expect of it.

Meanwhile, try out this ether.camp tutorial which describes the integration of oraclize.it into Ethereum Studio.

images:
[casino kurhaus] Kurhaus Casino by fr4dd under CC
[binary] binary by christine592 under CC
[
oracle] Oracle by Bob Doran under CC

icons:
icons made by Freepik from www.flaticon.com 

Ethereum Development Tools – an Evaluation Matrix

Developing for the Ethereum World Computer – Revisited

When comparing development methods for and in the Ethereum space, it becomes obvious how brilliant the people involved actually are: as a developer, you have several choices of great development tools and environments, even though the development process for Dapps is quite difficult: it involves different “layers” (frontend with HTML/CSS/JavaScript and backend with the Ethereum blockchain), different languages (JavaScript for frontend dev, Solidity for backend dev), different contexts (public/private/proprietary blockchains).

Taking these different contexts into account, evaluating the different development environments is only possible by identifying the different aspects and value them according to the own preferred usage.

Aspects of Dapp Development

Ethereum-docs-intro (1)

  • Solidity Development / Solidity Environment
    User can edit Solidity content in a text editor, there should be at least syntax highlighting.
  • JavaScript/Web Environment
    User can edit JavaScript, HTML and CSS in a text editor and gets different levels of support like syntax highlighting, code completion, etc.
  • IDE
    User can not only edit code (Solidity and JavaScript), but can also compile, check into a versioning system, debug and deploy to some operating environment.
  • Versioning
    Versioning is supported, eg. by enabling the user to check edited content into a versioning system, show diffs, apply patches, etc.
  • Collaboration
    Modification of code by multiple users is supported, at minimum support of different versions of the code is possible to avoid conflicts.
  • Deployment
    Working code can be deployed to some environment which enables the user and other users to use the working program (a sandbox or real blockchain and a web application server for JavaScript like node.js and static content like HTML and CSS files)

A first Categorization and a Teaser

We will summarize in short the different aspects which are supported in these development environment: Solidity Browser / Ethereum Wallet, Truffle and Ethereum Studio.

This is also a teaser for the upcoming blog posts, which will explain the environments in detail.

Solidity Browser / Ethereum Wallet

In terms of architectural styles, both environments represent minimalism. They are slim and handy, easy to use and fast to learn, but lack some functionality if real development “in the large” is necessary.

Ethereum-docs-browser
Solidity Browser, only Solidity Development, no Environment, ie. not even save of file is possible

Ethereum-docs-wallet
Ethereum Wallet (Mist), only Solidity Environment, no save of file possible, but integrated compiler

Truffle (also: Embark, Dapple)

Truffle satisfies all aspects which a usual client application can offer, therefore you can think of Gothik, it is mighty, almost lavish, and well structured. If you come from web development in JavaScript with node.js, who should look no further, this environment is for you (at least if you don’t need support for online development, versioning and multi user directly in your environment, but use external tools like Git and testrpc for these aspects).

Ethereum-docs-truffle
Truffle, also Embark and Dapple: web development environments, usefully extended with Solidity support

Ethereum Studio, the all-in-one-solution

The Ethereum Studio, in our opinion, resembles Deconstructivism. Why’s that? Because here all aforementioned aspects of software development are taken apart and are reconstructed to fit perfectly to Dapp development. This is an all-in-one-solution which we can really recommend, with two limitation: you have to agree to a uncertain pricing model (it just doesn’t exist right now, you can still test the product) and a “closed” environment, which works seemless and smooth, but expects you to let in to this tool and the development process.

But no other tool lets you test your code this easy with manual and even unit testing built into the environment.

Ethereum-docs-studio
The all-in-one-solution, steep learning curve, but all you will ever need in multi user, versionized, unit tested Dapp development

Stay tuned for the detailed explanations of these great development tools.

Wir machen uns die Welt … wie sie uns gefällt

Nach der Entdeckung der neuen Welt und dem Überwinden der ersten Hindernisse wollen wir uns nun sesshaft machen und anfangen, Applikationen und Smart Contracts jenseits von “Hello World” zu entwickeln.

Aber wie fangen wir an? Die ersten Erfahrungen mit dem fantastischen Tool cosmo.to waren viel versprechend, leider ist das Tool mittlerweile online nicht mehr verfügbar. Der wahrscheinliche Grund ist die Tatsache, dass das Standard-Ethereum-Wallet von ethereum.org die gleiche Funktionalität und noch viel mehr bietet. Allerdings zu Lasten der Übersichtlichkeit.

Wir wollen deshalb hier einen Überblick der bekanntesten Entwicklungsumgebungen geben, mit einer subjektiven Einordnung in Architekturstile:

  • Minimalismus: minimal, übersichtlich, aber auch schlicht: der Solidity Browser. Super zum Erlernen der Sprache Solidity, aber das war’s dann auch schon. Persistierung? Versionierung? Alles nicht vorgesehen. Super für den Einstieg.
  • Bauhaus: funktional und praktisch: das Ethereum Wallet dient nicht nur als Wallet selbst, sondern ermöglicht die Erstellung und das Deployment von Smart Contracts und die Verwaltung von eigenen Tokens.
  • Gotik: opulent, gut strukturiert, mächtig: Truffle ist ein reines Javascript-Framework und verwendet alle Komponenten, die moderne Javascript-Entwicklung bietet: Gulp, Mocha, Chai, etc. Sehr gut dokumentiert, ebenfalls gut für den Einstieg geeignet, bietet darüber hinaus aber auch viel mehr.
  • Kubismus: ganz anders, aber erfolg- und einflussreich: die Entwicklungsumgebung von Microsoft, Visual Studio (Community) oder der neue Open Source Editor Visual Studio Code zusammen mit BlockApps STRATO, einer zentralisierten Blockchain. Leicht zu nutzen, mit automatischer Frontenderstellung. Etwas für den anderen, schnellen Einstieg in private Chains mit Microsoft Azure.
  • Dekonstruktivismus: das “new kid on the block”, das Ethereum Studio von <ether.camp> macht alles etwas anders, nach unserer Meinung auch besser: eine verteilte Entwicklungsumgebung auf Basis von cloud9, ein integrierter Sandbox-Ethereum-Node, eine Deploymentmöglichkeit in alle möglichen Umgebungen (die JSON-RPC verstehen). Leider auf Dauer nicht kostenlos, Preise sind noch nicht bekannt.

In den nächsten Wochen werden wir die hier erwähnten (es gibt noch zahlreiche andere!) Entwicklungsumgebungen genauer testen, immer mit dem gleichen Tokenbeispiel. Stay tuned!

Ethereum Usecase: Online Identitätsprüfung

Die Identitätsprüfung des Kunden bei Onlinegeschäften ist in der Regel ein Prozess, der mehrere Tage in Anspruch nimmt. Die Identifizierung wird zum großen Teil über das PostIdent Verfahren abgewickelt, das von dem Kunden verlangt zur Postfiliale zu fahren, um sich vor Ort identifizieren zu lassen. Die schnellste (mir bekannte) Onlineidentifizierungsmethode bietet idnow, das z.B. von Number26 bei der Kontoeröffnung benutzt wird. Dabei wird in einem Video-Chat die Identität des Kunden überprüft. Der Prozess nimmt etwa 5 Minuten in Anspruch und ist mit gängigen Smartphones durchführbar.

Was wäre aber, wenn man den Identitfikationsprozess noch schneller und mit noch weniger Intermediären durchführen könnte? Das Zauberwort heißt Ethereum.

Der große Anspruch von Ethereum ist es einen offen zugägnlichen Welt-Computer zu schaffen, der in der Lage ist die Programme, die er ausführt und den Laufzeitzustand, der sich aus der Ausführung dieser Programme ergibt, in eine Blockchain so zu verpacken, dass es keine Möglichkeit gibt die Programme oder deren Laufzeitzustand zu verfälschen.

Jeder Benutzer und jedes Programm in Ethereum haben eine oder mehrere öffentlich bekannte Adressen. Zusätzlich zu der öffentlichen Adresse hat jeder Benutzer einen privaten (geheimen) Schlüssel mit dem er Transaktionen in Ethereum signieren kann.

Welche Möglichkeiten würden sich ergeben, wenn die Behörde bei der Ausstellung eines neuen Personalausweises für alle Ausweisdaten (Name, Vorname, Geburtsdatum, Adresse, …), einen Hash-Wert berechnen und in einem öffentlich zugänglichen Identitätsverzeichnis an die Ethereum-Adresse des Kartenbesitzers binden würde?

In Ethereum kann man so ein Identitätsverzeichnis mit wenigen Codezeilen durch den folgenden Contract abbilden:

contract IdentityRegistry {
    address owner; // Der Besitzerer der Registry (die Behörde)
    string name;   // Der Name der Registry
    
    // Abbildung von Ethereum Adresse
    // zu dem Hash-Wert der Personalausweisdaten
    mapping(address => uint256) idHashes;  
    
    // der Konstruktor wird einmalig beim Anlegen des Contracts ausgeführt
    function IdentityRegistry(string _name) {
        owner = msg.sender;   // hier merken wir uns den Contract-Ersteller als Besitzer
        name = _name;         // den Namen der Registry setzen
    }
    
    // Liefert den Namen der Registry, verändert nicht den Zustand
    function getName() constant returns (string) {
        return name;
    }
    
    // Beschreibt wie der Hash-Wert für die Daten gebildet wird
    // Alle Informationen werden durch "/" getrennt, hintereinander abgelegt
    // Es wird SHA-1 Hashwert der Zeichenkette berechnet
    function getIdHashFormat() constant returns (string) {
        return "sha-1(NAME/GIVENNAMES/DATEOFBIRTH/PLACEOFBIRTH/NATIONALIY/ADDRESS1/ADDRESS2/ADDRESS3)";
    }
    
    // Diese Methode kann nur von dem Besitzer (Bürgeramt) aufgerufen werden.
    // das "throw" rollt die Transaktion zurück, wenn die Transaktion
    // nicht vom Besitzer der Registry (Bürgeramt) aufgerufen wurde.
    // Die Funktion bindet den Hash-Wert an die Ethereum Adresse des Ausweisbesitzers
    function registerIdHash(address who, uint256 hash) {
        if(owner != msg.sender) throw;
        idHashes[who] = hash;
    }
    
    // Wird vom Gegenüber (z.b. Bank) aufgerufen, um den Hash-Wert einer
    // Ethereum Adresse zu überprüfen
    function verifyIdentity(address who, uint256 hash)
    constant returns(bool) {
        return idHashes[who] == hash;
    }
    
    // Falls keine der oben definierten Methoden aufgerufen wurde,
    // sorgt diese Funktion, dass die Transaktion zurückgerollt wird.
    function() {
        throw;
    }
}

Beantrag beispielsweise Max Mustermann, geboren am 01.01.1990 aus Musterstrasse 12, Musterhausen den Ausweis, berechnet das Amt zunächst den Hash-Wert aus allen oben genannten Daten, z.B.:

sha1("MUSTERMANN/MAX/01.01.1990/MUSTERHAUSEN/DEUTSCH/MUSTERHAUSEN/MUSTERSTRASSE 12") = 1417400950720517943593210833135938663929334829119

Dieser Hash-Wert wird anschliessend vom Amt im Identitätsverzeichnis an Maxs öffentliche Ethereum-Adresse (0xDBEc37…) gebunden, z.B.:

identityRegistry.registerIdHash(
    0xDBEc371775c57f59fDA5BBa2c9FC8876968F34E3, 
    1417400950720517943593210833135938663929334829119)

Hierbei ist es wichtig anzumerken, dass aus dem Hash-Wert der Daten keine Rückschlüsse auf die Daten selbst gezogen werden können.

Möchte Max ein Konto bei der Musterbank eröffnen, könnte er nun über ein Onlineformular der Musterbank seine persönlichen Daten eingeben und zusätzlich seine öffentliche Ethereum-Adresse senden. Mit diesen Informationen kann die Musterbank bereits überprüfen, ob der Datensatz korrekt ist. Genauso wie das Bürgeramt, berechnet die Musterbank den Hash-Wert und vergleicht diesen mit dem Hash-Wert aus dem Identitätsverzeichnis des Bürgeramts. Z.B.:

bool res = identityRegistry.verifyIdentity(
    0xDBEc371775c57f59fDA5BBa2c9FC8876968F34E3,
    1417400950720517943593210833135938663929334829119)

Damit ist überprüft, ob der Datensatz valide ist, aber noch nicht ob Max auch der tatsächliche Absender der Information ist. Um auch das zu überprüfen, instantiiert die Musterbank einen weiteren Contract auf Ethereum und wartet darauf, dass Max mit seinem privaten (geheimen) Schlüssel die Bestätigungsmethode aus dem Contract aufruft und damit beweist, dass er tatsächlich der Besitzer des Ethereum Kontos mit der öffentlichen Adresse 0xDBEc37… ist. Der Contract sieht wie folgt aus:

contract IdentityConfirmation {
    address createdBy;    // Ersteller des Contracts (Musterbank)
    address who;          // Wer soll sich identifizieren (Max)
    bool confirmed;       // wurde die Identität bestätigt?
    
    // dieses Event wird verschickt,
    // wenn Max die Funktion "confirm" aufruft
    event IdentityConfirmed(address who);
    
    function IdentityConfirmation(address _who) {
        who = _who;
        createdBy = msg.sender;
        confirmed = false;
    }
    
    // wenn die Methode von Max aufgerufen wird, d.h.,
    // der Aufruf mit dem privaten Schlüssel von Max signiert wurde
    // bekommt die Musterbank die Bestätigung über
    // die erfolgreiche Authentifizierung
    function confirm() {
        if(who == msg.sender) {
            confirmed = true;
            IdentityConfirmed(msg.sender);    
            suicide(createdBy);
        }
    }
    
    function() {
        throw;
    }
}

Anbei der gesamte Vorgang zusammengefasst in einem Sequenzdiagramm:

Sequence Diagram

Weitere Überlegungen

Das vorgestellte Konzept ist eine grobe Skizze. Ein produktives System bräuchte noch weitere Feature wie z.B Aktualisierung / Sperrung / Entsperrung des Eintrags im Umzugsfall oder beim Verlust des privaten Schlüssels bzw. beim Ablauf des Ausweises.

Falls die Behörden nicht die Blockchain-Technologie adaptieren sollten, kann man sich auch folgende Alternativen vorstellen:

  • Es existiert ein Intermediär vergleichbar zu idnow, der den Aufbau des Identitätsverzeichnisses übernimmt und den Dienst gegen Gebühr anbietet.
  • Das Identitätsverzeichnis wird innerhalb des Konsortiums/Verbands aufgebaut und benutzt.

Schließlich wäre noch zu untersuchen, ob man mit dem privaten Ethereum Schlüssel außerhalb von Ethereum Daten signieren kann (public/private-key Verfahren). Das würde den zweiten Contract überflüssig machen.

Homestead … settling down

Having crossed frontiers in unknown and unsafe land, finally, we are settling down.

After having described last time how to create our own cryptocurrency in Ethereum Frontier – the description of which was way to complicated as we have learnt – we will repeat it, this time in Ethereum Homestead, and we assure you: this time it will be really easy.

In fact, creating a new cryptocurrency is even built into the new Ethereum wallet, so if you use the proposed “coin-interface“, your own currency is even supported with an own pocket in the wallet itself, besides your real Ether – this is just gorgeous and if you are still unsure about the world dominance about Ethereum, try this out and hopefully, just be astonished.

EtherumWallet

Ok, enough propaganga, let’s get down to the nitty-gritty.

Objective

Create you own cryptocurrency in Ethereum Homestead. You should be able to fund yourself with some amount of initial value (let’s say 10000 items) of your own currency and be able to send it around to any valid Ethereum address.
This currency should in no way be related or dependent on an existing crytocurrency like Bitcoins or Ether and creating it should cost you not one penny of your fiat or “real” crypto-money.

Setup

The easiest way to archieve the goal would be to just follow the instructions on the new ethereum.org Homestead site closely, you can then use your cryptocurrency in the real and in the Morden testnet.

However, this approach has two limitations:

  • It takes longer than five minutes, which is our definition of really easy (but afterwards you will know why it works)
  • It runs on the real Ethereum blockchain or on the Morden testnet, but we want to build this using own very own, local and/or private, Ethereum blockchain.

If these limitations do not apply for me, stop here and go ahead and read the official tutorial.

Ok, I want my local, private blockchain, really fast, so let’s go…

Ready, Set…

  • Start Geth with an own genesis file and an unique networkid (greater than 1), for details see this post.
    You can use this genesis file, just store it as /ethereum/genesis.json (always add the drive for Windows, eg. c:/ethereum/genesis.json)

    {
        "nonce": "0xdeadbeefdeadbeef",
        "timestamp": "0x0",
        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "extraData": "0x0",
        "gasLimit": "0x8000000",
        "difficulty": "0x400",
        "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "coinbase": "0x3333333333333333333333333333333333333333",
        "alloc": {
        }
    }

    and create the empty directory /ethereum/data
    The start command then is

    geth --genesis /ethereum/genesis.json --datadir /ethereum/data --networkid 123 --nodiscover --maxpeers 0 console

    we need this initial start with the console to create our first account, which we need to start mining.
    In the console, type

    personal.newAccount()

    and create your “etherbase”-account. Subsequent accounts can be created in the Ethereum Wallet.
    Make sure that you exit geth afterwards.

    …Go

  • Now, start the Ethereum Wallet, make sure Geth is not running currently
    There will be several dialogs, it does not really matter what you type in there. You should choose testnet if asked for real or Morden testnet.
  • Afterwards, when all steps have been completed, you will see an empty account in the Morden testnet

    ethereum-morden

  • Quit the Wallet.
  • To start the Wallet using our local testnet, consult the readme.txt in the installation folder and make sure you set the ipcpath cli argument correctly. On Windows, you can skip this step.
  • Start geth with this parameters (plus the ipcpath, if on Linux)
    geth --genesis /ethereum/genesis.json --datadir /ethereum/data --networkid 123 --nodiscover --maxpeers 0 --mine

After restarting the Wallet, we should see our created account with some Ether in it (we are mining currently and the difficulty is really low and we have no peers, so we get all the money)

account-start

Choose Contracts and Copy & Paste the code from the tutorial…

created-my-token

…linked on the contracts page

build-token

Don’t forget to set the arguments for your token/currency (like display name, initial supply, etc.)

arguments-token

Choose the fastest possible deployment (we have enough Ether right now).

fastest-deploy

Here we go, congrats to your very own cryptocurrency with Wallet support.

etherbase-mouc

Please comment on this tutorial, does it work for you? Did you get stuck at some step? We want to improve out tutorials to make sure more people use this great technology.