ETHLend & uPort, A Match Made in Heaven

Here is a second post written in my series of articles for ETHLend, an Ethereum based lending start up.  Enjoy!

In my previous write up I mentioned that we would dive deeper into what a possible block chain credit score would look like. Well, in order to have a credit score, you must first have an identity with which to attach that credit score. It therefore seems the most logical place to start in our investigation of credit scoring is identity. Today, we’ll be using uPort to create a loan on ETHLend using our uPort identity. For the sake of brevity, I’m going to assume you’ve followed the steps in the uPort devPortal and have an identity. I’m also going to assume you’re familiar with how ETHLend works.

uport-connect

To start, we’re going to create a quick and dirty node.js cli for illustrative purposes which we’ll use to connect our uPort identity to:

const uport_lib = require('uport-connect');   
const qrcode = require('qrcode-terminal');      
const SimpleSigner = uport_lib.SimpleSigner;   
const Connect = uport_lib.Connect;      
const uport = new Connect('ETHLend Integration', {       
  clientId: 'UPORT_APP_ADDRESS',       
  network: 'rinkeby',      
  signer: SimpleSigner('SIGNING_KEY'),              
  uriHandler = uri => qrcode.generate(uri,{small:true})  
})
uport.requestCredentials(['name'])
  .then(userProfile => {  console.log(userProfile);  })    
  .catch(err => {  console.log(err)  })

You’ll obviously need to npm install uport-connect as well as qrcode-terminal.

Put the above code into a file (may I suggest ETHLendRocks.js?) and run:

node ETHLendRocks.js

You should see a QR code generated on your terminal. Scan it, and grant your uPort mobile app access to your uPort identity credentials. You should see your uPort profile data logged to the terminal. Now that we have an identity, we can store different attributes about this identity using IPFS and the uPort-registry package.

uport-registry

In order integrate uport-registry we need to do a bit of extra set up to our existing application:

const uport_lib = require('uport-connect');
const MNID = require('mnid'); 
const qrcode = require('qrcode-terminal');
const registryArtifact = require('uport-registry'); 
const Contract = require('truffle-contract'); 
const Registry = Contract(registryArtifact);  
const NUMBER_OF_LOANS = 10; //random number of loans of illustration
var registryInstance;  
const SimpleSigner = uport_lib.SimpleSigner;   
const Connect = uport_lib.Connect;      
const uport = new Connect('ETHLend Integration', {       
  clientId: 'UPORT_APP_ADDRESS',       
  network: 'rinkeby',       
  signer: SimpleSigner('SIGNING_KEY'),
  uriHandler = uri => qrcode.generate(uri,{small:true})  
})   
 
const web3 = uport.getWeb3();
Registry.setProvider(web3.currentProvider); 
Registry.deployed()
  .then(reg => {  
    //set the global registryInstance variable to access anywhere in the app
    registryInstance = reg;
  });    
	 
uport.requestCredentials(['name'])   
  .then(userProfile => {  
    //decode the users address based on which network they're on   
    let addressPayload = MNID.decode(userProfile.address);     
    return registryInstance.set('Open Loans',addressPayload.address,NUMBER_OF_LOANS,{from:addressPayload.address});    
  }) 
  .catch(err => {    console.log(err)  })

Using the registryInstance.set parameters we can put any sort of financial data we want to store about a uPort identity. We can then retrieve it using the registryInstance.get() method:

uport.requestCredentials(['name'])
  .then(userProfile => {     
    let addressPayload = MNID.decode(userProfile.address);     
    return instance.set('Open Loans',addressPayload.address,NUMBER_OF_LOANS, {from: addressPayload.address});   
  })
  .then(tx => {     
    const subject = tx.logs[0].args.subject;
    instance.get('Open Loans', subject, subject)
      .then(value => {      
        console.log(hexToString(value));     
      })   
  })
  .catch(err => {     
    console.log(err)   
  })  
	
function hexToString (hex) {     
  var string = '';     
  for (var i = 0; i < hex.length; i += 2) {       
    string += String.fromCharCode(parseInt(hex.substr(i, 2), 16));    
  }     
  return string; 
}

Obviously, this can be used to store information about a uPort identity any time they do anything in an ETHLend dApp. How many times they’ve defaulted, how many loans are currently open, and what value they’re for, are a few examples.

ETHLend

To integrate this uPort identity into the ETHLend ecosystem we simply need to create a contract object with whatever contract we’re interested in interacting with:

const web3 = uport.getWeb3();
const CreateLedgerContractObj = () => {      
  let LedgerContractABI = web3.eth.contract(LEDGER_CONTRACT_ABI);
  let LedgerContractObj = LendingContractABI.at(LEDGER_CONTRACT_ADDRESS);      
  
  return LedgerContractObj;  
}
const LedgerContract = CreateLedgerContractObj();

In this case I’ve chosen to use ETHLend’s Ledger contract. So you’d fill in the LEDGER_CONTRACT_ABI and LEDGER_CONTRACT_ADDRESS with whichever smart contract you’re interested in interacting with.

Once we have the smart contract object, we can call methods on it inside the .then() block of the requestCredentials call:

uport.requestCredentials(['name'])
  .then(userProfile => {     
    let addressPayload = MNID.decode(userProfile.address);     
    const usersEthereumAddress = addressPayload.address;     
		makeLoanRequest(usersEthereumAddress, 100);    
  })   
  .catch(err => {     
    console.log(err)   
  })  
	
const makeLoanRequest = (address, loanAmount) => {   
  LedgerContract.createNewLendingRequest({     
    from: creator,
    value: loanAmount,     
    gas: 2000000    
  }, (err,txhash) => {     
    if(err) throw err;           
    waitForMined(txhash, {blockNumber: null},          
    pendingCB() => {              
      console.log('waiting for loan request to be mined...');         
    },          
    successCB() => {       
      console.log('your loan\'s transaction hash is:',txhash);       
      incrementIPFSLoanCount(address);       
      incrementIPFSOpenLoanAmount(address, loanAmount);       
      //any other financial data you'd like to track can be get and set here...     
    }          
  }) 
}
const incrementIPFSLoanCount = (subject) => {   
  instance.get('Open Loans', subject, subject)
    .then(value => {     
      instance.set('Open Loans', subject, value + 1, {from: subject})    
  }) 
}
const incrementIPFSOpenLoanAmount = (subject, openedLoanAmount) => {   
  instance.get('Open Loan Value', subject, subject)
  .then(value => {     
    instance.set('Open Loans', subject, value + openedLoanAmount, {from: subject})    
  }) 
}

Here I’ve illustrated how one would store the number and amount of open loans made by a uPort identity at the time of loan creation, but any number of metrics can be used and any point in a loaning and borrowing process.

Developers

This brings me to my final point. If we’re going to use IPFS as an open, transparent data store, then the ETHLend smart contract is going to need to update the data associated with the uPort identity via IPFS as well, depending on various conditions known only to the ETHLend smart contract. Currently this is not implemented.

If you’re a developer and you’re interested in developing smart contract code, this is a perfect opportunity to make your mark! Check out the ETHLend repo, and see if you can get your pull request merged into the master branch, or, feel free to get in touch with ETHLend via the many social media channels:

https://twitter.com/ethlend1

https://www.facebook.com/ETHLend/

https://www.instagram.com/ethlend1/

https://steemit.com/ethereum/@ethlend

uPort is always interested in hearing from developers as well and in fact were instrumental in making this article happen.

https://www.uport.me/

https://github.com/uport-project

https://gitter.im/uport-project/Lobby

Advertisements

Lessons learned from an ICO

Background

A few months ago I dabbled in solidity development.  I’m interested in all things cryptocurrency, and ethereum smart contracts appear to be a very large aspect of the current state of cryptocurrency.  As such, I had no choice but to experiment with the technology.  This experimentation involved using the truffle.js framework to follow the ethereum foundation tutorials.

During initial smart contract development it’s common to use the testrpc client as this speeds up deployment times allowing for quicker code iterations. There is also less complexity in this chain, so less can go wrong and you can focus explicitly on development.  However, given that the eventual goal is deploying smart contracts to the main net, eventually you begin to turn your attention to the ethereum test networks.  After testing my contracts using testrpc my next step is typically to test on the parity development chain, which similar, to the testrpc client has less complexity but is an actual blockchain.  After testing on the parity dev chain, I move to the kovan or ropsten test networks.  At the time the ropsten network was under attack (and looks like it is again).  So my only choice for testing was kovan.

Kovan

This is where I begin to have problems in my development and eventually moved on to other aspects of technology (I think at the time it was react-native).  I was working through a tutorial to deploy a DAO like smart contract, and everything was going well, until I attempted to deploy the contract to the kovan test network.

When I would deploy via the testrpc client, or even the parity dev chain, the contract would deploy successfully and I could interact with it via javascript.  However, on kovan the deploy would hang, and then after a long period of time, would fail with this cryptic error:

Error encountered, bailing. Network state unknown. Review successful transactions manually.
    Error: Contract transaction couldn't be found after 50 blocks

At the time I didn’t really understand what was going on behind the scenes with regard to addresses and transactions.  I knew that I had to sign the transaction in parity, but I had already deployed on the parity development chain, created two different accounts on the kovan chain, one email verified in order to get some test ether, and had my main net accounts floating around in the parity files as well.  So I tried a number of different key files, unsure of which was correct,  none of them were signing the transaction successfully, or if they were, there wasn’t enough ether in the wallet.

At the time I wasn’t even sure I was barking up the right tree, and given that I wasn’t actually trying to deploy to the main net anyway, I posted to stack overflow, never heard back, and shelved the issue.

Enter the ICO

A few weeks ago I posted about proof of stake, and through this post met the CEO of a blockchain start up.  I ended up proof reading their white paper, and kept in touch during their ICO.  During the pre-sale they were deploying their smart contract for the ICO and were getting the exact same error I was getting months ago.  Since this seemed to be a recurring error rather than a one off issue specific to me I felt this warranted more investigation.

I went back to my original DAO smart contract that was giving me issues and tried deploying it again.  During this time the CEO made a number of observations eventually leading to a successful deployment of their smart contract.

Here are a few lessons to keep in mind when deploying smart contracts to both the main net and the test nets.

Don’t forget to sign your transaction in parity

Since it’d been a few months since my previous test deployment I had to remind myself how to process works.  When you run:

truffle migrate --network kovan

The transaction still needs to be signed by the address set in the truffle.js file for the kovan network settings.  If you forget this, truffle will just wait, and after a very long time finally fail with the cryptic error message mentioned above.

There’s no harm in trying different keys

As users we’ve been trained that after too many password attempts you’ll be locked out of your account.  In my case I had a bunch of different key files for the same address, if I’d just tried all of them eventually I would’ve found the correct one.

Key management is paramount

I wouldn’t have needed to try every key file if I’d paid more attention to what I was doing with each key while creating test accounts.  As an ethereum user, this important, but it becomes even more important as this can introduce inadvertent bugs, adding to the already high cognitive load associated with development.

Make sure you have enough ether to cover the gas costs

I remember this kept coming up while I was troubleshooting the issue a few months ago.  The first question asked in forums was always “what did you set your gas price to?” and “does the signing address have enough ether to cover this cost?”

Usually when you sign the transaction in parity it will allow you to set the gas price at that time, and will show you the current average gas price on the network.

Screenshot from 2017-09-29 19-47-03

Screenshot from 2017-09-29 19-47-20

You can also set the gas price explicitly in the truffle.js network settings.  For example:


kovan:{

from: 'KOVAN ADDRESS',
network_id: 42,
host:'localhost',
port:8545,
gas: 4712388,
gasPrice: 25000000000
}

would set the transaction to use 4712388 gas with a gas price of 25000000000 on the kovan network.

Use the parity transaction viewer

Screenshot from 2017-09-29 19-53-17

This was one of the jewels passed along to me by the CEO that I wasn’t aware of.  Parity comes with a bunch of dApps, and one of them is a transaction viewer.  This allows you to keep tabs on the state of your transactions, as well as view other pending transactions on the blockchain.  I believe this is what led the CEO to the truffle.js gas price file insight.

Use etherscan

At the end of the day, when I finally went to check if my contract deployed successfully on the kovan network, I looked at all transactions made by my kovan address, and some of my transactions from months ago actually made it onto the blockchain.  Truffle uses what they call an “initial migration” and then the actual contract deploy.  Some of my initial migrations made it into the blockchain, but not the actual contracts, until sorting out the rest of the things discussed above.

This lesson is an obvious one.  Always check etherscan.  Although, some times this may add to the confusion.  Since the kovan network was sluggish at the time, it took awhile for my transactions to show up, this coupled with the cryptic truffle error lead me to believe absolutely nothing was happening.

Conclusion

Most of these are trivial to debug, but when combined lead to difficult debugging, add to that cryptic error messages and it can often be difficult to break down what’s going wrong in a systematic way.  But, this is brand new tech, and because of this, if you’re a developer, any help with these frameworks will speed up development iterations and in turn make this tech easier to work with for other developers in the future. parity truffle

That’s all for now.  I’ve recently upgraded my miner to a new beta AMD blockchain driver, so I may pass along this bit of info in my next post.  Until then!

Proof Of Stake vs Proof Of Work

I’ve decided to write post about the differences between proof of stake (a protocol currently being used by Neo and being worked on by Ethereum), and proof of work (a protocol made famous by Bitcoin, and currently in use by coins like ZCash and Monero).  I felt motivated to write this post because there seems to be a bit of confusion when I talk with people about the proof of stake protocol as to what exactly happens.  Many I’ve talked with seem to view it as creating money out of thin air (as if mining wasn’t that already), or at the very least less secure than proof of work.

Proof of Work

I believe people feel more comfortable with proof of work because it’s the simpler of the two protocols.  The idea is this: Your computer is going to try billions of different inputs to a hash algorithm (it’s going to put in work), and if it comes up with the right output (it’s proved that it’s worked on the puzzle sufficiently), you’ll be rewarded. Here is an example proof of work algorithm from the Ethereum cryptocurrency tutorial:

// The coin starts with a challenge
bytes32 public currentChallenge;
// Variable to keep track of when rewards were given
uint public timeOfLastProof;
//Difficulty starts reasonably low
uint public difficulty = 10**32;

function proofOfWork(uint nonce){
    // Generate a random hash based on input
    bytes8 n = bytes8(sha3(nonce, currentChallenge));
    // Check if it's under the difficulty
    require(n >= bytes8(difficulty));
    // Calculate time since last reward was given
    uint timeSinceLastProof = (now - timeOfLastProof);
    // Rewards cannot be given too quickly
    require(timeSinceLastProof >=  5 seconds);
    // The reward to the winner grows by the minute
    balanceOf[msg.sender] += timeSinceLastProof / 60 seconds;
    // Adjusts the difficulty
    difficulty = difficulty * 10 minutes / timeSinceLastProof + 1;
    // Reset the counter
    timeOfLastProof = now;
    // Save a hash that will be used as the next proof
    currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1));
}

If you were to mine this coin, you’d essentially send your input (nonce) to the proofOfWork function in this smart contract.  If your input is below the current difficulty level, and it’s been long enough since the last block was mined, you receive a reward, otherwise the function returns (that’s what the require statement does in solidity) and you try the next input you think might result in a sha3 hash below the current difficulty.  This is proof of work mining in a nutshell.

Proof of Stake

Proof of stake has the same goal as proof of work: to achieve distributed consensus of the state of the blockchain.  Going back to the git perspective, both protocols are trying to select maintainers of the blockchain “branch” without allowing anyone too much control.  Proof of stake does this by substituting out hash power for economic power.  The more coins you have, the more likely you, or the block you’ve chosen, is to be used and the more you’ll be rewarded for it.  I believe cryptocurrency developers are moving in this direction because unlike proof of work, proof of stake has the added property that the more coins you’re holding, the more likely you are to act in solidarity with the will of the users of blockchain when selecting blocks.  In proof of work there is a tension between miners and users of the blockchain that may not exist in a proof of stake protocol (this is yet to be seen), as often the users will also be the validators (a miner in proof of stake is often called a validator).  There’s also the added benefit that proof of stake doesn’t cost millions of dollars in power and bandwidth every year to maintain the blockchain.

Casper

Let’s use the Ethereum casper protocol as a detailed example for proof of stake, as this one seems to be getting so many people interested in what proof of stake is.

The casper protocol will involve a smart contract being deployed to the Ethereum blockchain.  An address interested in becoming a validator will send the amount of ETH they would like to stake on blocks to the smart contract.  The smart contract will then receive two messages from validator addresses, PREPARE and COMMIT.  Prepare is essentially a validator saying “I think this set of transactions should be the next block”, if one of these blocks attains a 2/3’s economic vote in the smart contract, it becomes a possibility for a COMMIT.  After the possible PREPARE blocks have been selected, validators vote on this set of blocks with the COMMIT message, once again, if 2/3’s economic vote is found on a COMMIT block, it will be added to the block chain and all the validators who took part in selecting this block will be rewarded for minting the block in proportion to the amount of ETH they deposited to the smart contract when joining the validator pool.  As far as I’m aware, there doesn’t exist a mechanism for selecting validators*, but it could easily be something like a random subset selection of all possible validators weighted by the amount of their deposit in each dynasty.

Nothing to Stake

One of the problems with proof of work is the “nothing to stake” problem.  The idea is as follows: If I don’t have to compute any hard hash puzzles, why not bet on every block that comes my way? Since this incentive structure exists for everyone in a nothing to stake protocol, everyone decides to stake their hard earned crypto currency on every block.  Now we have no consensus, there are 50 different chains all growing at the same rate and all possibly legitimate because no one wants to take the lead and decide on one.  Also because of this lack of consensus, double spend attacks become much easier and more likely than they are on a proof of work protocol.

Ethereum’s casper protocol circumvents the nothing to stake protocol by locking the funds in the smart contract discussed above, only paying them out after a sufficient amount of time, and destroying the ether, or penalizing it, for various kinds of behaviour (to include malicious).

 

Conclusion

I think people are uneasy about proof of stake due to a misunderstanding of proof of work more so than anything else.  As I stated in my git perspective of the blockchain the only reason miners exist is to act as the “maintainer” of the blockchain, and since we want this maintainer to change often, mining was used as a mechanism to distribute time as the maintainer evenly.  With proof of stake, the same thing is happening, it’s just the mechanism to choose maintainers is based on the amount of cryptocurrency a person holds, rather than their hash power.  The 51% attack we saw in the previous post  now becomes a 51% currency attack, whereby you’d have to own 51% of the cryptocurrency in which you’re attacking.  This is a presumably much more difficult feat to accomplish than purchasing 51% of the hash power.  In the currency case, you’ve just purchased 51% of the currency, all the while raising it’s market price and only have 49% of the rest of the currency to defraud, at which point, news will probably have broken that someone purchased 51% of the currency on the market, and the currency is now socially worthless.  In the case of proof of work, you just secretly buy more computing power, or bribe, or even hack existing mining pools, and rather than defrauding 49% of the currency you’re able to defraud all of it.

As you can see, we aren’t creating money out of thin air, at least in the casper protocol, there is a very real chance of losing your money, and your money is also stuck in the smart contract, so it’s no different than a government bond gaining interest, or mining for that matter.

Until next time!

* if someone has any information let me know.  There is a reddit discussion here, but since it’s a year old, I hesitate to trust it given how much Ethereum proof of stake has changed, this seems to suggest its proportionate to the ETH you deposit, Vlad also mentions it as a possibility here.  I looked briefly at the casper source code and didn’t see validator selection anywhere, but since I was brief, there’s a very good chance I wasn’t looking in the correct place.