<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Narek Hovsepyan on Medium]]></title>
        <description><![CDATA[Stories by Narek Hovsepyan on Medium]]></description>
        <link>https://medium.com/@promentol?source=rss-37db62e72843------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_dVxKMgvwGfZQ7v5MSCiEA.jpeg</url>
            <title>Stories by Narek Hovsepyan on Medium</title>
            <link>https://medium.com/@promentol?source=rss-37db62e72843------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:32:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@promentol/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lottery Smart Contract: Can we generate random numbers in Solidity?]]></title>
            <link>https://medium.com/@promentol/lottery-smart-contract-can-we-generate-random-numbers-in-solidity-4f586a152b27?source=rss-37db62e72843------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f586a152b27</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[random]]></category>
            <dc:creator><![CDATA[Narek Hovsepyan]]></dc:creator>
            <pubDate>Sat, 10 Feb 2018 22:12:33 GMT</pubDate>
            <atom:updated>2018-02-10T22:12:33.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine we are building a decentralized Lottery. What challanges does it have? Ever thought about is that even possible? In this article we are going to explore the possibile approaches for building a Smart Contract for decentralized lottery.</p><h4>History of Lottery.</h4><p>The earliest mention of lottery games is in China, during Han dynasty, a game called keno, which you can still find in many Casinos in Asia. The idea of the lottery is simple. The organizer is collecting the money from players, and a randomly selected subset of players, called winners, are getting rewarded, while others are loosing their money. The organizer usually is distributing one part of all collected money, which is putting him on always profiting position. French King Francis I used lottery to get money to state budget and help state budget. Countries like Thailand or Russia, are allowing only state issued lotteries, while other countries like Goergia you can register lottery company within minutes.</p><h4>What is Lottery?</h4><p>Well, everybody knows what is lottery. At least if you are reading this articles, you know what is lottery. I am asking to question, to go further and define the task we will solve in this article.</p><p>Design a Smart Contract, which accept a single number from users, after getting payed for 0.1 eth, add a pool of users. At some point stop allowing submissions of new user, then select a random number, distribute half of collected funds between users, who have submitted the selected number.</p><h4>Why It is difficult?</h4><p>Here are two challanges we will face in order to develop Smart Contract for a lottery.</p><ol><li>How we will generate random number? In Solidity, the code should be deterministic, as it will run on multiple nodes. Things like clock time are not available for generating random number.</li><li>How does Smart Contract know the time for selecting the winner? Again things like clock time are not available in Ethereum Virtual Machine, as the code will be ran on multiple nodes, on different time.</li></ol><p>The second challange can be solved using Ethereum Alarm. The blocknumber can be an alternative in a clock time, as it is always increasing by 1. As I want to focus on the first challage, in our smart contract We will make a public function which will trigger the winner(s) selection process. This can be triggered either by owner of smart contract, or by Ethereum alarm, or in any other way.</p><h4>Generating (Pseudo)Random number in Solidity</h4><p>We need a <strong>random number generator</strong>, which will generate the same <strong>number</strong> on <strong>multiple nodes</strong>, running <strong>multiple times</strong>. This is <strong>nonsense</strong> for anyone who knows what means <strong>random number</strong>. Then how we can accomplish that task? We need a <strong>random number</strong> generated <strong>once</strong>, and use that on <strong>different nodes</strong>. Well <strong>Solidity</strong> code will ran the <strong>code</strong> on multiple nodes, multiple times, but there is <strong>one running process</strong> which makes it <strong>unique</strong> among all the runs of the code. Yes it is the time when the <strong>code</strong> will be ran by <strong>miner</strong>, who will <strong>confirm the transaction</strong>. Let’s take a look to the <strong>block</strong> variable , which is assigned by miner to every confirmed <strong>smart contract</strong>. If we will look to <strong>block.timestamp</strong> constant, it is assigned by <strong>miner</strong>, no <strong>player</strong> have control on it. After it will be generated and assigned, it will be the <strong>same for all other nodes</strong> which will ran the <strong>Solidity</strong> code. <strong>block.difficulty </strong>also has some properties of randomness. Basically those two variables are completely out of control of the <strong>players</strong>, thus they can be used as a <strong>source</strong> for <strong>random number</strong>. They are generated only once by <strong>miner</strong>, and on all other nodes it will have <strong>the same value</strong>, thus random number will be generated on multiple nodes will be the same.</p><p>Sounds legit enough right? let’s look the Solidity code snippet for a lottery, everything should be self explaining. Note that in this code I have ignored gas limits, as this code is for demonstration of random number generation only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0858b6c8ff77bc0b99a2975a56d3823/href">https://medium.com/media/d0858b6c8ff77bc0b99a2975a56d3823/href</a></iframe><p>Let’s explain the <strong>random() </strong>function. It depends on block.difficulty and block.timestamp, it is being hashed and encoded as a number. After encoding 256 bit hash to 256 bit integer, we are taking reminder by dividing 251, to get an integer in a range from [0, 250]. In our case 251 is prime number, whic is good. You are free to use any hash function Solidity is providing. But Why Hashing? All you need is just an operation which will convert given constants into fixed length bits. Hashing is not important here, as it is only incapsulating initial values, which is not giving us anything, as initial values they are available for any blockchain explorer.</p><p><strong>But wait? can we trust miners?<br>The answer is NO!</strong></p><h4>More good solution?</h4><p>A question was asked on stackoverflow about how lottery can be implemented in Solidity. A user <a href="https://ethereum.stackexchange.com/users/131/tjaden-hess"><strong>Tjaden Hess</strong></a> has suggested wonderfull solution. Am implementation bellow is heavily based on his algorithm. We have simplified a little bit, also modified as our definition of the task was slightly different.</p><p>The paradigm is simple. As a source of randomness, there can be used adresses of players, or their numbers, as their distributions are completely random. We need also to hide those values for other players, in order to prevent attacks. We can not hide adresses of players, as they are recorded in the blockchain. So we need relay only on numbers submitted by our players. We may need from them to submit their hashes instead of numbers.</p><p>Let’s describe algorithm of the lottery smart contract bellow</p><ol><li>The organizer is starting to accept submissions</li><li>User is generating their number, which they want to submit</li><li>User is hashing it’s number alongside with their address</li><li>User submits that hash only, instead of number</li><li>At some point, ether by block number, or by the organizer, or when sufficient players are here, the contract is stopping to accept new submissions.</li><li>Contract is opening new round of submissions. Now users who have previously submitted a hash, are required to submit the original number. Only users who have submitted before a hash can submit original value. Note that two rounds were created, in order to hide user’s numbers from other users, as we don’t want them to know the source of randomness.</li><li>When the user is submitting original number, the contract is verifying it by adding it to the address of sender, hashing and comparing with previously</li><li>Contract is stopping to accept new submissions.</li><li>As we have list of original numbers, we can use them to generate final number. One possible solution is to XOR all numbers. You are free to do some creativity here.</li><li>The half of the funds collected by the users are being split between users who have submitted number.</li></ol><p>Bellow is an implementation of such lottery.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6599a5b0bcc616f95bf4e2ba1e94e651/href">https://medium.com/media/6599a5b0bcc616f95bf4e2ba1e94e651/href</a></iframe><p>This idea of collecting hashes, then numbers, then generating pseudorandom number based on them, are used and implemented in <a href="http://randao.org/">Randao</a>, think like a DAO for generating random number. I strongly encourage to go further to their documents.</p><h4><strong>Wrap Up</strong></h4><p>Thank you for reading, if you enjoyed the material follow me on medium, and look to my other articles. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f586a152b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing your first Ethereum Smart Contract and Dapp with Solidity]]></title>
            <link>https://medium.com/@promentol/first-ethereum-solidity-smart-contract-and-dapp-draft-e27a7d0cff26?source=rss-37db62e72843------2</link>
            <guid isPermaLink="false">https://medium.com/p/e27a7d0cff26</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[dapps]]></category>
            <dc:creator><![CDATA[Narek Hovsepyan]]></dc:creator>
            <pubDate>Wed, 07 Feb 2018 21:39:09 GMT</pubDate>
            <atom:updated>2019-02-03T05:59:23.260Z</atom:updated>
            <content:encoded><![CDATA[<p>In my second post about blockchain related development, we are starting to exploring the world of Ethereum and Solidity. If you are not familiar with Ethereum, or you don’t know what is smart contract, I am recommending to skim <a href="https://github.com/ethereum/wiki/wiki%E2%80%A6">this</a> article from <strong>Ethereum</strong> team. In this tutorial I will assume you already know about what is blockchain, and what is smart contract in general.</p><p>In this article we will create a first <strong>smart contract</strong>, using <strong>Solidity</strong> deploy to a test virtual network, running locally, using <strong>ganache-cli</strong>, and itneract with it from javascript using <strong>web3.js</strong>. Although there are fremeworks like <strong>truffle</strong> or <strong>embark</strong>, we will do everything from scratch, to have better understanding of what’s going on under the hood. For frontend we will use <strong>jQuery</strong>, to focus on <strong>Ethereum</strong>, not on single page application development. Also we will skip private/public keys authentication and deployment on a real blockchain. This will be my next tutorials.</p><h4>Decentralised Public MessageBoard</h4><p>We are going to build a public MessageBoard application, where everyone can post a new message. This is simplest application we can build. In this tutorial there will not be a paying transaction involved.</p><h4><strong>Enter Ganache</strong></h4><p><strong>Ganache</strong> is a tool which simulates virtual, in memory blockchain, in order to develop and test our <strong>smart contracts</strong>. To install just run:</p><pre>npm install -g ganache-cli</pre><p>Then let’s run ganache with default configuration</p><pre>ganache-cli</pre><p>This will simulate a blockchain, with 10 test accounts, each loaded 100 fake ethers. Usually it will run on localhost:8545</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXSi7D0gRRfCIwWp40dZrw.png" /><figcaption>Output of ganache-cli command</figcaption></figure><h4>Writing our first contract</h4><p>For better understanding the smart contract development, think like <strong>contract</strong> is a class in terms of <strong>OOP</strong>. Now let’s model our application. We will need a <strong>contract Chat</strong>, which will contain list of users with nicknames, as well as the messages, methods for adding messages and a <strong>struct Message</strong>, which will contain the text and the user’s nickname+address.</p><p>Bellow is the code of our smart contract</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aefe3fdb3e747ccbc0b3e792ca1fb17/href">https://medium.com/media/3aefe3fdb3e747ccbc0b3e792ca1fb17/href</a></iframe><h4>Compile, Deploy, Call</h4><p>Now we are ready to compile and deploy, then make calls to our smart contract. Let’s install dependencies.</p><pre>npm install --save solc<br>npm install --save web3@1.0.0-beta.29</pre><p>Now let’s setup web3 inside node REPL</p><pre>&gt; Web3 = require(&#39;web3&#39;)<br>&gt; web3 = new Web3(new Web3.providers.WebsocketProvider(&quot;ws://localhost:8545&quot;));</pre><p>Now we have web3 instance ready to use. As we are building a chat application, which will be subscribed to events sent from smart contract, we will use WebSocket provider. If you will only call/send data to smart contract, you can use Web3.providers.HttpProvider.</p><p>Let’s compile the contract and deploy to our blockchain</p><pre>&gt; var solc = require(&#39;solc&#39;)<br>&gt; var fs = require(&#39;fs&#39;)<br>&gt; var code = fs.readFileSync(&#39;messageboard.sol&#39;).toString()<br>&gt; var compiledCode = solc.compile(code)</pre><p>We can see the contracts in compiledCode.contracts object. We can access a specific contract by compiledCode.contracts[&#39;:CONTRACT_NAME&#39;] , in our case we can access MessageBoard contract by &#39;:MessageBoard&#39; key. The compiled <strong>byte code</strong> will be incompiledCode.contracts[&#39;:MessageBoard&#39;].bytecode , while the ABI incompiledCode.contracts[&#39;:MessageBoard&#39;].interface . ABI is the interface of Smart Contract, which will be used to make calls to Smart Contract from javascript. Learn more about ABI <a href="https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI">here</a>.</p><p>After compiling, we are ready to deploy now.</p><pre>&gt; var ABI = JSON.parse(compiledCode.contracts[&#39;:MessageBoard&#39;].interface)<br>&gt; var byteCode = compiledCode.contracts[&#39;:MessageBoard&#39;].bytecode</pre><pre>&gt; var MessageBoardContract = new web3.eth.Contract(ABI, {<br>    from: address,<br>    gas:  4700000<br>})<br>&gt; deployedContract = MessageBoardContract.deploy({data: byteCode})<br>&gt; address = &#39;0xf3d31153795b5bf4072bc638eb088a794ab18538&#39;<br>&gt; deployedContract.send({<br>    from: address,<br>    gas:  4700000<br>  }).then((newContractInstance)=&gt; {<br>    console.log(newContractInstance.options.address)<br>    return newContractInstance.methods.setUsername(&quot;NarekUser&quot;).send()</pre><pre>  }).then((x) =&gt; console.log(x))</pre><p>We have <strong>address</strong> variable, which is the address of an account, which can be taken from output of <strong>ganache-cli</strong> we run previously. Gas is describing amount of resource needed from miners to acomplish their task. Read more about it <a href="https://github.com/ethereum/wiki/wiki/Ethereum-Development-Tutorial#gas">here</a>. The <strong>deployedContract.send</strong> method will return a promise, which will resolve to a ready to use contract instance. With <strong>newContractInstance</strong> you can interact with out Smart Contract. Please copy/paste the <strong>address</strong> of deployed smart contract (<strong>newContractInstance.options.address</strong>), as it will be needed for building the UI in the next section.</p><p>Before moving to next section, let’s unlock an ethereum ganache-cli account</p><pre>&gt; web3.eth.personal.unlockAccount(address)</pre><h4>UI for our Smart Contract</h4><p>We are going to create a UI for our smart contract using html and jQuery. Take a look to the code bellow, look to the comments and everything will be self explaining. Do NOT Copy paste the code, write line by line, and change the variable values when it will be required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b934eb053d88d812b19b29e5d730db97/href">https://medium.com/media/b934eb053d88d812b19b29e5d730db97/href</a></iframe><p>You may need to include web3.js. You can download <strong>web3.js</strong> from <a href="https://github.com/ethereum/web3.js/tree/1.0/dist">here</a>.</p><p>Note that events are stored in the blockchain, and we can fetch all previous evetns, that’s why instead of keeping array of messages, we just relay on events history.</p><p>Now just open index.html file inside your favorite browser and we have now a working Message Board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6eLfWaqdr5yNEfgorhEXQ.png" /><figcaption>Our app is asking username first.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foWBkoQFe39Qq8GWLZJ84A.png" /><figcaption>The messages are displayed one by one.</figcaption></figure><h4>Wrap Up</h4><p>This was a tutorial for creating really basic Smart Contract with a basic UI. For this tutorial we have skip private/public keys authentication and deploying on a real blockchain. This will be in my next tutorials.</p><p>If you understood the material in this tutorial, I’ve made for you four exercises you can try to accomplish.</p><ol><li>Modify <strong>index.js</strong> and <strong>index.html</strong> to display the user’s name alongside with the message.</li><li>Modify <strong>index.js</strong> file to get provider and addresses from MetaMask. You can install MetaMask from Chrome Store.</li><li>Modify <strong>index.js</strong> and <strong>messageboard.sol</strong> files, that the UI will not ask <strong>username</strong> if a user with this <strong>address</strong> already exists.</li><li>Modify <strong>index.js</strong> and <strong>messageboard.sol</strong> so it will require for username to be unique for each user.</li></ol><h4><strong>Thank you!</strong></h4><p>Thank you for reading the tutorial, feel free to ask any question in comments, I will respond within a day. Follow me if you want to support these tutorials. Also look to my other tutorials/posts. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e27a7d0cff26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptography for JavaScript/Node.js developers: Part 1 Hash Function]]></title>
            <link>https://medium.com/@promentol/cryptography-for-javascript-node-js-developers-part-1-hash-function-86d119c7304?source=rss-37db62e72843------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d119c7304</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Narek Hovsepyan]]></dc:creator>
            <pubDate>Wed, 07 Feb 2018 07:10:37 GMT</pubDate>
            <atom:updated>2018-02-11T07:45:03.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJ-xOEIVoJ7QTgJZNReKyg.jpeg" /></figure><p>In this series of articles, We are going to explore ready-to-use cryptographic functions, as well as some definitions for better understanding user side of cryptography. We are going to use <strong>crypto-js</strong> library published in npm, instead of node.js built in module. Why? It doesn’t matter what library we will choose, if you understand one, you will be able to use any library with any language. There is a reason why I choose crypto-js, because it is written in pure javascript, instead of C++ bindings, s you are able to run on any JavaScript environment. On next tutorials after being comfortable with crypto.js, we will introduce bcrypt library for node.js, which is de facto standart to use, specially with dealing with passwords or any other critical data.</p><p>In the part 1 we are going to understand hash functions. Hash functions are everywhere. Your password is hashed on any website before storing in database, the content of website before caching is hashed for detecting if the cache has been changed, your favorite torrent tracker is providing hashes of data so you can check locally if the data you received was not modified.</p><h4>But what is hash function?</h4><p>Let’s go little bit into theory. Hash function is a any function, which <strong>arbitrary size data</strong> input, and it is taking output a <strong>data with a fixed size</strong>. The returned value usually called <strong>hash code</strong>, <strong>hash value</strong> or just simply <strong>hashes</strong>. By saying hash should have fixed size, we mean that no matter what the input data will be, after processing the data with hash function, we will always receive data with same fixed size. You may think that you can hash numbers just making the reminder of dividing to 9, or you can hash strings just by taking their first symbol? Let’s go over properties a <strong>hash function</strong> can have.</p><h4>Deterministic</h4><p>Your hash function for a given input should always return the same hash code. In other words, it should not depend on any external variable or state. The hash code is dependend only from input data, and should always return the same output for the same input. This is called property of <strong>determinism</strong>. For exampleconst hash1 = (number) =&gt; number % 9 have the property of determinism, while const hash2 = (number) =&gt; number % 9 + Math.random() don’t, because for different calles of hash2 you will get different outputs for the same input. Sometimes our hash function can receive an external parameter for hashing. For example const hash3 = (number, param) =&gt; number % param. In that case hash3 is still have property of determinism, because for the same input data and the same parameters, it will return the same output.</p><p><strong>Collision Free<br></strong>As we said, input can be data of arbitrary size, while the output should have fixed size. Well there <strong>indefinite</strong> amount of data, which can be taken as input, meanwhile the output, as it have fixed size, can have <strong>definite/limited</strong> available values. Yes that means, that two different inputs can have the same hash code, and it may be still good. For example for thehash1 from previous we have hash1(1) = hash1(10) . For a good <strong>hash function</strong> it should be <strong>hard</strong> enough to find two differnt a and b values such hash(a) = hash(b) . There are <strong>algorithms</strong> like <strong>brute force</strong>, to find such values for a <strong>good hash functions</strong>, yes they are, but for some <strong>hash functions</strong>, on a modest <strong>cluster of supercomputers</strong>, it may take even <strong>million of years</strong> to find such values.</p><p>So let’s define propery of <strong>Collision Free</strong>. We will say that hash function is <strong>Collision Free</strong>, if it is safe to assume, that if hash(a) is equal to hash(b) , then a is equal to b.</p><h4>Non-invertible</h4><p>The last important property is the <strong>non-invertible</strong> property. That mean if you have a <strong>hash code</strong>, you can not recover an original data, at least without spending a lot of resource of computing. This means that you can not find any of the original data. In other words if you have a <strong>hash code</strong> h, you can not find a value x, that hash(x) = h.</p><h4>Other properties</h4><p>There are other properties that hash function can have, like uniformly or continouty, which we will not cover as they are less important in cryptography. You can read them in <a href="https://en.wikipedia.org/wiki/Hash_function">wikipedia</a> if you have an interest.</p><h4>Cryptographic hash functions</h4><p><strong>Cryptographic hash functions</strong> are hash functions, which are usefull in <strong>cryptography</strong>, and usually they should always hold the properties of <strong>determinism</strong>, beinng <strong>collision free</strong> and and <strong>non-intervitble</strong>, and also be quick enough to compute. There multiple algorithms like <strong>md5</strong> or <strong>sha3</strong>, we are not going to cover the actual algorithms, but we are going to give general overview and use cases.</p><h4>Back to coding</h4><p>Open the command line terminal<br>Install crypto-js by typing ithe following code in terminal</p><pre>npm install crypto-js</pre><p>Then open node REPL, by typing <strong>node</strong> in terminal</p><pre>$ node</pre><p>Now we are ready to explore crypto-js. Let’s import it and use some hash functions.</p><pre>&gt; var Crypto = require(&#39;crypto-js&#39;)<br>&gt; Crypto.SHA256(11)<br>&gt; Crypto.SHA256(11).toString()</pre><p>The Crypto.SHA256()is returning an object, which is containing the result of SHA256 algorithm, like state of internal variable, as well as methods for going furhter, whiletoString() method will return the hash code. You can run them multiple times, over and over again, to make sure it will always return the same value. As those functions do not contain I/O, they will run synchronously, which is good to play around in REPL.</p><p>You can hash numbers, strings, objects and even files.</p><pre>&gt; Crypto.SHA256({}).toString()<br>&gt; Crypto.SHA256([]).toString()<br>&gt; Crypto.SHA256(&quot;single string&quot;).toString()</pre><pre>&gt; var fs = require(&#39;fs&#39;)<br>&gt; Crypto.SHA256(fs.readFileSync(&quot;Some file path&quot;)).toString()</pre><p>Now let’s see what other hash functions does crypto-js contain.</p><pre>&gt; Crypto.MD5(124124).toString()<br>&gt; Crypto.SHA1(&quot;asd&quot;).toString()<br>&gt; Crypto.SHA256(&quot;asdafaf&quot;).toString()<br>&gt; Crypto.SHA224(&quot;asdadad&quot;).toString()<br>&gt; Crypto.SHA512(&quot;qqqq&quot;).toString()<br>&gt; Crypto.SHA384(&quot;asfasfaf&quot;).toString()<br>&gt; Crypto.SHA3(1).toString()<br>&gt; Crypto.RIPEMD160(7).toString()</pre><p>You may ask why so many hash functions. First the diversity is guaranteeing that the attacker can not guess the hash function . Somethimes it also usefull to define a constant <strong>nonce</strong> variable in the application, and add on every data, before hashing, like crypto.SHA256(nonce+data).toString(). Secondly, for over period of time, hash functions may use the propery of being <strong>non-invertible</strong>. You may ask how, if the algorithm is not changing. Let’s look for example to <strong>md5</strong>. It was innovative hash function few ago, but now it is not recommended to use it anymore. Why? There are databases of over few milliards common words with their md5 hashes, and an attacker can easily find the original data by <strong>md5 hash</strong>. Also there are algorithm for every string or file to create another one, which will have the same hash. Over period of time, the same thing can happen to every hashing algorithm, that’s why it is important to have multiple hash algorithms.</p><h4>Use cases</h4><p>The most popular use case of hash functions are passwords hashing. Do NOT store <strong>passwords</strong> of users in database, instead store their <strong>hash code</strong>. You can verify the written password during sign in by hasing and comparing with the stored hash. Due properties of determinism you will always get the same hash. Due propery of being <strong>collision free</strong>, someone can not accidentaly write another password and still login. Due property of being <strong>non-invertible</strong>, an attacker who will get access to your database, user’s password will be safe, nobody will know or guess them.</p><p>Another popular of use case of hash functions are <strong>checksums</strong>. Imagine you are sending a large file of 10GB to your friend over network, and your friend has received it, and you now want to check if it received as it is, without any byte transformations, loss or modifications by men in the middle. You can just hash your file on both your and your friends PC with <strong>SHA256</strong>, and compare those hashes. Due property of being <strong>collision free</strong>, if they will match you can assume that original files are the same.</p><p>Hash functions are everywhere, they are used in source code management systems, like git or mercurial, for getting short unique identifier for files, directories and trees, hash functions are heavily used in cryptocurrencies, as well as a in proof of work systems and much much more.</p><h4>HMAC</h4><p><strong>H</strong>ash-<strong>b</strong>ased <strong>m</strong>essage <strong>a</strong>uthentication <strong>c</strong>ode, or simply <strong>HMAC</strong>, is an extension, which is used for data integrity tasks, as well as for message authentication. Think like <strong>HMAC</strong> is extending original hash argument with an additial parameter, which is called <strong>key</strong>, without loosing all the properties of cryptographic hash function. The idea is to have a <strong>key</strong> is that you can generate <strong>code</strong> for specific input, only by knowing the <strong>key</strong>. Read more about <strong>HMAC</strong> <a href="https://en.wikipedia.org/wiki/Hash-based_message_authentication_code">here</a>. <strong>Crypto-js</strong> is providing HMAC support as well. Let’s see in a code sample bellow. You will see we are passing additional string parameter as a <strong>key</strong>.</p><pre>&gt; Crypto.HmacMD5(124124, &quot;key1&quot;).toString()<br>&gt; Crypto.HmacSHA1(&quot;asd&quot;, &quot;keyx&quot;).toString()<br>&gt; Crypto.HmacSHA256(&quot;asdafaf&quot;, &quot;some string&quot;).toString()<br>&gt; Crypto.HmacSHA224(&quot;asdadad&quot;, &quot;4&quot;).toString()<br>&gt; Crypto.HmacSHA512(&quot;qqqq&quot;, &quot;asd&quot;).toString()<br>&gt; Crypto.HmacSHA384(&quot;asfasfaf&quot;, &quot;anything&quot;).toString()<br>&gt; Crypto.HmacSHA3(1, &quot;a&quot;).toString()<br>&gt; Crypto.HmacRIPEMD160(7, &quot;&quot;).toString()</pre><h4>Crypto-js character encodings</h4><p><strong>Byte</strong> is sequence of 8<strong> bits</strong>. <strong>Bit</strong> is either 0 or 1. Everything is stored inside <strong>bytes</strong>. <strong>Strings</strong> are stored inside bytes too. String <strong>characters</strong> can be converted into sequence of <strong>bytes</strong> by multiple ways. Those ways are called <strong>encodings</strong>. There is <strong>ASCII</strong> or <strong>Latin1</strong> encoding for latin characters, there is <strong>UTF-8 </strong>multilanguage support and much much more. As the same string can provide different <strong>hashes</strong> if they will be <strong>encoded</strong> differently. Crypto.js is providing support for various encodings in Crypto.enc submodule. See code examples and play around to get better understanding.</p><pre>&gt; Crypto.SHA256(crypto.enc.Utf8.parse(&quot;кирилица&quot;)).toString()<br>&gt; Crypto.SHA256(&quot;кирилица&quot;).toString()<br>&gt; Crypto.SHA256(crypto.enc.Latin1.parse(&quot;кирилица&quot;)).toString()</pre><h4>Wrap Up</h4><p>This was the first article in series of cryptography for JavaScript developers, next will come about symmetric encryption, public/private key encryption, as well as digital signatures and much much more.</p><h4>Press “Follow” me if you enjoyed the tutorial.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d119c7304" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction into StorJ with node.js]]></title>
            <link>https://medium.com/@promentol/introduction-into-storj-with-node-js-911d8416231d?source=rss-37db62e72843------2</link>
            <guid isPermaLink="false">https://medium.com/p/911d8416231d</guid>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[storj]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[blockchain-startup]]></category>
            <dc:creator><![CDATA[Narek Hovsepyan]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 21:07:26 GMT</pubDate>
            <atom:updated>2018-02-05T21:07:26.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1GVeP0PmwWvWuSEmmNgww.png" /></figure><p>I am starting to explore the world of blockchain and decentralized applications. After 4.5 years of full stack development, I decided to do a career switch, move from web development to blockchain (I will write a separate article about career switching as well). During next months I will start to write series of articles about Ethereum, Solidity and Smart Contracts, Web3js, Truffle, Embark, RSK, OpenZeppellin, Hyperledger Fabric, IPFS, StorJ, Ripple, Factom, Corda and much much more. Those series of articles will <strong>beginner-friendly</strong>, but they will <strong>NOT</strong> be introduction into blockchain.</p><h4>What is StorJ?</h4><p><strong>StorJ</strong> is a Decentralized Cloud Storage, it is allowing to store your files in a Cloud, and get access to it from any StorJ connected device. You can use it to store your regular files, store files of your application’s users, store files just as you wish. What it makes unique among other providers like AWS, Google or Azure? Instead of storing your files in a centralized cloud, StorJ will store your files in hard drives of it’s network members, and deliver to you anytime you like. Members of StorJ network who are deciding to share empty space in their hard drives for other users, are earning special coins called SJCX (now STORJ), which can be traded/sold as other coins just like ETH and BTC.</p><p><em>Are my files safe, do other users have access to it, as they are stored in other users devices?<br></em>First, StorJ will shard (make small pieces) and then store multiple shards on multiple devices (1 shard multiple devices)<br>Second, before sharding, it will encrypt the data with your key,encrypt your files and store in multiple devices, so your files will be available to you and only to you.</p><h4>Why Storj?</h4><p>You may ask why to start from StorJ instead of just smart contract development? First on almost every application, we’ll have to deal files, and StorJ is the way to store files in decentralized applications (Dapps). Second, developing on top of StorJ is not requiring blockchain or smart contract experience, and you will develop on top of it just as you usually did before. There are other decentralized file providers, like SiaCoin or FileCoin, but the most easier to start is still StorJ.</p><h4>Let’s Get Started!</h4><p>Now let’s get started with StorJ. You will need Node.JS, python 2.xx installed in your system.</p><p>Things we will do in this article together.<br>1. Installation and Sign Up<br>2. Accessing <strong>StorJ</strong> through <strong>Node.js</strong><br>3. Accessing to <strong>Storj</strong> from browser and any other JS environment</p><p>What this article will <strong>NOT</strong> covering<br>1. How to setup your PC to share emtpy space and earn little money<br>2. How to <strong>SJCX</strong> token to <strong>STORJ</strong> (see <a href="https://storj.readme.io/docs/migrate-tokens-from-sjcx-to-storj">here</a>)<br>3. How to build an innovative blockchain startup, with decentralised file storage, make <strong>Initial Coin Offering</strong> and retire in Caribbean Islands.</p><h4>1. Installation and Sign Up</h4><p>If you don’t have a StorJ account yet, you can register a new one <a href="https://app.storj.io/signup?referralLink=spectrometry-discographer-855">here</a> (referral). You will get a free 10$ credit, as well as you will support me.</p><p>Then we can jump to development. Run the following.</p><pre>npm install github:storj/node-libstorj --save</pre><p>This librabry will be build with <strong>node-gyp</strong>, as it is a wrapper of native library lib-storj. Refer <a href="https://github.com/nodejs/node-gyp">here</a> if you are listening <strong>node-gyp</strong> for first time. Thus it will not work inside browser, react-native or other JS environments.</p><p>Let’s create a file <strong>index.js</strong> and start coding.</p><pre>const StorJ <strong>=</strong> require(&#39;storj&#39;);</pre><pre>const storjInstance <strong>=</strong> <strong>new</strong> StorJ.Environment({<br>    bridgeUrl<strong>:</strong> &#39;https://api.storj.io&#39;,<br>    bridgeUser<strong>:</strong> &#39;YOUR_EMAIL&#39;,<br>    bridgePass<strong>:</strong> &#39;YOUR_PASSWORD&#39;,<br>    encryptionKey<strong>:</strong> &#39;VERY_STRONG_STRING&#39;,<br>    logLevel<strong>:</strong> 4<br>});</pre><p><em>Well, StorJ, is decentralized, WTF is bridgeUrl there?</em> This is very good question to ask. In order to provide a Rest API, as well as handling authentication and billing, Storj has developed Bridge, an open source web app, to provide thus. You are going to request to StorJ Bridge, which will request from avaible users shards of your file. <br>You will also see <em>encryptionKey</em> as well. Every file you will upload/download will be encrypted/decrypted with a secret key, which will only have you. Make sure you will not lost your key, otherwise your files can not be decrypted and will become useless until end of universe and after that too. Not Sure what to write as an encryptionKey, or you are getting some errors for <strong>encryptionKey</strong>? StorJ is providing a method called <strong>Storj.mnemonicGenerate(bits)</strong>, to generate that for you. There is also supplemented method <strong>Storj.mnemonicCheck(key)</strong>, which will verify the structure of your encryption key, generated by previous command, as well as compare checksum. This is usefull if you think you have make a typo there.</p><h4>2. Accessing <strong>StorJ</strong> through <strong>Node.js</strong></h4><p>Now we are ready to explore StorJ with node.js<br>StorJ is storing files inside buckets. Treat bucket is just like a directory/folder, but it can’t have subdirectories/subfolders. Every file should be stored inside a bucket. You can create a bucket with <strong>createBucket</strong> method</p><pre>storjInstance.createBucket(&#39;SOME_BUCKET_NAME&#39;, (err, res) =&gt; {<br>    if (err){<br>        console.log(err)<br>    } else {<br>        console.log(res.id, res)<br>    }<br>})</pre><p>Buckets should have unique name within your profile. If you will explore the object <strong>res</strong>, you will see that each bucket have name, id, status. Let’s remember our id of our bucket, before moving for forward. There are complementary methods<strong> deleteBucket(bucketId, [calback])</strong> and <strong>getBuckets([callback])</strong>. Note that deleteBucket and other upcomming methods will work with bucket’s id, not with buckets name we used in <strong>createBucket</strong>.</p><h4><strong>Uploading and Downloading files</strong></h4><p>Let’s upload a sample file to our bucket. Change variables BUCKET_ID, as well as LOCAL_FILE_PATH and FILENAME to match with your system.</p><pre>const state = storjInstance.storeFile(BUCKET_ID, LOCAL_FILE_PATH, {<br>  filename: FILENAME,<br>  progressCallback: (progress, downloadedBytes, totalBytes) =&gt; {<br>    console.log(&#39;progress:&#39;, progress);<br>  },<br>  finishedCallback: (err, fileId) =&gt; {<br>    if (err) {<br>        return console.error(err);<br>    } else {<br>        console.log(&#39;File complete:&#39;, fileId);<br>    }<br>  }<br>});</pre><p><strong>storjInstance.storeFile(bucketId, localFile, options) </strong>takes three arguments. First two arguments are self explaining. Options should be object, it can contains the following keys: filename, which is the name you wish to have your file in the bucket (may be different from the name locally), progressCallback and finishedCallback functions to handle events. It is returing a <strong>state</strong> object, which can be used to cancel the download with <strong>storjInstance.storeFileCancel(state)</strong> method. You may noticed from the code variable fileId. Each file have it’s id beside name, and just like the buckets, every operation regarding files, the file is referenced by it’s id. There are two complementary methods <strong>storjInstance.resolveFile(bucketId, fileId, downloadFilePath, options) </strong>and<strong> storjInstance.resolveFileCancel(state)</strong>, which will download the files. You can always list your files from bucket with <strong>listFiles(bucketId, [callback])</strong> method, as well as delete a file with <strong>deleteFile(bucketId, fileId, [callback])</strong> method.<br>If you don’t need <strong>storjInstance</strong> anymore, make sure you call <strong>storjInstance.destoy()</strong> to avoid memory leaks.</p><h4>3. Accessing StorJ from browser</h4><p>StorJ is currently implementing a new library, which is written in JavaScript and can be used in any JavaScript environment. They strongly recommend to use the first library, as this one is for testing purposes only. It is offering more rich functionality, and I am very engaged to use this one sooner. Why? First that it can be used inside any JS platform. Second reason is more important. You may notice that in the previous section we were using our username and password for connecting to API, which is <strong>BAD</strong> practice. Alongside with username/password authentication, the new library is offering a public/private key based authentication as well. Let’s install the new library and explore that.</p><pre>npm install --save https://github.com/storj/storj.js</pre><p>I assume you are in <strong>node.js</strong> environment or you are using <strong>webpack</strong> for building the project for browser, so I am going to use <strong>CommonJS</strong> module format in the code + <strong>es6</strong>. For plain usage inside browser, you can include in with <strong>script</strong> tag the ready to use <strong>storj.es5.js</strong> or <strong>storj.es6.js</strong> file. You can get them from <a href="https://github.com/Storj/storj.js/releases">here</a>. They will declare global <strong>Storj</strong> variable, so you can use it just as you will use inside <strong>node.js</strong>.</p><p>Now let’s move forward, and look in depth the public/private key mechanism. I’m going to write a separate blog post about basic cryptography later. Let’s create a new <strong>StorJ</strong> instance and generate public/private keys.</p><pre>const StorJ = require(&#39;storj&#39;)</pre><pre>const encryptionKey = StorJ.generateEncryptionKey()<br>console.log(&quot;Encryption Key:&quot;, encryptionKey)</pre><pre>const storjInstance = new StorJ({<br>    bridge: &#39;https://api.storj.io&#39;,<br>    basicAuth: {<br>        user<strong>:</strong> &#39;YOUR_EMAIL&#39;,<br>        password<strong>:</strong> &#39;YOUR_PASSWORD&#39;,<br>    },<br>    encryptionKey: encryptionKey<br>})</pre><pre>const keypair = storjInstance.generateKeyPair()</pre><pre>const privateKey = keypair.getPrivateKey()<br>const publicKey = keypair.getPublicKey()</pre><pre>console.log(&quot;Private key:&quot;, privateKey)<br>console.log(&quot;Public key:&quot;, publicKey)</pre><pre>storjInstance.registerKey(publicKey)</pre><p>You may notice the differencies from previous library, while creating the <strong>storjInstance</strong>. The <strong>generateKeyPair</strong> method will create private/public keys, which you can get with <strong>getPrivateKey</strong> and <strong>getPublicKey</strong> methods. If you have private key, but you don’t remember your public key, you can pass your private key to <strong>generateKeyPair(privateKey)</strong> method to get the public key. Do not confuse this keys with encryption key, which is used to encrypt and decrypt the data. We are using generateEncryptionKey method to get a valid encryption key. Please store the key in a safe place, as you can not use your files, in the case, if you will lost the key. The encryption key should be a list of words separated with backspace. One thing which we have missed is, that only you should have <strong>private key</strong>, while all users from the network, as well as the <strong>StorJ bridge</strong>, should have the public key. How we can inform them all? <strong>StorJ</strong> is providing <strong>storjInstance.registerKey(publicKey, [callback])</strong> method for registering the <strong>public key</strong>. There are two supplementary methods for dealing with public keys, the <strong>storjInstance.getKeyList([cb])</strong> method and <strong>storjInstance.getKeyList([cb])</strong> method.</p><p>Now we are ready to create a new storjInstance, without username is password. Note that inside a browser, mobile app, or any other codebase, which will be running on client’s device, it is important to use only public key, We should avoid username and password from those codebase.</p><pre>const StorJ = require(&#39;storj&#39;)</pre><pre>const storjInstance = new StorJ({<br>    bridge: &#39;https://api.storj.io&#39;,<br>    key: publicKey,<br>    encryptionKey: encryptionKey<br>})</pre><p>As the previous library, you can read, create, delete buckets , using the following methods, which are self explaining:</p><p><strong>storjInstance.getBuckets([cb(err, buckets)])<br>storjInstance.createBucket(bucketName, [cb(err, bucket)])<br>storjInstance.getBucket(bucketId, [cb(err, bucket)]<br>storjInstance.deleteBucket(bucketId, [cb(err)]))</strong></p><p>There is also a new method <strong>storjInstance.makePublic(bucketId, [perms], [cb(e)])</strong>. What is it doing? With new library, you can allow every user to read data from your bucket, as well you can allow every user to store data in your bucket. The <strong>perms</strong> argument is an array of strings which is having the permissions you want the users to have, “PULL” for downloading, “PUSH” for uploading. For example a valid argument for <strong>perms</strong> will be [&quot;PULL&quot;, &quot;PUSH&quot;]</p><p>For getting the list of files from bucket you can use <strong>storjInstance.getFileList(bucketId, [cb(err, files)])</strong> method, and for removing the file from the bucket you can use<strong> storjInstance.deleteFile(bucketId, fileId, [cb(e)]) </strong>method.</p><h4><strong>What about file uploads and downloads?</strong></h4><p>The API has slightly changed for uploading and downloading the files.<br>For uploading the file we can use following codestorjInstance.createFile(bucketId, fileName, file, [opts], [cb]) where the file is either a plain text <strong>string</strong>, a <strong>BLOB</strong>, or a <strong>readable stream</strong>. Note that filename is NOT your file path, but you can upload your file by passing <strong>fs.createReadStream(filepath) </strong>instead.<br>Now let’s move to downloading the files. You can download the file with following method. var file = storj.getFile(bucketId, fileId, [cb()]). Now let’s look to to the file object. You can create a stream by file.createReadStream() method, you can a get a buffer with file.getBuffer(cb(e, buffer){}) method, if you are inside a browser, you can get a blob with file.getBlob(cb(e, blob) {}) . For browser there are two additional methods file.appendTo and file.renderTo , Please refer to <a href="https://github.com/Storj/storj.js#fileappendtorootelem-opts-function-cbe-elem--browser-only"><em>documentation</em></a>, as they are more advanced functionality.</p><h4>Wrap Up</h4><p>This tutorial intended to be first in a series about how to become blockchain developer. The more practical youtube video will come soon. Do not judge too hard, they are my first posts :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911d8416231d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anagram Finding app with Python Part 2: Enter Toga]]></title>
            <link>https://medium.com/@promentol/anagram-finding-app-with-python-part-2-enter-toga-2f3ae49d6f8a?source=rss-37db62e72843------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f3ae49d6f8a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gui]]></category>
            <category><![CDATA[toga]]></category>
            <dc:creator><![CDATA[Narek Hovsepyan]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 08:19:21 GMT</pubDate>
            <atom:updated>2018-02-02T08:43:03.111Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Welcome back!</strong></p><p>In the second part of our tutorial, we are going to create a GUI for our anagrama solver application. For newcomers refer <a href="https://medium.com/@promentol/anagram-finding-app-with-python-part-1-algorithm-implementation-b2ccbf7208be">here</a> for the <a href="https://medium.com/@promentol/anagram-finding-app-with-python-part-1-algorithm-implementation-b2ccbf7208be">first</a> part. We are going to create a GUI using the wonderful library Toga.</p><h4>Enter Toga</h4><p>There are numerous libraries for creating GUI, like Tkinter, PyQt, PySide, WxPython and etc. Why to choose Toga? First for it’s simplicity, you will see how easy it will be to install and develop on top of Toga. Second and more important feature is, that Toga is rendering native widgets, and the apps created by Toga will look like native because they will be native off course! For macOS Toga will use Cocoa backend, for Linux GTK and etc. At the moment of writing this article Toga have also experimental support of Android and iOS. For more information about Toga, you can look for <a href="http://toga.readthedocs.io/en/v0.2.13/philosophy.html">official documentation</a>.</p><h4>Graphical User Interface (GUI) design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxAEkwBFH5_YWD4IZ85slw.png" /></figure><p>We may need to have an input for writing an anagrama string, a button which will trigger solving procedure, and some place to show the result. I’ve decided to show in a one column table, but you are free to choose whatever you would like. We can mentally breakdown the application in functional components for structuring GUI elements inside window like in the picture bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3k3wquSe-_onwOTH819dHA.jpeg" /><figcaption>Component breakdown</figcaption></figure><p>We will have a label, an input and a button, placed inside a box which will be placed in the left part. We will have a table for the word list, placed in the right part of the window.</p><h4>Coding is fun!</h4><p>We are going to modify the code from the first part to add GUI. For those who didn’t completed the first part, you can download the existing codebase <a href="https://github.com/promentol/anagram-pyhton-toga/tree/0778cef301df66638d755df258fbb45baf04418c">here</a>.</p><p>Lets install toga first. Note that it is working only with Python 3+ versions. We are going to use <strong>pip </strong>to install toga, you will see how easy it is.</p><pre>pip3 install toga</pre><p>At the moment of writing this article, there are some problems with macOS High Sierra, so if you are using this version of macOS, the bug is fixed in github, so just install that version from github</p><pre>pip3 install git+https://github.com/pybee/toga.git@f839f0e910acf974f9372554339f8a5be6ae5a98</pre><p>Now let’s rename <strong>solver.py</strong> to <strong>gui.py</strong> and add the following boiler plate code</p><pre>import toga<br>from toga.style.pack import *</pre><pre>def build(app):<br>    pass</pre><pre>def main():<br>    return toga.App(&#39;Anagram App&#39;, &#39;org.promentol.anagrama&#39;, startup=build)</pre><pre>if __name__ == &#39;__main__&#39;:<br>    main().main_loop()</pre><p>What we are doing is just importing Toga, creating an empty application with title “Anagram App” and package name “org.promentol.anagrama”. We are specified <em>startup=build</em>, where build function will be entry point of our application. Now we are going to modify our build function. Let’s add the following inside build function</p><pre>left_box = toga.Box()<br>left_box.style.update(direction=COLUMN, padding=10)<br>left_input = toga.TextInput()<br>left_label = toga.Label(&#39;Anagram&#39;, style=Pack(text_align=LEFT))<br>solve_button = toga.Button(&#39;Solve&#39;)</pre><pre>left_box.add(left_label)<br>left_box.add(left_input)<br>left_box.add(solve_button)<br>left_box.style.update(flex=1, padding=5)</pre><p>Well, we created the label, the input and the “Solve” button, now let’s move forward and create the table</p><pre>table = toga.Table([&#39;Words&#39;])<br>table.style.update(flex=1, padding=5)</pre><p>The <strong><em>toga.Table([‘Words’])</em></strong><em> </em>method, is taking an argument, a list of strings, which will be the header titles of the table’s column. As our table have only one column, we are passing only one string. You can experiement by adding multiple titles and so on. You may also see that we are updating styles with <strong><em>flex=1</em></strong>. It is just adding a flexible size, so the component will stretch sizes if we resize the window. The padding argument is quite similiar to the padding we know from CSS, refer Toga or CSS documentation for more information.</p><p>Now let’s finish the GUI skeleton, by placing our box and table inside main window. We are going to create another wrapper box and return that new box inside <strong><em>build(app)</em></strong> method.</p><pre>main_box = toga.Box()<br>main_box.add(left_box)<br>main_box.add(table)<br>return main_box</pre><p>You can see the final code of <strong>gui.py </strong><a href="https://github.com/promentol/anagram-pyhton-toga/blob/77ffc12918d23e78632d8507b51234ab728524fe/gui.py">here</a>. Now let’s run the application and see the result.</p><pre>python gui.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUmo5JRVbKp4-T2UFzEQPw.png" /><figcaption>The result of the <strong>gui.py</strong></figcaption></figure><h4>Let’s add some logic</h4><p>Congratulations! You have just created your first graphical user interface with Toga. Now we will move one step forward, and add solve button’s click handler and business logic.</p><p>First let’s change how we are creating the solve button. We will add new argument <strong>on_press </strong>a function which will be called when someone will press the button. It will pass one argument, which will be a pointer towards the button.</p><pre>...<br>def button_handler(widget):<br>    print(left_input.value)</pre><pre>solve_button = toga.Button(&#39;Solve&#39;, on_press=button_handler)<br>...</pre><p>Now if we will run the app, we will see by click to the “solve” button, it will print in the console the value written in the input. By calling <strong>solver(left_input.value)</strong>, we will get the desired list of words we need to display. We can use <strong>table.data</strong> attribute to assign the data</p><pre>...<br>def button_handler(widget):<br>    table.data = solver(left_input.value)</pre><pre>solve_button = toga.Button(&#39;Solve&#39;, on_press=button_handler)<br>...</pre><p>Now we are ready to run the application. Write the word “duckstone” in the input and let’s see what valid words anagram it can be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXSYGYY-gWqd9NY5T04B5Q.png" /><figcaption>Almost finished. Why it is showing only first letters?</figcaption></figure><p>Any suggestions why it is displaying only the first letters of the words?<br>Well, the <strong>table.data</strong> argument should be a list of list. As we are passing a list of strings, it is explicitly converting string to list of letters.The solution will be to convert our list of strings to a list of lists of one string, e.g. [“asd”, “dsa”] to [[“asd”], [“dsa”]] for example. We will use Python’s map function and lambdas to accomplish that</p><pre>...<br>def button_handler(widget):<br>    table.data = list(map(lambda x: [x], solver(left_input.value)))</pre><pre>solve_button = toga.Button(&#39;Solve&#39;, on_press=button_handler)<br>...</pre><p>The <strong>map()</strong> function is taking two arguments. The first one should be a function which will be applied to the every single element of the second argument, and return a new collection. You can find more information <a href="http://book.pythontips.com/en/latest/map_filter.html">here</a>. We are wrapping it inside a <strong>list() </strong>method to convert to a list.</p><p>Now we are ready to run application and see the result</p><pre>python gui.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2St_nHxhthLgWAqft563A.png" /><figcaption>The word <strong>“duckstone” </strong>is an anagram of the word <strong>“unstocked”</strong></figcaption></figure><h4>Wrap Up</h4><p>Hope you enjoyed the second part of the Python and Toga tutorial<br>Github: <a href="https://github.com/promentol/anagram-pyhton-toga">https://github.com/promentol/anagram-pyhton-toga</a><br>Youtbe: Coming Soon</p><p>You can refer to officials tutorials about Toga here<br><a href="http://toga.readthedocs.io/en/latest/tutorial/index.html#tutorial">http://toga.readthedocs.io/en/latest/tutorial/index.html#tutorial</a></p><p>Feel free to write any comments or questions. Follow me to get more tutorials and lifestyle stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f3ae49d6f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anagram Finding app with Python Part 1: Algorithm Implementation]]></title>
            <link>https://medium.com/@promentol/anagram-finding-app-with-python-part-1-algorithm-implementation-b2ccbf7208be?source=rss-37db62e72843------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ccbf7208be</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gui]]></category>
            <dc:creator><![CDATA[Narek Hovsepyan]]></dc:creator>
            <pubDate>Thu, 01 Feb 2018 12:19:32 GMT</pubDate>
            <atom:updated>2018-02-02T08:25:44.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s0XVi-ORrxmVvt5qHxGq1g.jpeg" /><figcaption>Python is Awesome</figcaption></figure><p>What is anagram? An <strong>anagram</strong> is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example the word <em>boats </em>can be rearranged into “boast”.</p><p>Sometimes it is easy to recover original word from one if its anagrams, but on most cases it will be almost impossible to recover the original one mentally. Just take a look to this example: the anagram “cedknotsu” is rearranged form of “duckstone”. Is there any algorithm for recovering original word from it’s anagram? In this two part tutorial we will build an application, which will take an anagram as an input and show all possible valid anagram words.</p><p>Let’s observe those two words “cedknotsu” and “duckstone”. What they have in common? Yes the first thing which is coming in our mind is their length. Anything else? Let’s sort the letters of word “cedknotsu” in alphabetical order. We will get “cdeknostu”. What if we will sort the letters of the word “duckstone”? We will get “cdeknostu” again. So it is trivial that if we will sort the letters of two anagram strings, we will get the same string. This is the key for solution.</p><h4><strong>The Algorithm</strong></h4><p>Let’s define the task clearly. We have a string <strong>a</strong>, we need to find a valid word <strong>b</strong>, which will be an anagram of the string<strong> a</strong>.<strong><br></strong>Let’s describe the algorithm. We have a list of words, let’s sort all of the letters of our words, and keep pairs of sorted letters string and original strings in a <strong>hash table</strong>. After this preprocessing, we can sort the letters of the string <strong>a</strong>, then look to our hash table and find it’s corresponding pair.</p><h4>The Code</h4><p>We can get the list of all english words from this repository <a href="https://github.com/dwyl/english-words">https://github.com/dwyl/english-words</a>. We will download words.txt file, then in the same directory we will create <strong>preprocess.py</strong>.</p><p>Let’s create an empty dictionary</p><pre>dict = {}</pre><p>Then we are opening the <em>words.txt </em>file</p><pre>f = open(&quot;words.txt&quot;, &quot;r&quot;)</pre><p>We are passing<strong> “r”</strong> as a second argument, to indicate that it is for read only. Let’s go over all lines inside the file, and sort the letters of each word to store in <strong>dict</strong>. Note that one anagram can have multiple original valid words, so we will store our <strong>dict </strong>as a hash table from string to list of strings. We will also preprocess each word by making all the letters lowercase.</p><pre>for line in f.readlines():<br>    word = line.strip().lower()<br>    sortedLetters = sorted(list(word))<br>    sortedWord = &quot;&quot;.join(sortedLetters)<br>    if sortedWord in dict:<br>        dict[sortedWord].append(word)<br>    else:<br>        dict[sortedWord] = [word]</pre><p>We have finished the preprocessing, so let’s dump our <strong>dict </strong>to a file, so we can import it in other scripts. We will use python’s <strong>pickle </strong>module. We will open a file and use <strong>pickle.dump()</strong> to serialize our <strong>dict</strong> to a file.The second argument <strong>”wb”</strong> to the <strong>open() </strong>method is statding for <strong>“write binary”</strong></p><pre>import pickle<br>with open(&#39;words.pickle&#39;, &#39;wb&#39;) as f:<br>    pickle.dump(dict, f)</pre><p>Now we are ready to create a script, which will recover the original word by it’s anagram. Let’s create a new fie called <strong>solver.py</strong> and add following code.</p><pre><strong>with</strong> open(&#39;words.pickle&#39;, &#39;rb&#39;) <strong>as</strong> f:<br>    dict = pickle.load(f)</pre><p>At this point we will have the dictionary ready and we can create the solver function</p><pre>def sort_letters(a):<br>    return &quot;&quot;.join(sorted(list(a)))</pre><pre>def solver(a):<br>    sorted_a = sort_letters(a)<br>    if sorted_a in dict:<br>        return dict[sorted_a]<br>    else:<br>        return []</pre><p><strong>list(a)</strong> will turn the string into list of letters, the <strong>sorted()</strong> method will return a new sorted list, while <strong>“”.join()</strong> method is a trick to get a new string from a list of letters. Now the <em>solver(a) </em>method will find the anagrams which are valid words. We can recover the original word of the anagram “cedknotsu”, just by typing this code</p><pre>solver(&quot;cedknotsu&quot;)</pre><p>It will return an array, with two words “duckstone” and “unstocked”</p><p><strong>Wrap Up</strong></p><p>Hope you enjoyed first part, In the second part we will add GUI<br>Github: <a href="https://github.com/promentol/anagram-pyhton-toga">https://github.com/promentol/anagram-pyhton-toga</a><br>Youtbe: Coming Soon</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ccbf7208be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>