# 4 posts tagged with "blockchain"

View All Tags

## Verifying Rust: Exploring Verification Options for Substrate

Security is hard to get right in blockchains. It's even harder to make sure that code is correct while still actively developing the product: code changes are frequent, requirements are changing, and the codebase is growing.

In this post, we'll explore options for verifying blockchain code, specifically for the Substrate blockchain framework to try to verify the code of the Interlay blockchain.

My requirements for the test were simple: the tool should be integrated into the Rust toolchain (no DSLs) and I set myself a time limit of a single day to get started and get a useful result.

Spoiler alert: I managed to get two tools running and produce output. This post covers only the setup and I will follow up with more details in a future post.

## Substrate Runtimes as Verification Targets​

We are building the Interlay and Kintsugi blockchains based on the Rust Substrate framework. For verifying that the "code is correct", we are looking for two targets:

1. Runtime: The WASM runtime encodes the rules of the blockchain subject to consensus verification. This is where we can potentially introduce logical errors in how the protocols are working or in their implementation such that we either impact the safety or liveness of the system.
2. Node Implementation: The node implementation wraps around the runtime. Bugs introduced here can impact the liveness of the system.

## Diving into Verification​

Software verification is most often quite an academic exercise. With the adverse environment of blockchain development, there's a clear benefit of increased security assurance in the software development process. This goes hand in hand with the desire of the verification community to integrate verification into the development process.

I'll not cover the usual testing and fuzzing tools but rather explore the three tools I found most accessible for verification in Rust.

My criteria for selecting tools were:

1. Actively maintained: The tool should be actively maintained and have a community around it. I checked the GitHub repositories for current contributions and when the last commit was made.
2. Clear documentation: The tool should have clear documentation on how to use it and get started. If after 10 minutes of parsing the available documentation, I could not get a good understanding of how to install or use the tool, I would not use it.
3. Rust integration: Since the idea is to integrate the tool into the normal development workflow, I was looking for a tool that integrates well with cargo and also does not require writing verification code in a language other than Rust.

## Selected Tools​

From the tools I found, I selected the following three tools for further exploration:

More tools are available on the Rust Formal Methods Interest Group website and on Alastair Reid's blog.

For all tools, I installed them and ran them without any additional configuration against the chain implementation of the Interlay blockchain.

### A Note on Expectations​

I would be happy if a tool runs on the first try: installing the tool without issues and scanning the code base without setting up verification rules. Overall, the code is well-tested, but it is very complex: more than 1,000 dependencies, almost 100,000 lines of code, and invoking external C libraries.

## kani​

From the developer's website:

Kani is an open-source verification tool that uses model checking to analyze Rust programs. Kani is particularly useful for verifying unsafe code in Rust, where many of the Rust’s usual guarantees are no longer checked by the compiler.

### Getting started​

I found getting started very easy with just two commands to execute:

cargo install --locked kani-verifiercargo kani setup

Next, I ran kani against the runtime of the Interlay blockchain:

# From the interbtc repo rootcargo kani

### Compilation Errors​

That produced the following error during the compilation of the schnorrkel crate:

error: format argument must be a string literal   --> /home/nud3l/.cargo/registry/src/github.com-1ecc6299db9ec823/schnorrkel-0.9.1/src/batch.rs:165:47    |165 |     assert!(hrams.len() == public_keys.len(), ASSERT_MESSAGE);    |                                               ^^^^^^^^^^^^^^    |help: you might be missing a string literal to format with    |165 |     assert!(hrams.len() == public_keys.len(), "{}", ASSERT_MESSAGE);    |                                               +++++

At this point, I wasn't sure how to convince kani to ignore these errors in the dependencies. I tried running kani only on a single crate but it resulted in the same compiler issue.

The authors have a guide on how to get started with real code but it does not include how to handle compiler errors in dependencies.

## Prusti​

From the developer's website:

Prusti is a verification tool for Rust programs. It is based on the Rust compiler and uses the Rust type system to verify Rust programs. Prusti is a research prototype and is not yet ready for production use.

### Getting started​

Getting started with Prusti required downloading the Prusti Assistant VS Code extension. I already had the required Java SDk and rustup versions installed so the process of getting started only involved opening a rust file and hitting the "Verify with Prusti" button on the VS Code status bar.

As the first target, the fee pallet seemed interesting as it's mildly complex, has few dependencies, and with its fixed point math might be subject to issues.

### Errors​

On the first run on the fee crate, Prusti found 358 errors. That seemed quite a lot but after initial inspection, most of the errors were:

• Unsupported features (313 errors): I was expecting Prusti with its current feature set to run into these issues as substrate makes heavy use of macros, traits, and other advanced features of Rust.
• Internal errors (24 errors): Several internal errors occured.
• Unexpected verification error (9 errors): Some verification failed.
• Verification errors (14 errors): These seem to be the ones worth investigating.

### Success​

Prusti found potential overflow and underflow errors in the bitcoin crate:

// bitcoin/src/parser.rsif position + 4 > raw_bytes.len() {    return Err(Error::EndOfFile);}

It also found possible issues with unbounded arrays:

// bitcoin/src/script.rspub fn op_return(return_content: &[u8]) -> Script {    let mut script = Script::new();    script.append(OpCode::OpReturn);    script.append(return_content.len() as u8);    script.append(return_content);    script}

## MIRAI​

From the developer's website:

MIRAI is an abstract interpreter for the Rust compiler's mid-level intermediate representation (MIR). It is intended to become a widely used static analysis tool for Rust.

### Getting started​

Installation of MIRAI was straightforward, following the guide:

git clone https://github.com/facebookexperimental/MIRAI.gitcd MIRAIcargo install --locked --path ./checker

Next, I ran MIRAI in the interbtc root directory.

cargo mirai

### Compilation Errors​

MIRAI produces compilation errors on the wasm builds:

     Compiling wasm-test v1.0.0 (/tmp/.tmpfNz4QS)  error[E0463]: can't find crate for std    |    = note: the wasm32-unknown-unknown target may not be installed    = help: consider downloading the target with rustup target add wasm32-unknown-unknown    = help: consider building the standard library from source with cargo build -Zbuild-std  error: requires sized lang_item  For more information about this error, try rustc --explain E0463.  error: could not compile wasm-test due to 2 previous errors  warning: build failed, waiting for other jobs to finish...  error: cannot find macro println in this scope   --> src/main.rs:3:5    |  3 |                 println!("{}", env!("RUSTC_VERSION"));    |                 ^^^^^^^  error: could not compile wasm-test due to 3 previous errors  ------------------------------------------------------------

### Success​

As the wasm build is done on the entire runtime, I decided to try my luck against a single pallet instead. Similar to before, I tried the fee crate. This worked and to my surprise, MIRAI did not print any warnings or errors.

Next, I tried the bitcoin create that implements parsing and other somewhat error prone code. MIRAI gave me results here:

warning: possible attempt to subtract with overflow   --> crates/bitcoin/src/parser.rs:239:24    |239 |     let target: U256 = parser.parse()?;    |                        ^^^^^^^^^^^^^^    |note: related location   --> crates/bitcoin/src/parser.rs:177:40    |177 |         let (result, bytes_consumed) = T::parse(&self.raw_bytes, self.position)?;    |                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^note: related location   --> crates/bitcoin/src/parser.rs:151:23    |151 |         let compact = U256::set_compact(bits).ok_or(Error::InvalidCompact)?;    |                       ^^^^^^^^^^^^^^^^^^^^^^^note: related location   --> crates/bitcoin/src/math.rs:53:25    |53  |             word << 8 * (size - 3)    |                         ^^^^^^^^^^

## Summary​

Overall, I was very happy with the results. I was able to run two tools against the crates without additional configuration and they found potential issues. Next up will be trying to implement custom verification rules and dive deeper into the identified issues.

## Analyzing Bitcoin smart contracts from a mechanism design perspective

Contracts can be used to enforce agreements between entities. To this extent, smart contracts have been proposed by Nick Szabo and implemented for example in Bitcoin. This article covers the basics of mechanism design of smart contracts in the context of Bitcoin. Mechanism design is concerned with creating or encoding preferences in an agreement. Hence, an author of a smart contract can create a mechanism that enforces certain behaviour of the agents (or humans) interacting with the contract. Essentially, the author of the contract wants to reward desired behaviours and punish undesired behaviours. This is widely used in cryptocurrency protocols including the Lightning Network or Ethereum-based protocols such as Casper or TrueBit.

Use Case: Agents having access to sensors could sell the sensor data they are collecting to agents willing to buy this data. This represents a simple contract where a resource is exchanged for a price. Bitcoin in combination with payment channels secure the payments and allow for micro-payments. Thus, one has to design protocols integrating with these existing technologies to achieve for example secure decentralised data exchanges.

## Bitcoin and smart contracts​

Nakamoto introduced Bitcoin as a way to send money between peers without trusted third parties [2]. In Nakamoto consensus the heaviest chain is considered having correct transactions as most miners have contributed to this specific chain by solving a proof of work (PoW) puzzle. Assuming that the majority of players in the system are honest (i.e. $50\% + 1$), the heaviest chain represents the "true" state of the network.

Bitcoin also included the capability of executing smart contracts with Bitcoin Script [3]. A smart contract is a piece of software which formalises a relationship between entities much like a legal contract [4]. However, the idea is to use secure computer protocols and include game theoretic elements to cover aspects that cannot be adequately verified in the protocol. Szabo argues that smart contracts cover interactions including search, negotiation, commitment, performance, and adjudication.

## Rational agents​

Agents in decentralised systems are self-interested [5]. Hence, protocols facilitating (economic) interactions between agents need to account for autonomous agents to behave rationally. A set of agents $P = \{1 ... n\}$ is considered to be rational if they seek maximise their utility $u_i$ depending on some function [5] [6] [1]. This is especially relevant in decentralised systems, where we have to assume agents act only in their interest. Agents can apply multiple strategies $s \in S$ within a negotiation [1]. We have to assume that agents will execute actions $\theta \in \Theta$ based on $s$ that optimises their utility including cheating, lying, breaking contracts, and hiding their intentions. However, we also assume that agents that interact can find an outcome $\omega \in \Omega$ that increases or optimises $u_i$.

## Mechanism design​

Mechanism design is used to encode preferences in an agreement. Essentially, a "designer" defines a preferred social choice which, under the assumption of rational agents, the mechanism is intended to favour [6]. Considering a contract $C$ as an agreement between agents, $C$ implements a mechanism $M = (\Sigma, g)$ [7]. The outcome of the mechanism $g$ depends on the actions of agents $\Sigma$. $M$ implements a rule $f$. Rational agents would only enter $C$ or follow $C$ if $f$ is the result of the dominant strategies or Nash equilibrium of the agents.

An agent will have multiple options to enter contracts with other agents. To ensure that the proposed contract $C$ is chosen, we want to have it incentive compatible. Loosely speaking incentive compatibility of a mechanism occurs when the utility $u_i$ of each agent $i$ is maximised when an agent is "truth-telling" (i.e. the dominant strategy). In games without money, non-trivial choices (e.g. more than two contracts, multiple potential agents, multiple different terms) lead either to incentive incompatibility, or the social choice function is a dictatorship according to the Gibbard--Satterthwaite theorem. However, in Bitcoin, we can construct games with money.

## Games in Bitcoin​

In games with money, a Vickery-Clarke-Groves (VCG) mechanism maximises social welfare. A VCG mechanism is incentive compatible. Hence an agent strives to implement a contract as such a mechanism. To construct such games the mechanism the Clarke pivot rule can be applied [6]. Agents in Bitcoin are playing a game with strict incomplete information. One could argue that an agent could potentially analyse actions of an agent as transactions are public. However, as agents might take multiple identities (Sybil), this is a non-trivial task, and thus, we will not consider it in this case. We further assume that agents have independent private values, i.e. resources subject to trade do not depend on the other agents.

Such a game can be defined as follows [6]:

• A set of players $P = \{1, .., n\}$ exists.
• Every player $i$ has a set of actions $\Sigma_i$.
• Every player $i$ has a set of types $T_i$. A value $t_i \in T_i$ is a private input to the player.
• Every player $i$ has a utility function $u_i$. The utility function depends on its private input and the actions of all players $u_i = (t_i, \sigma_1, .., \sigma_n)$.

Hence, a player must choose an action only based on his private input but without knowing the private inputs of other agents. A strategy $s$ describes an agent's decision to execute a specific action based on a private input. The agent will choose $s$ that is the best response to any $\sigma$ by other agents.

However, an agent needs to optimise a specific social choice. In Bitcoin, we are not concerned with social welfare as a social choice as this is unknown to the agents and they are not naturally interested in the utility of others. In the case that only two agents are involved and we have a simple contract concerning one resource, single-parameter domains can be applied [6]. In such domains, the valuation $v_i$ of an agent depends only on one parameter, say obtaining the resource. Moreover, the price an agent is willing to pay is already included in the incentive mechanism.

Yet, this would only hold for the case where two agents compete for obtaining a single resource. In more complex cases, for example, adding the quality of the data, we need to apply a more complex social choice function. In these cases, variations of VCG are the only incentive compatible mechanisms [6].

## Assumptions​

Using the resource exchange formalisation described in [1] the following tuple defines the exchange setting:

$(P,\mathcal{Z}, (v_{i})_{i \in P})$

We are assuming that two agents exist, i.e. two players $P = \{A, B\}$. Those agents are exchanging a purely digital resource for a specific price. The agents negotiate over a single resource $z \in \mathcal{Z}$. Moreover, they use a valuation function $v_i : 2^{\mathcal{Z}} \to \mathbb{R}$. Agent $A$ hence defines the value $v_A(z)$ individually as well as agent $B$ in $v_B(z)$.

This valuation expresses the price an agent is willing to exchange the resource for, whereby we assume that $v_A \leq v_B$ if $A$ is offering the resource and $B$, is willing to pay for it. Otherwise, there would be no price for them agree on. In this simple case, we assume that the agents follow the negotiation protocol truthfully and that their utility $U$ increases when making a deal and exchanging the resource. We further assume that the agents have a way to enter such an agreement, i.e. one of them can prepare a contract that the other one can interpret and willing to commit to.

## Contract​

The contract $C$ is implemented as an Hashed Timelock Contract (HTLC) [8] with multiple transactions in the Lightning Network. Note that $A$ sells data $z$, and $B$ buys it for the agreed price $p$ in Satoshi. To allow agents to exchange $z$ and atomic swap is used. This protocol has been described for cross-chain transactions but is equally useful within a single chain [9].

1. $A$ stores $z$ on IPFS receiving $H(z)$. $A$ uses this as the secret for the HTLC and sends this to $B$. As $A$ takes the Merkle root of $z$, the data can be of (almost) any size.
2. $B$ prepares a transaction transferring $p$ to $A$ spendable with the signature of $A$. Also, $B$ includes the spending condition $H(input) == H(z)$ based on the IPFS hash of the file. $B$ is also setting a time $t$ after which the transaction must be spent, otherwise, $B$ can redeem the locked funds. Last, $B$ sends the transaction to $A$ to sign it.
3. $A$ signs the transaction to agree to the trade and commits it to the channel.
4. $A$ reveals the $H(z)$ to issue the payment, which gives $B$ $H(z)$. $B$ obtains $z$ through IPFS.

This contract allowed an atomic swap of the file without the need to upload the file to Bitcoin. It requires both agents to be online which is a reasonable assumption for autonomous agents. The protocol does not handle the security of the file. Any party observing $H(z)$ can access $z$ without paying any price. Hence, the protocol could be extended using GPG or other asymmetric encryption schemes. In that case, $A$ could take $B$'s public RSA key to encrypt $z$ and then store it on IPFS. This would allow private trading of the file.

## Mechanism analysis​

Players: $A$ and $B$ are the only players in the game. They have the same capabilities and pre-contract the same norms. Post-contract one agent has the obligation to pay for $z$ and the other has an obligation to provide $z$. The contract is atomic. Hence, payment and delivery occur at the same time. However, there is a possible weakness in the contract. If $A$ reveals $H(z)$ without having the file stored on IPFS any more, $B$ will not be able to retrieve the file.

Types: Both players have a valuation $v(z)$. $A$ has private access to $z$.

Strategy: $A$ has three actions: not reveal $H(z)$, reveal $H(z)$ and have $z$ accessible, and reveal $H(z)$ and have $z$ inaccessible. $B$ has two actions: prepare HTLC with a payment $p$ for $A$ or not. Assuming $B$'s valuation of $v_B(z) > 0$, $B$ will propose a minimum payment. Since there is no proof of $z$ being available and the desired resource, $B$ has to account for this risk. The protocol could be improved by using concepts such as proof of replication [10]. $A$ will only consider revealing $H(z)$ in the proposed HTLC if $p \geq v_A(z)$. Moreover, $A$ might cheat $B$ by not making $z$ available. In case $A$ expects future trades with $B$, it has a motivation to actually provide $z$. $B$ might promise a higher pay for future interactions and adjust his valuation function to the resource $z$ provided by $A$ to a higher value since $A$ is based on previous direct experience trusted.

Utility: Utilities depend on the combination of strategies.

• $B$ proposes HTLC with payment $p$ and $A$ reveals $H(z)$ with $z$ available: $u_A = p - v_A(z)$ and $u_B = v_B(z) - p$. Under the assumption that $A$ does not loose anything from selling $z$.
• $B$ proposes HTLC with payment $p$ and $A$ reveals $H(z)$ with $z$ unavailable: $u_A = p - v_A(z)$ and $u_B = 0 - p$.
• $B$ proposes HTLC with payment $p$ and $A$ does not reveal $H(z)$: $u_A = 0$ and $u_B = 0$.
• $B$ does not propose HTLC: $u_A = 0$ and $u_B = 0$.

Social choice: Since $B$ proposes the contract, $B$ can set the social choice function. In this case, a single parameter domain is useful. The utility analysis shows that $p$ has the condition $v_A(z) \leq p \leq v_B(z)$. Since $B$ is not able to be sure that $z$ is available, $p$ will be low in the first tries as $B$ tries to manage his risk exposure. However, $B$ could argue that $A$ might be interested in future trades and include this as part of his utility function as an expected value. Hence, $B$ would only propose a contract if $p << v_B(z)$ since otherwise the risk is too high.

## References​

[1] S. Fatima, S. Kraus, and M. Wooldridge, Principles of Automated Negotiation. Cambridge: Cambridge University Press, 2014 [Online]. Available: http://ebooks.cambridge.org/ref/id/CBO9780511751691

[2] S. Nakamoto, "Bitcoin: A peer-to-peer electronic cash system," 2008.

[3] Bitcoin Wiki, "Script." 2018 [Online]. Available: https://en.bitcoin.it/wiki/Script{\#}Opcodes. [Accessed: 27-Jun-2018]

[4] N. Szabo, "Formalizing and Securing Relationships on Public Networks." 1997 [Online]. Available: http://ojphi.org/ojs/index.php/fm/article/view/548/469. [Accessed: 07-Apr-2017]

[5] T. W. Sandholm and V. R. Lesser, "Leveled Commitment Contracts and Strategic Breach," Games and Economic Behavior, vol. 35, nos. 1-2, pp. 212--270, 2001.

[6] N. Nisan, T. Roughgarden, E. Tardos, and V. V. Vazirani, Algorithmic Game Theory, vol. 1. Cambridge: Cambridge University Press, 2007, pp. 1--754 [Online]. Available: [http://portal.acm.org/citation.cfm?doid=1785414.1785439 http://ebooks.cambridge.org/ref/id/CBO9780511800481](http://portal.acm.org/citation.cfm?doid=1785414.1785439 http://ebooks.cambridge.org/ref/id/CBO9780511800481)

[7] N. Nisan and A. Ronen, "Algorithmic Mechanism Design," Games and Economic Behavior, vol. 35, nos. 1-2, pp. 166--196, Apr. 2001 [Online]. Available: http://linkinghub.elsevier.com/retrieve/pii/S089982569990790X

[8] Bitcoin Wiki, "Hashed Timelock Contracts." 2018 [Online]. Available: https://en.bitcoin.it/wiki/Hashed{\_}Timelock{\_}Contracts. [Accessed: 28-Jun-2018]

[9] I. Bentov et al., "Tesseract: Real-Time Cryptocurrency Exchange using Trusted Hardware," 2017 [Online]. Available: http://www.cs.cornell.edu/{~}iddo/RTExchSGX.pdf

[10] A. Juels and B. Kaliski Jr., "Pors: Proofs of retrievability for large files," Proceedings of the ACM Conference on Computer and Communications Security, pp. 584--597, 2007 [Online]. Available: http://www.scopus.com/inward/record.url?eid=2-s2.0-74049101079{\&}partnerID=40{\&}md5=83cf075b3704d4fe5bfb2ccf38c39362

## Integrating Python and Ethereum

In Ethereum and other blockchains there are still a lot of proof of concept implementation and developers trying out how to cope with the new concepts. As part of the dInvest post series I was also looking into Ethereum and trying to implement a hedge fund in a blockchain. In a previous post I discussed how to get a quantitative framework in python up and running. In this post I will write how to integrate python programs with Ethereum smart contracts. For one reason or another you might be also faced with the issue, that although Ethereum offers a Turing-complete language not everything is actually doable there.

Let's say you have created one of the simple tutorial contracts in Ethereum and now want to look at something more advanced. I personally liked the Hitchhiker's Guide to Smart Contracts by Manuel Aráoz to get started with more complex code, setup testrpc, and truffle. Take a look at it.

## dInvest smart contract​

dInvest is composed of one smart contract that is responsible for making investments, verifying investment criteria and distribution of returns. The contract exposes public functions to create new investments and for withdrawal which will act as main functions of a hedge fund. Users of the hedge fund are identified by their Ethereum address which is equivalent for the public key. Suggestion of investment strategies and strategy execution are done in different agents that also have Ethereum addresses. These agents are set by the contract creator only. When a user is creating an investment it is possible to specify a list of industry sectors identified by a two digit number based on the Standard Industrial Classification codes. These sectors will be identified as a black list when making the investments. Therefore user have the ability control the sectors which the hedge fund will invest on.

The contract can be found in the GitHub repo.

## Interaction with smart contracts​

To interact with smart contracts, there are a couple of option including RPC or a JavaScript API. I found the easiest way to interact with Ethereum smart contracts from other programs (like python programs) was using their web3 JavaScript API. As the majority of dInvest is written in python, I wanted to stick to the language and not include JS as well. Luckily, there is a web3 implementation in python. To get it up and running for the dInvest setting I switched to the virtualenv, where I also installed zipline and then install web3 simply with pip install web3.

Using web3, there are three steps to get you up and running to interact with your smart contract:

2. Setup the RPC connection
3. Interact with the smart contract

In the next sections, I will go into detail how to achieve the three steps. I am using this mostly as a python module for other programs. In the end our python module structure might look like this:

contract|-- __init__.py|-- ContractHandler.py|-- your-contract-name.json

Now, to interact with any smart contract you need the Application Binary Interface(ABI) defined by the contract. The ABI is a static, strongly typed interface. Whenever you create a new contract or change an existing one, chances are your ABI changes as well. In my experience the easiest way to get the current ABI of a smart contract (which might be yours or any contract you have the source code available) is to go to https://ethereum.github.io/browser-solidity/ and copy/paste your code there. Then press the "Compile" button on the upper right side and copy the entire string in the "Interface" field into a your-contract-name.json file. Once you have that JSON, your web3 interface will know how to interact with the contract.

## Setting up the RPC provider​

As a next step you will need to connect to the RPC provider. In your python file (e.g. ContractHandler.py) include those lines of code:

from web3 import Web3, TestRPCProviderclass ContractHandler:  def __init__(self):    self.web3 = Web3(RPCProvider(host='localhost', port='8545'))    with open(str(path.join(dir_path, 'contract_abi.json')), 'r') as abi_definition:      self.abi = json.load(abi_definition)    self.contract_address = your_contract_address    self.contract = self.web3.eth.contract(self.abi, self.contract_address)

I prefer having my configurations in a separate file. There are many ways to do it and it seems like there is no standard in python. I guess using a txt file is not the best option though and I plan to switch to yml soon. See also here https://martin-thoma.com/configuration-files-in-python/. Make sure to run your favorite Ethereum client before starting your program (e.g. geth --rpc).

## Interacting with the smart contract​

Note: Before interacting with your own account you need to unlock it first. This is achieved in web3 via:

self.web3.personal.unlockAccount(your_ethereum_account, your_ethereum_password)

There are some standard web3 calls you can make, like getting the current balance of an account in wei:

wei_balance = self.web3.eth.getBalance(some_ethereum_address)

In case you want to call a function in the contract you can do this by calling the command as defined by the contract ABI. In our dInvest example there is a contract call which returns the blacklisted companies for our sustainable investment. It is callable with:

blacklist = self.contract.call().blackListCompanies()

There are some more examples in the GitHub code available.

## Final note​

As a final note, I would like to point out that there are other blockchain solutions like Hyperledger Fabric or Tendermint that aim to solve issues around compatibility with other programming language, transaction throughput etc. As they are permissioned blockchains I haven't yet given them a try, but might be interesting to take a look at.

## dInvest - hedge fund on a blockchain

As public reputation becomes one of the most important success factors beyond financial success, investment opportunity should ensure ethical decisions and keep sustainable investment as core of their strategy. These long-term investment strategies based on criteria other than pure financial data are summarized under "Value Investment". Value investment is based on the assumption that the current price of an asset might not be the actual value of an asset (e.g. stocks and derivatives). Thus, criteria other than their current prices can be taken into account to calculate their value. The value investing approach offers thereby methods to select potential investment based on social or sustainability criteria. Furthermore, value investment includes diversification of the portfolio to achieve a desired level of risk.

In this blog post I will introduce dInvest, a project Tharidu and me are working on. With the development of blockchain technologies and the Ethereum blockchain, an autonomous and decentralized approach can be taken to create an investment opportunity. Users are able to invest directly with the cryptocurrency Ether into a company which exists in the Ethereum blockchain. Alternatively, they can invest with other cryptocurrencies (e.g. Bitcoin) or fiat currencies by utilizing currency exchanges. An autonomous organization build on Smart Contracts exists solely as code and can execute the details as specified in the contract. As an example, The DAO enabled users to act as venture capitalists by suggesting investments to other users. If a certain amount of investments was raised the contracts would be executed inside the blockchain. However, this approach failed as The DAO suffered security flaws, which led to a severe attack on its system. Furthermore, The DAO failed to give incentives to users proposing investments. Investments are voted for two weeks, while a vote can only be given by bounding a user’s capital into the vote. Thus, late voting and waiting for other’s resulted in available capital.

## Problem​

Certain investors want to invest their money in order to gain returns while being socially responsible and sustainable to e.g. achieve corporate sustainability objectives. However, financial intermediaries, such as investment banks or hedge funds, do not always adhere to investors’ requirements as there might be conflicting interests. Furthermore, the investment strategy applied by the financial intermediary can change through time and is highly influenced by social factors. In addition to that, investors do not have complete transparency over the transactions.

## Our work​

We decided to develop an autonomous hedge fund in the Ethereum blockchain. Users are represented in the Ropsten network of the Ethereum blockchain as addresses. Users can hold certain amounts of test Ether, which they can invest into dInvest. The investment will contain an amount of Ether and a time period defined by the user. The details of the investment will be defined in a smart contract between the user and dInvest. Selecting stocks for different investment amounts and time periods is comparably computation intensive and will require the application of investment algorithms. Thus, their executing is costly in the blockchain and will therefore be executed by an autonomous agent (invest agent) outside of the blockchain. The required information will be passed on to dInvest on demand and therefore keeping the operational cost to a minimum. The invest agent will suggest investment strategies to the hedge fund according to the current Ether value. The hedge fund will decide to approve or reject the offer based on the sustainability criteria of users’ investments. Only if the criteria is fulfilled, the Ether will be transferred to the buy agent and make the investment. The invest agent will transfer the investment return to the hedge fund where the profit/loss will be divided to investors according to their investment value.

We managed to achieve a linear cost function of user investments and their sustainability criteria in the smart contract. Based on a value investment investment strategy we managed to achieve around 360% increase of the portfolio in a back-testing simulation over around 6 years. The sustainability criteria was implemented using exclusion of assets based on industry codes (i.e. exclusion of defense, alcohol, tobacco, or coal industries). If you are interested in the academic side and the results of our implementation, you can check out our report. As the paper does not cover the implementation in detail, I will post the details in separate blog posts and link them here. You can also check out our source code on GitHub.