Brief introduction to ENS

Brief introduction to ENS (Ethereum Name Services)

An Internet without Domain Name Service (DNS) is hardly imaginable. Addressing resources directly on the basis of their IP address would be a difficult and an error-prone undertaking. How nice it is that there is a Domain Name Service (DNS) that makes the mapping between machine-readable IP addresses and easily understandable memorable names for humans. With the help of DNS, we can easily locate resources on the Internet, even if their IP addresses have changed in background.

A similar function as DNS on the Internet, is ENS on the Ethereum blockchain. Resources of the Ethereum blockchain are primarily Smart Contracts. Contracts are addressed via a 20 byte address, represented as a 40-digit hex string.

The core elements of the Ethereum Name Service are specified in EIP-137. These are the core elements:

  •  ENS-Registry
  •  Resolvers
  •  Registrars

The ENS Registry is a contract that is responsible for the administration of domain names. In addition to mapping domain names to a linked resolver contract, the registry is responsible for ensuring that the owner of a domain has the permission to set up new sub-domains for this domain or to change entries in the resolver.

Revolvers are responsible for responding to resource requests to a domain and return, for example, the contract address, the ABI of a contract or the publickey of a wallet. Each domain name has a link to its resolver.

The registrar is the owner of a domain. Only the registrar has the right to register new sub-donains or change resources. Registrars are contracts or owned accounts. Top- and second-level donains are usually managed by a registrar contract. For example, the second-level domain of Mainnet is administered by a registrar which implements an auction procedure for the allocation of new domains.

Analogous to DNS, the namespace is hierarchically subdivided. Individual domains are separated by dots. The DNS structure of top-level, second-level and sub-domains has been adopted. A valid domain name is, for example, ‘earth.planets.eth’. Domain names are mapped to sha3-hashs (keccak_256). The derivation of the hash is defined by the following namehash function:

def namehash(name):
  if name == '':
    return '\0' * 32
  else:
    label, _, remainder = name.partition('.')
    return sha3(namehash(remainder) + sha3(label)) 

The hash of ‘earth.planets.eth’ is calculated as follows:

sha3(sha3('eth') + sha3(sha3('planets') + sha3('0x0000000000000000000000000000000000000000000000000000000000000000' + sha3('earth'))))

Reverse Name Resolution

In addition to mapping a domain name to its resources such as address, ABI or publickey, ENS also supports reverse mapping from an address to its domain name. The procedure for this is described in EIP-160. For reverse mapping, the resource address is registered under the reverse domain name ‘address’.addr.reverse. The resolver for the reverse domain name holds the name of the original domain. The registrar of the domain ‘addr.reverse’ provides a function setName(‘domain’) under which a caller registers his domain-name.

Example

The following example shows how to install ENS including a registrar for reverse name resolution. Deploying all contracts requires a working truffle environment and access to an Ethereum node such as Ganache. You find the project repository at GitHub: Ehereum-ENS-Demo

Step 1: Contract Deployment

In the first step all required contracts are deployed. The script ‘2_deploy_ENS.js’ deploys the ENS-Registry (ENS.sol), the registrar for the top-level domain (FIFSRegistrar.sol), the registrar (ReverseRegistrar.sol) for the reverse domain, the resolver (PublicResolver.sol) for answering resource requests. Finally, the domains ‘planets.eth’ and ‘addr.reverse’ are registered.

The script ‘3_deploy_Planets.js’ deploys a demo contract and registers it under the name ‘earth.planets.eth’ and its addresses in the domain ‘addr.reverse’ with the name ‘earth.planets.eth’. The contract ABI is also packed in zlib format and assigned to the domain as a resource.

The entire deployment is started with the command:

truffle migrate --reset

Step 2: Access earth.planets.eth

The command

npm install

installs all necessary libraries. The libraries ethereum-ens and web3 are used for easy access to ENS and resources of a domain. Before start, the address of the ENS registry must be added to the script (see const ensAddr).

The script is started with the command `node scripts\call_Earth.v1.js`. First the script determines the address and ABI of the domain name ‘earth.planet.eth’, then creates a client for contract access. In the second step, the domain name stored for the address is determined and printed.

The library “ethereum-ens” simplifies the access to the ENS registry. Alternatively, the script ‘scripts\call_Earth.v2.js script’ shows access to the ENS registry without using “ethereum-ens”. The script is started with:

truffle exec scripts\call_Earth.v2.js

More Ressources

invite_me: Onboarding to Ethereum chains with keybase.io identity verification and EIP-712

This is not a Blockchain-bullshit-only post. Head to https://github.com/ice09/onboarding-eip712 for a sample implementation of a private Testnet onboarding with Twitter, Reddit or Github Keybase proofs.

The challenge…

Creating a private Ethereum Proof-of-Authority testnet is actually quite easy, just follow the instructions of Parity or, for testing purposes only, cliquebait, and you’re done.

But how do you onboard new users, who want to participate in your testnet, if they don’t have any ETH to start with and you still want to stay as close to your production environment in terms of gas usage as possible and therefore don’t want to enable gasless transactions in your PoA testnet?

…and the public testnet solutions

Kovan PoA

The public (Parity-powered) Kovan PoA solves this problem by providing a “Faucet Service” which is verified by

Rinkeby PoA

The public (Geth-powered) Rinkeby PoA solves this problem by providing a “Faucet Service” which is verified by

However, these methods require trust or establish dependencies on the testnet providers, which you will and can most likely not introduce in your private net. 

Analysing the problem

There are (at least) two different user states which a user can have in your PoA private testnet:

  1. The user has an authorized account in one of the authority node wallets.
  2. The user is connected to the private testnet, but initially has no balance.

In Proof-of-Work (PoW), the non-authorized user could start mining and get ETH for contract development. This is the Ropsten solution. In PoA, mining is not possible, so the user has no possibility to transact on the chain, except for using usd_per_tx=0 or similar for no gas costs on the authority nodes, which is possible, but contradicts the security measures established by having gas usage for transactions to minimize code execution, prevent infinite loops, etc. Even more, the setup on a test stage should always be similar to the production environment.

Recentralizing for “Almost Know Your Customer”

keybase.io does a great job in identifying users without revealing their real life identity if they don’t want to. But they make it quite difficult for attackers to create several identities. So a good enough solution for onboarding otherwise unknown users could be to bind their testnet accounts to their keybase users.

The basic idea and the following approach is inspired by Aragon and one of their great blog posts, which every Ethereum/Solidity dev should take a look at.

In our setup, we changed two crucial factors:

  1. removed dependencies on a product (Aragon) and on the Oracle (oraclize.it) and
  2. introduced a middleware component as a new dependency, but which you control and can (and have to) host on your own server.

keybase allows for publishing files per HTTPS by copying them to KBFS file system. Thereby, someone reading a file from https://KEYBASE_USER.keybase.pub/invite_me.json can be sure that the file invite_me.json was stored by keybase KEYBASE_USER.

But this is just one proof, how can we be sure that the user really has the private key for the address he wants to be registered? We can just sign the message with the private key and ecrecover in a contract. 

Using this mechanism, we can be sure that:

  1. If the URL https://KEYBASE_USER.keybase.pub/invite_me.json gives back the correct JSON, the user is who he pretends to be, since he had to copy invite_me.json to KBFS
  2. The address (private key) belongs to the user, since he signed the message in invite_me.json and the signature is ecrecovered in the invite_me contract.

MetaMask does a great job in helping signing data with your Ethereum’s account private key. However, up to EIP-712 the signed data has been displayed as a non-human-readable Hex string.

This is unacceptable, especially in crypto, a field of very easy and unavoidable fraud attempts. 

Therefore, we are supporting EIP-712 by signing with a MetaMask version supporting the new eth_signTypedData method. EIP-712 is a major step forward and should be the only way users are required to sign data with their Ethereum account’s private key.

The following overview shows the process which let a new user register his keybase user to a new generated address. Afterwards, 10 ETH are sent to this address. The user can only register once. However, the contract owner can manually unregister users if necessary.

For the ETH transfer to happen, the user must

  • have the invite_me.json as generated by the frontend part stored in his KBFS public directory, so that it can be retrieved by the server side process at the keybase.pub domain
  • have at least one of these Keybase proofs: Twitter OR Github OR Reddit

Introducing invite_me

The complete process is implemented in the “DApp” invite_me, which consists of a JavaScript frontend and a web3j-powered Java backend component called verifier.

After completing the steps, you can see the 10 ETH loaded into your account in MetaMask.

Let me try this!

First, checkout this. Then, make sure that you have an understanding how the authorization and verification works and what the Java component verifier does and how they depend on each other.

Last, install it locally and try it out. And, most importantly, please comment here or in the reddit post if it doesn’t work for you or if you have remarks about the approach, obviously this is work in progress.

What comes next?

We’d like to try two different approaches:

  • Using 3box as a more decentralized (but not as mature) keybase alternative
  • Realizing a different use case: “Almost KYC Airdrops” 

Excel2Blockchain with web3j

If you ever come to the conclusion, for whatever reason, that pushing Excel data to the Blockchain is what you need, we are happy to help!

We recently read about the Azure Blockchain Development Kit and had to cringe about the samples. But, who are we to judge those important enterprise business use cases requiring to get data from Excel to the Blockchain? 

Therefore, we took a look at the prerequisites, setup, initialisations and finally the execution of this with the new Microsoft Azure templates. And, to be clear, we love the idea of Microsoft getting involved into Blockchains and Ethereum and pushing Azure as a starter kit, that’s really great.

However, the whole procedure seemed quite long and exhaustive, that’s why we want to show how easy this is with standard development methods. Of course, these are lacking a lot of features and cool stuff you get with Azure then. But, they can help you to understand better what happens under the hood. So, let’s go for it.

No, wait, Excel to Blockchain, honestly? Why?

//TODO: Insert suitable reason here.

Ok then, but how?

Due to web3j it is really easy to connect to an arbitrary Ethereum Node, even Infura and Ganache, as simple as it is with web3.js or web3.py. All the other stuff is common Java dev tools, like Glueing with Maven, Excelling with Apache POI, etc. This is where Java shines, it’s really good at enterprisey integration stuff.

You can start directly and import the sources as a Maven project in your IDE or build it without an IDE and start it from the command line. See the details here.

Show me some code!

private void connectToBlockchain() throws IOException {
Web3j httpWeb3 = Web3j.build(new HttpService("http://localhost:8545"));
log.info("Connected to HTTP/JSON Ethereum client version: " + httpWeb3.web3ClientVersion().send().getWeb3ClientVersion());
// Create credentials from private key.
// Don't use with real (Mainnet) Ethereum accounts.
String privateKeyDeployer = "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3";
Credentials credIdentity = Credentials.create(pkDeployer);
BigInteger balance = httpWeb3.ethGetBalance(credIdentity.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance();
log.info("Deployer address " + credIdentity.getAddress() + " has " + balance + " wei.");
}

private void deployExcelContractToBlockchain() throws Exception {
ExcelStorage excelStorageContractHttp = ExcelStorage.deploy(httpWeb3, credIdentity, ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT).send();
log.info("Deployed contract at " + excelStorageContractHttp.getContractAddress());
}

As you can see, ExcelStorage is a class which can used like any other Java class. It has been generated by a Maven plugin (web3j-maven-plugin) during build time. It is statically typed with methods resembling the Solidity functions of the smart contract and with all the nice aspects this has: compile time checks instead of runtime checks and brilliant IDE support (code completion, type checking, static code analysis).

With great IDE and build tool support, you can try this out yourself, you will be surprised how lightweight and easy Ethereum smart contract usage is from Java. Even more, integration with your existing (“legacy”) software and infrastructure is straightforward. 

Have fun!

Addendum: This is a Testsetup only! What about the real Blockchain?

Where does the private key in the current Java sources come from? 
If you start Ganache with the mnemonic mentioned, everytime the same accounts are generated. The first one being 0x627306090abaB3A6e1400e9345bC60c78a8BEf57. This address has one private key which is set into the Java sources to create the Credentials for contract deployment and transactions.

Setup for other test chains

  • Create an account with infura.io
  • Use the Endpoint URL from the dashboard and copy in into the Java sources

  • Create an account with MetaMask
  • Copy the address of your account

  • Copy the private key to the Java source code to use the account for contract deployment and transactions

Token ERC Comparison for Fungible Tokens

“The good thing about standards is that there are so many to choose from.” Andrew S. Tanenbaum

Current State of Token Standards

The current state of Token standards on the Ethereum platform is surprisingly simple: ERC-20 Token Standard is the only accepted and adopted (as EIP-20) standard for a Token interface.

Proposed in 2015, it has finally been accepted at the end of 2017.

In the meantime, many Ethereum Requests for Comments (ERC) have been proposed which address shortcomings of the ERC-20, which partly were caused by changes in the Ethereum platform itself, eg. the fix for the re-entrancy bug with EIP-150. Other ERC propose enhancements to the ERC-20 Token model. These enhancements were identified by experiences gathered due to the broad adoption of the Ethereum blockchain and the ERC-20 Token standard. The actual usage of the ERC-20 Token interface resulted in new demands and requirements to address non-functional requirements like permissioning and operations.

This blogpost should give a superficial, but complete, overview of all proposals for Token(-like) standards on the Ethereum platform. This comparison tries to be objective but most certainly will fail in doing so.

The Mother of all Token Standards: ERC-20

There are dozens of very good and detailed description of the ERC-20, which will not be repeated here. Just the core concepts relevant for comparing the proposals are mentioned in this post.

The Withdraw Pattern

Users trying to understand the ERC-20 interface and especially the usage pattern for transfering Tokens from one externally owned account (EOA), ie. an end-user (“Alice”), to a smart contract, have a hard time getting the approve/transferFrom pattern right.

From a software engineering perspective, this withdraw pattern is very similar to the Hollywood principle (“Don’t call us, we’ll call you!”). The idea is that the call chain is reversed:  during the ERC-20 Token transfer, the Token doesn’t call the contract, but the contract does the call transferFrom on the Token.

While the Hollywood Principle is often used to implement Separation-of-Concerns (SoC), in Ethereum it is a security pattern to avoid having the Token contract to call an unknown function on an external contract. This behaviour was necessary due to the Call Depth Attack until EIP-150 was activated. After this hard fork, the re-entrancy bug was not possible anymore and the withdraw pattern did not provide any more security than calling the Token directly.

But why should it be a problem now, the usage might be somehow clumsy, but we can fix this in the DApp frontend, right?

So, let’s see what happens if a user used transfer to send Tokens to a smart contract. Alice calls transfer on the Token contract with the contract address 

….aaaaand it’s gone!

That’s right, the Tokens are gone. Most likely, nobody will ever get the Tokens back. But Alice is not alone, as Dexaran, inventor of ERC-223, found out, about $400.000 in tokens (let’s just say a lot due to the high volatility of ETH) are irretrievably lost for all of us due to users accidentally sending Tokens to smart contracts.

Even if the contract developer was extremely user friendly and altruistic, he couldn’t create the contract so that it could react to getting Tokens transferred to it and eg. return them, as the contract will never be notified of this transfer and the event is only emitted on the Token contract.

From a software engineering perspective that’s a severe shortcoming of ERC-20. If an event occurs (and for the sake of simplicity, we are now assuming Ethereum transactions are actually events), there should be a notification to the parties involved. However, there is an event, but it’s triggered in the Token smart contract which the receiving contract cannot know.

Currently, it’s not possible to prevent users sending Tokens to smart contracts and losing them forever using the unintuitive transfer on the ERC-20 Token contract.

The Empire Strikes Back: ERC-223

The first attempt at fixing the problems of ERC-20 was proposed by Dexaran. The main issue solved by this proposal is the different handling of EOA and smart contract accounts.

The compelling strategy is to reverse the calling chain (and with EIP-150 solved this is now possible) and use a pre-defined callback (tokenFallback) on the receiving smart contract. If this callback is not implemented, the transfer will fail (costing all gas for the sender, a common criticism for ERC-223).

 

Pros:

  • Establishes a new interface, intentionally being not compliant to ERC-20 with respect to the deprecated functions
  • Allows contract developers to handle incoming tokens (eg. accept/reject) since event pattern is followed
  • Uses one transaction instead of two (transfer vs. approve/transferFrom) and thus saves gas and Blockchain storage

Cons:

  • If tokenFallback doesn’t exist then the contract fallback function is executed, this might have unintended side-effects
  • If contracts assume that transfer works with Tokens, eg. for sending Tokens to specific contracts like multi-sig wallets, this would fail with ERC-223 Tokens, making it impossible to move them (ie. they are lost)

The Pragmatic Programmer: ERC-677

The ERC-667 transferAndCall Token Standard tries to marriage the ERC-20 and ERC-223. The idea is to introduce a transferAndCall function to the ERC-20, but keep the standard as is. ERC-223 intentionally is not completely backwards compatible, since the approve/allowance pattern is not needed anymore and was therefore removed.

The main goal of ERC-667 is backward compatibility, providing a safe way for new contracts to transfer tokens to external contracts.

Pros:

  • Easy to adapt for new Tokens
  • Compatible to ERC-20
  • Adapter for ERC-20 to use ERC-20 safely

Cons:

  • No real innovations. A compromise of ERC-20 and ERC-223
  • Current implementation is not finished

The Reunion: ERC-777

ERC-777 A New Advanced Token Standard was introduced to establish an evolved Token standard which learned from misconceptions like approve() with a value and the aforementioned send-tokens-to-contract-issue.

Additionally, the ERC-777 uses the new standard ERC-820: Pseudo-introspection using a registry contract which allows for registering meta-data for contracts to provide a simple type of introspection. This allows for backwards compatibility and other functionality extensions, depending on the ITokenRecipient returned by a EIP-820 lookup on the to address, and the functions implemented by the target contract.

ERC-777 adds a lot of learnings from using ERC-20 Tokens, eg. white-listed operators, providing Ether-compliant interfaces with send(…), using the ERC-820 to override and adapt functionality for backwards compatibility.

Pros:

  • Well thought and evolved interface for tokens, learnings from ERC-20 usage
  • Uses the new standard request ERC-820 for introspection, allowing for added functionality
  • White-listed operators are very useful and are more necessary than approve/allowance, which was often left infinite

Cons:

  • Is just starting, complex construction with dependent contract calls
  • Dependencies raise the probability of security issues: first security issues have been identified (and solved) not in the ERC-777, but in the even newer ERC-820

(Pure Subjective) Conclusion

For now, if you want to go with the “industry standard” you have to choose ERC-20. It is widely supported and well understood. However, it has its flaws, the biggest one being the risk of non-professional users actually losing money due to design and specification issues. ERC-223 is a very good and theoretically founded answer for the issues in ERC-20 and should be considered a good alternative standard. Implementing both interfaces in a new token is not complicated and allows for reduced gas usage.

A pragmatic solution to the event and money loss problem is ERC-677, however it doesn’t offer enough innovation to establish itself as a standard. It could however be a good candidate for an ERC-20 2.0.

ERC-777 is an advanced token standard which should be the legitimate successor to ERC-20, it offers great concepts which are needed on the matured Ethereum platform, like white-listed operators, and allows for extension in an elegant way. Due to its complexity and dependency on other new standards, it will take time till the first ERC-777 tokens will be on the Mainnet.

Links

[1] Security Issues with approve/transferFrom-Pattern in ERC-20: https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view

[2] No Event Handling in ERC-20: https://docs.google.com/document/d/1Feh5sP6oQL1-1NHi-X1dbgT3ch2WdhbXRevDN681Jv4

[3] Statement for ERC-20 failures and history: https://github.com/ethereum/EIPs/issues/223#issuecomment-317979258

[4] List of differences ERC-20/223: https://ethereum.stackexchange.com/questions/17054/erc20-vs-erc223-list-of-differences

 

 

Is it a blockchain or is it a DLT?

In various discussions I often hear people saying “But that’s not blockchain! That’s DLT!”. This sounds like blockchain and DLT would be two totally different things, while in fact, blockchain is a specific implementation of a DLT.  What most people actually mean is something like this: “But that’s not public, unpermissioned and egalitarian! That’s private, permissioned and authoritarian!”.

While I’m waiting to see the terminoligy get standardized, I have decided for myself to apply the following three-dimensional categorization:

private / public – connectivity to the network. E.g.: are nodes accesible via Internet or Intranet? Can anyone join or is it limited to a closed user group?

permissioned / unpermissioned – access regulation. Do I need a permission/invitation to join the network?

egalitarian / authoritarian – are all participants (potentially) equal in their rights?

The obvious two categories are the two well known extrems:

Public unpermissioned egalitarian – The participant doesn’t have to ask someone for permission to join. He can create an account (private/public key pair) by himself  and he can immediately start to use the network via Internet. Every participant in the network has the same rights (but not necessarily the same means). Typical representants of this category are Bitcoin and Ethereum.

Private permissioned authoritarian – The participant needs a permission or an invitation to join the network. There are authorities, which grant/revoke the rights. The network is private and/or the connection to it is regulated (firewals, whitelists, VPN, …). Typical representants are Hyperledger Fabric and Corda.

How about the other 6 categories? Of what use could they be? Let me try to describe the public one first, since the private variants are a narrower version of it.

Public permissioned egalitarian -the participant needs a permission to join the network, but as soon as he joined, he has the same rights as other participants. For instance an invite-only social network.

Public permissioned authoritarian – the network is open to everyone, but the onboarding and transaction validation is done by the network authorities. Example for this are RippleTobalaba Test Network, and Infrachain (maybe?). What I also could imagine is to have for instance a Europe-wide Proof of Authority Ethereum network. Let’s call this theoretical construct Eurochain. In Eurochain each government has a sealing node and is onboarding its citizents after checking their identity.

Public unpermissioned authoritarian – Same as above but with the difference that participants can join without asking for a permission.

Private permissioned egalitarian – this seems weird at first, but if you put it in the context of an extranet (see CredNet for example, which is the network connecting all German saving banks (Sparkassen)), it starts to make sense again. However, I have not observed one yet.

Private unpermissioned authoritarian – a narrower variant of the public one. For instance if the theoretical Eurochain is not intended to be used by the citizens but only for the communication between governments themselves.

Private unpermissioned egalitarian – more open variant of the permissioned one.

Das große Mining Abtenteuer ….

… oder der neue Mining Goldrausch mit Crypto – Währungen.

Bitcoin Mining hat sich in den letzten Jahren deutlich verändert. Zuerst experimentiert man mit seiner eigenen CPU, dann nutzte man seine Grafikkarte und zum Schluss begann der Krieg der ASIC Miner. ASIC (Application Specific Integrated Circuit).

Wer mit dem ASICs Mining Geld macht, entschied sich weitgehend anhand der Stromkosten und wer neue effiziente Modelle herstellen konnte. Daher verwundert es nicht, dass nur noch dort wo der Strom billig war, mehr und mehr Miner sich konzentrierten. Die klugen Miner gehen auch noch dahin wo das Klima kälter ist, um die kosten für die Klimatisierung gering zu halten.

Die Preisbewegungen und der Boom der Cryptos in der ersten Jahreshälft 2017 hat die Karten für einen begrenzten Zeitraum neu gemischt. Auf einmal konnte man wieder mit seinem Gaming PC profitabel Minen. Der Ethereum Algorithmus Ethash läuft aktuell am besten auf einer Spielegrafikkarte, die Gewinne reichten aus um auch in Länder mit hohen Stromkosten die laufenden Kosten zu kompensieren.

Der Mining Markt kam in Bewegung, immer mehr private Miner bauten sich Mining Rigs, auf youtube gibt’s eine menge Filme dazu mit sehr spannenden Konstruktionen und die Motherboard und Grafikkarten Hersteller produzieren Gaming Hardware die nur noch für das Minen ausgerichtet ist.

Am besten lässt sich der Minig-Boom am Verlauf der produzierten Hashrate im Ethereum Netz über die Zeit, oder dem Aktienverlauf von Nvidia ablesen.

https://etherscan.io/chart/hashrate

Stand 7.9.2017 werden ca. 90 tera Hashes im Ethereum Netzwerk fürs Mining erzeugt. Eine Nvidia Geforce 1070 generiert ca. 30 Mega Hashes, d.h. alleine für Ethereum würden aktuell alleine 3 Mio. Grafikkarten verwendet. Die Karte benötigt ca. 100 Watt wenn sie richtig eingestellt ist, also werden mindestens 300 Megawatt für das Ethereum Netzwerk verbraucht. Eine durchschnittliche Windkraftanlage erzeugt 3 MW, d.h. min. 100 Windräder laufen nur für Ethereum.

Die meisten verwendeten Karten erzeugen weniger Hashes und verbrauchen mehr Strom.

Die verwendeten Algorithmen unterscheiden sich stark im Stromverbrauch, So benötigt das Minen der Währung Monero weniger Leistung, Ethereum liegt im Mittelfeld, wohingegen Zcash 10..20 % mehr Energie aufnimmt. Jede Währung hat eine eigne optimale Configuration von Leistung, Speicher- und GPU Taktrate.

Das Minen von Ethereum hat einen weiteren Pferdefuß. Nicht nur die stark wachsende Anzahl der Mining-Grafikkarten reduzieren die Erträge, auch die „difficulty bomb“ im Code sorgt für fallende Erträge. Sie macht das Mining schrittweise unattraktiver bis zum nächsten Release, in dem der Konsen-Algorithmus auf Proof-of-Stake umgestellt wird.

Auf der folgenden Website wird der Effekt deutlich:

http://www.mycryptobuddy.com/EthereumMiningCalculator

Andere Cryptos haben zwar keine „difficulty bomb“ und bleiben beim Proof-of-Work, es ist jedoch zu beobachten, dass der Hashrate Markt sehr effizient ist, Ethereum Miner wechseln zu Zcash, Monero etc. so dass die Mining-Erträge dort analog sinken und sich dem Strompreis nähern.

Welcher Coin welchen Algorthmus verwendet findet man unter anderen auf whattomine.com oder bei der Börse cryptopia.co.nz.

Die Preise für Mining geeignet Grafikkarten ist ebenfalls im Sommer schnell angestiegen um bis zu 50 %, sinkt jetzt jedoch schon wieder, hat aber noch nicht das Mai Niveau erreicht. Glaskungeln gehen davon aus, dass sie Anfang 2018 wieder auf dem Level von vor dem Boom sind.

Wie bei jedem Goldrausch verdienen auch bei diesem die Verkäufer von Schaufeln am meisten Geld. Neben Nvidia und AMD scheinen auch die Entwickler von Miningsoftware das große Geld zu machen. Der weitverbreitete Claymore Mining-Software nutzt 1% der Mining-Zeit für den Entwickler. Das könnte bedeuten, wenn 10% der Miner die Software von Claymore verwenden, jede Grafikkarte 40 $ in Cryptos pro Monat schürft, dann würde der Entwickler 0,40$ pro Grafikkarte und Monat verdienen. Das wären bei 3 Mio. Karten einnahmen von 120.000 $ im Monat. Vermutlich verwenden jedoch mehr Grafikkarten den Claymore Miner.

Ob es sich lohnt einen Rechner fürs Minen zu bauen, muss jeder für sich entscheiden. Einen positiven Business Case auf lange Sicht zu rechnen ist schwierig, in der ersten Hälfte des Jahres 2017 hätte man mehr Geld verdient, wenn man das Kapital für einen Rechner direkt in Ether investiert hätte, jedoch ist der Spaß einen eignen Rechner zusammen zu bauen unbezahlbar.

Blockchain + Streaming Analytics = Smart Distributed Applications

We are really pleased to publish a guest contribution by Kai Wähner about Smart Distributed Applications.
Kai is Technology Evangelist and Community Director for TIBCO Software. His expertise lies within the fields of Big Data, Advanced Analytics, Machine Learning, Integration, SOA, Microservices, BPM, Cloud, Internet of Things, Blockchain and Programming Languages such as Java EE, Scala, Groovy, Go or R. He regularly writes about new technologies, articles and conference talks on his blog.

We are approaching Blockchain 3.0 these days. You ask “3.0”? Seriously? Blockchain is still in the early adoption phase! Yes, that is true. Nevertheless, while we are moving forward to real world use cases in various industries, we see that you need more than just a blockchain infrastructure. You need to build decentralized applications. These include blockchains, smart contracts plus other applications plus integration and analytics on top of these solutions.

Middleware is Key for Success in Blockchain Projects

Blockchain is the next big thing for middleware! There is no question around this. You need to interconnect other applications, microservices and cloud offerings with a blockchain infrastructure to get real value out of it. In addition, visual analytics and machine learning have to be leveraged to find insights and patterns in blockchain and non-blockchain data. Finally, streaming analytics is used to apply these insights and patterns to new events in a blockchain infrastructure. There is a variety of use cases like fraud detection, compliance issues, optimization of manufacturing or supply chain processes, or any kind of scenarios with the Internet of Things (IoT).

Reference Architecture for Blockchain and Middleware

Variety of Blockchain Platforms including Hyperledger and Ethereum

The blockchain market is growing significantly these days. You need to think about various blockchain characteristics for your next blockchain project.

  • Who are the users of the blockchain? Is it public or private? Which partners do you need to work with?
  • Do you want to build your own blockchain infrastructure (based on a framework such as Hyperledger and one if its implementations like IBM’s Hyperledger Fabric, Iroha, Intel’s Sawtooth Lake) or leverage an existing platform (like Ethereum)?
  • Do you want to host the infrastructure yourself or leverage a cloud service like IBM’s Bluemix with focus on Hyperledger or Microsoft’ Azure with focus on Ethereum?
  • What development environment and tooling do you want to use (like Truffle or BlockApps on top of Ethereum)
  • Which characteristics are important for your scenario? What about speed, security, consensus algorithms, integration of non-blockchain services, and other important aspects? Maybe an add-on on top of a blockchain is needed, like the Raiden Network to leverage off-chain state networks to extend Ethereum with some nice properties like scalability or high performance for asset transfers?
  • Or do you want to focus on a industry-specific blockchain solution like R3 Corda or Ripple for financial services?
  • What middleware do you need? Do you need Application Integration or API Management to interconnect everything? Visual Analytics to find insights and patterns in historical blockchain data? Streaming Analytics to apply rules to action in (near) real time for new blockchain events?

The following shows how to leverage Streaming Analytics together with blockchain events. This example uses TIBCO StreamBase in conjunction with the public Ethereum test network. Note that similar scenarios can be build with any other blockchain infrastructure. A follow-up post about how to leverage middleware with Hyperledger will come soon, too.

Streaming Analytics for Correlation of Blockchain and Non-Blockchain Events

The scenario uses a Smart Contract to define a Coin system. You can mine coins and transfer them to other users (i.e. blockchain addresses). This example is similar to Bitcoin concepts to show how to leverage streaming analytics with any custom blockchain application and smart contracts. The goal is not to show the power of smart contracts (other articles are available for this). The programming language used to develop this Smart Contract is Solidity; more or less the de facto standard to write smart contracts for Ethereum.

Here is the Smart Contract built and deployed with Browser Solidity:

Smart Contract ‘Coin’ developed and deployed with Browser Solidity

MetaMask, a bridge to run Ethereum dApps in your Chrome browser, is running in the background to connect to the Ethereum network and commit the transactions developed with Browser Solidity. You could also use Streaming Analytics to deploy smart contracts, of course. However, in this example TIBCO StreamBase was only used for the following two parts:

  • Receive new events from the blockchain network: You can filter, aggregate, analyse or transform any events like pending transactions, logs or blockchain blocks – and also combine this information with non-blockchain events, of course. For example, you could build a streaming analytics process to analyze just the logs relevant for your specific transaction IDs to spot issues and act proactively, let’s say if a pending transaction takes too long or fails.
  • Execute transactions on the blockchain network via smart contracts: You can mine new coins, send coins to other blockchain addresses and also check the balance of an address. Anything what the smart contract allows can be included into the streaming analytics process.

The streaming analytics process monitors all Ethereum events continuously. This is not as trivial as you might know it from classical messaging systems. You cannot just listen to a topic or queue, but you have to pull information out of the blockchain. Depending on the use case, you have to implement some solution which solves your problem but also does not consume too many resources. This is always a trade-off, which has to be thought through when building your streaming analytics process. This also highly depends on the blockchain infrastructure you use and its feature set.

Please note that security considerations are not part of this example. In the real world, you would integrate encryption and other security requirements into the streaming process, of course. In this demo, we use “hardcoded” private keys for sending transactions. A no-go in a real world project.

Let’s now take a look at an implementation of this process.

TIBCO StreamBase + Ethereum Blockchain

Here is the demo setup:

Architecture with TIBCO StreamBase + Ethereum Blockchain

The Ethereum test network is a distributed peer to peer ledger. It runs on various Ethereum clients. We used one of the most mature ones on our local laptop: The geth client implement in Golang. This is synced and also part of the Ethereum test network.

TIBCO StreamBase is used to build the streaming analytics process:

TIBCO StreamBase Connectors for Ethereum

The web3j Java API is used to connect TIBCO StreamBase with the Ethereum network through our local geth client. You just need to write the connector once and can reuse it in all your streaming processes via drag&drop and configuration. These behave “just” like any other connector (such as messaging via MQTT or Apache Kafka)  and components to build streaming logic (like filter, aggregate or transform).

For more details, please check out my live demo of combining streaming analytics and Ethereum blockchain

Building this process was actually a pretty easy task with TIBCO StreamBase. In the same way, you can build much more sophisticated blockchain processes in your real world project. Let’s also think about some other next steps.

Next Steps: Application Integration, API Management, Machine Learning, and more

A real world blockchain projects needs streaming analytics to correlate blockchain and non-blockchain events to fight fraud or compliance issues, to improve efficiency in manufacturing or supply chain processes, to combine Internet of Things with blockchain infrastructures, and for many other use cases.

Though, Streaming Analytics is just one piece of the puzzle. Here are some more thoughts about why you might combine blockchain with middlware and analytics:

  • Live Visualization for Real Time Monitoring and Proactive Actions
  • Cross-Integration with Ethereum and Hyperledger Blockchains
  • Data Discovery for Historical Analysis to Find Insights and Patterns
  • Machine Learning to Build of Analytic Models
  • Application Integration with other Applications (Legacy, Cloud Services, …)
  • API Management to expose blockchain services and handle caching / throttling challenges
  • Native Hardware Integration with Internet of Things Devices

I will do more posts about these ideas and show more live demos in the next weeks and months. In the meantime, first customer projects also kicked off, already. Blockchain and middleware have a great and interesting future…

Keywords:

Blockchain, Ethereum, Hyperledger, Middleware, Integration, Streaming Analytics, TIBCO, StreamBase, Live Datamart, Smart Contracts, Cloud, web3j

An overview of the blockchain universe

The blockchain universe is evolving very fast. New products and platforms are announced daily. This post should help you to get a rough overview about the existing blockchain technologies.

wich BC.001

I categorize the blockchain technologies into 3 tiers:

tier 1The market leaders.Bitcoin, Ripple, Ethereum
tier 2The challengers, upcoming blockchains where we see the potential to reach tier 1 during the next 6 month.Hyperledger, Quorum, Stellar
tier 3Promissing technololgies and conceptsMonero, Corda

 

Tier 1:

Namebitcoin
Linkshttps://bitcoin.org
https://blockchain.info
https://github.com/bitcoinbook
Main application areavalue transfer, crypto-currency
Characteristicsstable, secure
Consensusproof of work
Governanceopen source, 5 committers, non commercial
DescriptionBitcoin is the first blockchain implementation. The network has started in 2009 and the consensus mechanism has not been hacked yet, despite countless attacks. Bitcoin does not support smart contracts like Ethereum do, however, it offers limited scripting possibilities, which haven been applied in various Bitcoin extensions (e.g. Coloured Coins).

Very often we hear the criticism about performance of the Bitcoin blockchain, the lightning networks shows a possible solution.

In any case, everyone new to blockchain should put his hands on bitcoin and try it at least. The book of Andreas Antonopoulos gives a good introduction to it.
NameRipple
Main application areacurrency independent money and security exchange
Links https://ripple.com/
https://github.com/ripple/rippled
Characteristicsfast
Consensusprobabilistic voting consensus
Governanceopen source managed by Ripple Labs
DescriptionThe ripple concept is based on IOUs and trust relations between network participants. For instance, if a person B trusts that a person A will pay his debts, and C trusts that B will be paying his debts, A will be able to send money to C by introducing following debts (IOUs): 1) A owes money to B, 2) B owes money to C. The network is only managing the ledger of IOUs, the concrete payment is done outside of the network. Moreover, Ripple offers a FX market for transferring between currencies. The FX is offered directly by Ripple. The idea of the systems is, to always use the cheapest liquidity provider.

Ripple is used by several banks as an alternative for the classic correspondent bank based international money transfer. The implementations I looked at still look experimental.
NameEthereum
Linkshttps://www.ethereum.org
Main application areaprogrammable blockchain (smart contracts)
Characteristicsflexible smart contract implementation
ConsensusProof of Work, Proof of Stake in preparation
Governanceopen source, maintained by a foundation
DescriptionEthereum is the leading smart contract platform with a turing completed virtual machine. This means that you can implement every kind of algorithm in this smart contract. If you hear the first time about smart contract concepts, it's a little bit complicated to understand the universal power of this kind of tool. The members of the foundation call it the “world computer”. If you think of the bitcoin blockchain as a large distributed Excel spread sheet, Ethereum would be like having the ability to script every single cell of your spread sheet. Disadvantage of this flexibility is that Ethereum has a large attack surface as we already experienced by recent attack. The good news is that the consensus algorithm didn't fail yet at any point in time.

It is not recommended to implement complex algorithms in Ethereum. Every execution step costs a predefined amount of gas and is much more expensive than the cost of your own CPU at home. It is easy to prototype your own ideas with Ethereum.

 

Tier 2

NameHyperledger
Interesting linkshttps://www.hyperledger.org/
http://www.ibm.com/blockchain/
Main application areano specific
Characteristicsblockchain tool box
Gouvernanceopen source, Linux Foundation
DescriptionHyperledger is not a public Blockchain like Ethereum or Bitcoin, it is more an blockchain building kit under the roof of the linux foundation. The focus of this tool box is building business blockchain apps in private networks. The most active participant seems to be the IBM, they offer also a lot of useful services and extensions around Hyperledger. The IBM bluemix cloud services offers a low entrance level to the technology.
The tool box concepts makes it little bit complicated to define the main characteristics of hyperledger, because you can implement a lot of different kind of distributed ledgers or blockchains.
NameStellar
Interesting linksstellar.org
Main application areacurrency independent money and security exchange
Characteristicsfast
ConsensusStellar Consensus Protocol
Gouvernanceopen source, stellar.org, nonprofit
DescriptionStellar started as a fork of the ripple network. If you look from a distance to both networks you see parallels in the functionality and features. The participance of the stellar network should be individuals, ripple focuses on institutional partners. The consensus algorithm was also changed in the stellar implementation. Stellar could also become a SWIFT competitor like ripple.
NameQuorum
Linkshttps://www.jpmorgan.com/country/US/en/Quorum
https://github.com/jpmorganchase/quorum
Main application areaprivate blockchain for business apps
Characteristicstrust, speed
Consensusmajority voting
Gouvernanceopen source, JP Morgan
DescriptionQuorum is the shooting star of the last months. JPM extended Ethereum with privacy and a voting consensus mechanism. These two extensions match the requirements in the financial industry pretty well. I am excited to see what will happened with this technology in the next months. Most probably, JPM will come up with new business applications and processes based on their new platform.

 

Tier 3

NameCorda
Interesting linkshttps://www.corda.net/
Main application areaFocus on banking applications
Characteristicsno blockchain, just distributed ledger technology
Gouvernanceopen source, Linux Foundation
DescriptionCorda is not really a blockchain it is a distributed ledger system. It comes from the R3 consortiums. R3 started noisy, now first members already left the group. Corda moved under the hyperledger project umbrella, at the moment Hyperledger and Corda are not technical connected, some function exists in both tool boxes in different implementations.
The focus of corda is to become a distributed backend database for the banking industry. Today in the institutes you find different IT systems which are loose coupled by enterprise bus systems. The vision of Corda is, to bring this systems to the same distributed database. From my point of view it is a nice vision from a childlike architecture view, but it will not be realistic. I think the technology can be used to realize a new class of distributed backend systems, like distributed Master Data Management or distributed Business Process Management systems in decentral organized enterprise structures.
NameMonero
Interesting linkshttps://getmonero.org
Main application areaexchanging coins
Characteristicsanonymization
Consensusproof of work
Gouvernanceopen source
DescriptionMonero's focus is on exchanging the Monero coin. The anonymization level is much higher the in the most other crypto currencies. This could also be useful for legal usage. The ideas behind this crypto are similar to bitcoin, but it’s completely new coded. Monero uses an own protocol which is different to all other blockchain implementations. It’s also not possible to see inside the blockchain without the private key or a special view key. This feature enables also an absolutely private communication between the participants. The transactions will also be splintered and merged, so it is not possible to reproduce a single transaction again.

In general, blockchain is a new technology, using it will feel experimental. You’ll have all problems you can get with new technologies in early stages.

In this post we have not discussed all the tokens based of Ethereum. This would be a good content for a follow-up article. 

A generic “Claim and Endorse” Contract

Did you already endorse someone at LinkedIn? For instance, someone claims that he knows C++ and you endorse this claim because you know it’s true.

A large number of processes can be modelled in this way:

A simple Solidity contract for managing claims and endorsements could look like below.

contract ClaimAndEndorse {
struct ENDORSEMENT {
uint creationTime;
}

struct CLAIM {
uint creationTime;
uint claimHash;
mapping (address => ENDORSEMENT) endorsements;
}

mapping (address =>
mapping (uint /* CLAIM GUID */ => CLAIM)) claims;

function setClaim(uint claimGuid, uint claimHash) {
CLAIM c = claims[msg.sender][claimGuid];
if(c.claimHash > 0) throw; // unset first!
c.creationTime = now;
c.claimHash = claimHash;
}

function unsetClaim(uint claimGuid) {
delete claims[msg.sender][claimGuid];
}

function setEndorsement(
address claimer, uint claimGuid, uint expectedClaimHash
) {
CLAIM c = claims[claimer][claimGuid];
if(c.claimHash != expectedClaimHash) throw;
ENDORSEMENT e = c.endorsements[msg.sender];
e.creationTime = now;
}

function unsetEndorsement(address claimer, uint claimGuid) {
delete claims[claimer][claimGuid]
.endorsements[msg.sender];
}

function checkClaim(
address claimer, uint claimGuid, uint expectedClaimHash
) constant returns (bool) {
return claims[claimer][claimGuid].claimHash
== expectedClaimHash;
}

function checkEndorsement(
address claimer, uint claimGuid, address endorsedBy
) constant returns (bool) {
return claims[claimer][claimGuid]
.endorsements[endorsedBy].creationTime > 0;
}
}

The fantastic thing about this very simple contract is that we now can answer the following question:

Who claims what and who endorses it?

Usecase – Skill/Degree Endorsements

John claims that he holds a PhD in computer science at the Stanford university.

contract.setClaim(
3000010 /* GUID for PhD in CS */,
HASH("PhD in Computer Science at Stanford University"))

The Stanford university confirms this fact.

contract.setEndorsement(JOHN, 3000010)
Usecase – Identity Verification

Step 1. John claims facts about his personal data by binding hashes to his ethereum address. The corresponding pseudo code is:

// RND is a random sequence introduced for making it impossible to restore the initial data from the hash by brute force lookups.

contract.setClaim(1000010 /*guid firstname*/,
HASH("John"+RND))

contract.setClaim(1000011 /*guid surename */,
HASH("Smith"+RND))

contract.setClaim(1000012 /*guid bday */,
HASH("1965-01-01"+RND))

contract.setClaim(1000013 /*gender */,
HASH("m"+RND"))

Step 2. John visits his bank, which endorses these facts about his identity:

contract.setEndorsement(JOHN, 1000010 /*guid firstname*/);
contract.setEndorsement(JOHN, 1000011 /*guid surename */);
contract.setEndorsement(JOHN, 1000012 /*guid bday */);
contract.setEndorsement(JOHN, 1000013 /*guid gender */);

Now consider that JOHN wants to open A) an  account at ACME Inc, B) buy alcohol in the bar and C) register at a dating site. If all three trust John’s bank, he’ll be able to digitally prove his claims on his personal data. Moreover, he only needs to present the relevant pieces of data. For instance at the bar, he only has to prove the claim that he’s older than 18.

Related: ShoCard, uPort 

Usecase – Approving existence of documents

ACME Inc. wants to publish a new financial product. The hashes of the required documents are stored on the blockchain. The authorities and the exchanges are confirming the existence and the correctness of these documents.

Related: Luxembourg Stock Exchange OAM

Usecase – Managing Memberships

John wants to become a member in his local bowling club. He stores this fact on the blockchain and the club confirms this fact. With the first step, John manifests his will to enter the club. In the second step, the club confirms that they are accepting John as a member.

Try it yourself on Ropsten Testnet

https://testnet.etherscan.io/address/0x65ec6e00e336a96972987ee25386a3090f38a27d#code

 

Rebuilding Ripple on Ethereum

Ripple is a P2P payment network with an integrated foreign exchange market. It supports any possible currency. In it’s core it is based on a public distributed ledger containing liabilities between individuals and organisations (IOUs). The network depends on the trust relations between its members. Transferring a value within the network between A and B requires a direct or indirect path in this web of trust. Moreover, the ledger  contains a distributed foreign exchange market, which makes it possible to convert between currencies in real-time.

In this blog post, I want to sketch how a Ripple-like implementation could look like in Ethereum.

Asset Contract

First of all we need a contract to represent an asset that network participants can agree on. This could be a fiat or a crypto currency, but it also could be bonus miles, loyalty points or similar.

contract Asset {
string public description;
string public id;
uint public decimalUnits;

mapping (address => bool) public accepted;

function Asset(string _description, string _id, uint _decimalUnits) {
description = _description;
id = _id;
decimalUnits = _decimalUnits;
}

function accept() {
accepted[msg.sender] = true;
}

function reject() {
delete accepted[msg.sender];
}
}

An asset has a description, an id, and how many decimal units are used. For instance, we would model US Dollar and European Euro as:

Asset USD = new Asset("USD Currency", "USD", 2)
Asset EUR = new Asset("EUR Currency", "EUR", 2)

With the accept function, network participants are agreeing upon a specific Asset instance. Network participants can only use assets that they have accepted.

EthRipple Contract

data model

After defining the Asset contract, we can now specify the data model for the EthRipple contract itself. We’ll need the following model elements:

ACCOUNT

Every participant in the network needs an ACCOUNT struct storing his ASSETs. The assets are identified with their contract addresses.

struct ACCOUNT {
mapping (address /* of an Asset */ => ASSET) assets;
}

mapping (address => ACCOUNT) accounts;
ASSET

An ASSET consists of all IOUs that a participant holds and of all his asset exchange offers (XCHG).

struct ASSET {
mapping (address => IOU) ious;
mapping (address /* of an target Asset */ => XCHG) xchgs;
}

xchgs – Offers for exchanging this asset for another asset.
ious – list of debtors for this asset.

IOU – “I owe you”
struct IOU {
uint amountOwed;
uint maxAllowed;
}

The IOU struct describes how much of a specific asset (e.g. USD) a debtor owes to the lender (amountOwed). Moreover, it describes how much a lender trusts that a potential debtor is going to pay him back (maxAllowed). During a transfer, amountOwed will always be less than or equal to maxAllowed.

E.g.:

IOU iou = accounts[JOHN].assets[EUR].ious[ANDY];
iou.maxAllowed = 100;
iou.amountOwed = 10;

iou.maxAllowed = 100 – JOHN trusts ANDY that he’ll pay his debts up to 100 units of the EUR asset.

iou.amountOwed = 10 – currently ANDY owes to JOHN 10 units of the EUR asset.

XCHG – Asset Exchange
struct XCHG {
uint validUntil;
uint exchangeRateInMillionth;
}

This struct represents the offer to exchange an Asset for another Asset at a specific exchangeRate which is equal to exchangeRateInMillionth/1,000,000. Note that here we have to work with unsigned integers since Ethereum’s Solidity Compiler has no support for decimals yet. validUntil is used to limit an offer to a specific period of time.

E.g.

XCHG xchg = accounts[JOHN].assets[EUR].xchgs[USD];
xchg.exchangeRateInMillionth = 1100000;

xchg.exchangeRateInMillionth = 1100000 – JOHN offers to exchange EUR for USD at a rate of 1100000/1000000 (1,10).

Operations

The minimal interface for the contract offers methods to modify IOUs and asset exchange offers. And finally, there is a ripple method for sending assets through the web of trust to a specific destination. Note that sending a value in this case means changing the IOU records along the path in the web of trust. If required, the sent asset can also be exchanged for another asset (e.g. converting EUR to USD).

 function modifyIOU(address debtor,
Asset asset,
uint newAmountOwed,
uint newMaxAllowed);

function modifyXCHG(Asset fromAsset,
Asset toAsset,
uint exchangeRateInMillionth,
uint validUntil);

function ripple(address[] chain,
Asset[] assetFlow,
uint amount);

function modifyIOU(address debtor, Asset asset, uint newAmountOwed, uint newMaxAllowed) – with this function the msg.sender can reduce the amount owed by a debtor or he can change the maxAllowed amount for this asset/debtor. The amountOwned can only be reduced, never increased.

function modifyXCHG(Asset fromAsset, Asset toAsset, uint exchangeRateInMillionth, uint validUntil) – with this function the msg.sender can publish new offers for converting fromAsset to toAsset at an exchangeRate which is exchangeRateInMillionth/1000000.

function ripple(address[] chain, Asset[] assetFlow, uint amount) – this function is the main workhorse. It allows the msg.sender to transfer an asset to a destination address, which is reachable within the web of trust that is encoded via IOU relations.

Considering the relations below, JOHN can send money to ALEX via ANDY.

// JOHN and ANDY trust each other that they'll be paying their debts up to 1000 units of the EUR asset.
accounts[JOHN].assets[EUR].ious[ANDY].maxAllowed = 1000;
accounts[ANDY].assets[EUR].ious[JOHN].maxAllowed = 1000;

// same for ANDY and ALEX
accounts[ANDY].assets[EUR].ious[ALEX].maxAllowed = 1000;
accounts[ALEX].assets[USD].ious[ALEX].maxAllowed = 1000;

If JOHN want to send 10 units of the EUR asset to ALEX, he would call the ripple function like this

ripple([JOHN, ANDY, ALEX], [EUR, EUR], 10) 

The second array parameter means that JOHN is transferring EUR to ANDY and that ANDY is also transferring  EUR to ALEX. There is no conversion between assets. After the transaction has been committed to the blockchain, we would see the following changes in the IOU records.

// JOHN and ANDY trust each other that they'll be paying their debts up to 1000 units of the EUR asset.
accounts[ANDY].assets[EUR].ious[JOHN].amountOwed = 10;
accounts[ALEX].assets[EUR].ious[ANDY].amountOwed = 10;

If JOHN wants to send EUR, but ALEX wants to receive USD, the transfer would work if ANDY would have an active asset exchange offer for exchanging EUR to USD. Moreover, there also has to be an established trust relation between ANDY and ALEX for the USD asset.

The function call would be:

ripple([JOHN, ANDY, ALEX], [EUR, USD], 10) 

Note that the path within the web of trust is calculated off-chain and passed as input to the ripple function. There is no need to do this expensive calculation on-chain.

Try it yourself

I deployed this contract on the Morden Testnet. Feel free to try it yourself.

Contract Addresses

EUR Asset 0x110c1b256c180ddBBFF384cA553Bf7683Ce8a02c
USD Asset 0xFa33639783B5ae93795A4aeCF86985eB95EA0B39
Ripple 0x33f03cea07586f42900fbf46df6a7f596345bec1

Asset Interface

[ { "constant": true, "inputs": [], "name": "decimalUnits", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [], "name": "accept", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [], "name": "reject", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "description", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "id", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "a", "type": "address" } ], "name": "isAcceptedBy", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "type": "function" }, { "inputs": [ { "name": "_description", "type": "string" }, { "name": "_id", "type": "string" }, { "name": "_decimalUnits", "type": "uint256" } ], "type": "constructor" }, { "payable": false, "type": "fallback" } ] 

EthRipple Interface

[ { "constant": false, "inputs": [ { "name": "fromAsset", "type": "address" }, { "name": "toAsset", "type": "address" }, { "name": "exchangeRateInMillionth", "type": "uint256" }, { "name": "validUntil", "type": "uint256" } ], "name": "modifyXCHG", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "fxAddr", "type": "address" }, { "name": "fromAsset", "type": "address" }, { "name": "toAsset", "type": "address" } ], "name": "queryXCHG", "outputs": [ { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "fromAsset", "type": "address" }, { "name": "toAsset", "type": "address" } ], "name": "deleteXCHG", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "debitor", "type": "address" }, { "name": "asset", "type": "address" } ], "name": "deleteIOU", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "lender", "type": "address" }, { "name": "asset", "type": "address" }, { "name": "debitor", "type": "address" } ], "name": "queryIOU", "outputs": [ { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "debitor", "type": "address" }, { "name": "asset", "type": "address" }, { "name": "newAmountOwed", "type": "uint256" }, { "name": "newMaxAllowed", "type": "uint256" } ], "name": "modifyIOU", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "chain", "type": "address[]" }, { "name": "assetFlow", "type": "address[]" }, { "name": "expectedExchangeRateInMillionth", "type": "uint256[]" }, { "name": "amount", "type": "uint256" } ], "name": "ripple", "outputs": [], "payable": false, "type": "function" }, { "inputs": [], "type": "constructor" }, { "payable": false, "type": "fallback" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "lender", "type": "address" }, { "indexed": false, "name": "debitor", "type": "address" }, { "indexed": false, "name": "asset", "type": "address" }, { "indexed": false, "name": "newCurrent", "type": "uint256" }, { "indexed": false, "name": "newMax", "type": "uint256" } ], "name": "EventUpdateIOU", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "lender", "type": "address" }, { "indexed": false, "name": "debitor", "type": "address" }, { "indexed": false, "name": "asset", "type": "address" } ], "name": "EventDeleteIOU", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "xchgAddr", "type": "address" }, { "indexed": false, "name": "fromAsset", "type": "address" }, { "indexed": false, "name": "toAsset", "type": "address" }, { "indexed": false, "name": "exchangeRateInMillionth", "type": "uint256" }, { "indexed": false, "name": "validUntil", "type": "uint256" } ], "name": "EventUpdateXCHG", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "xchgAddr", "type": "address" }, { "indexed": false, "name": "fromAsset", "type": "address" }, { "indexed": false, "name": "toAsset", "type": "address" } ], "name": "EventDeleteXCHG", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "xchgAddr", "type": "address" }, { "indexed": false, "name": "fromAsset", "type": "address" }, { "indexed": false, "name": "toAsset", "type": "address" }, { "indexed": false, "name": "exchangeRateInMillionth", "type": "uint256" } ], "name": "EventExecuteXCHG", "type": "event" } ]

 

Full Source Code