<?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 2infiniti (Justin Hsiao) on Medium]]></title>
        <description><![CDATA[Stories by 2infiniti (Justin Hsiao) on Medium]]></description>
        <link>https://medium.com/@2infiniti?source=rss-39cf298c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q-NQpqXVO0hkOgFxtsBpDg.jpeg</url>
            <title>Stories by 2infiniti (Justin Hsiao) on Medium</title>
            <link>https://medium.com/@2infiniti?source=rss-39cf298c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:35:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@2infiniti/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[MyIconWallet Mobile App Security Audit]]></title>
            <link>https://medium.com/@2infiniti/myiconwallet-mobile-app-security-audit-c56b4d5a2099?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c56b4d5a2099</guid>
            <category><![CDATA[coinex]]></category>
            <category><![CDATA[miw]]></category>
            <category><![CDATA[icon-blockchain]]></category>
            <category><![CDATA[icon-project]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Wed, 27 May 2020 04:14:19 GMT</pubDate>
            <atom:updated>2020-05-27T04:21:18.488Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an audit report of MyIconWallet mobile app, based on the code from its github repository’s master branch as of May 27th.</p><h3><strong>Scope of Audit</strong></h3><p>In this audit we’ll be focusing on the management and usage of two crucial security components — <strong>PIN and Private Key</strong>. This audit is not intended to cover code legibility, maintainability or other UI/UX related features.</p><h3><strong>PIN Management</strong></h3><p>There are 4 places within the app that involve user PIN — Creating a PIN during initial setup, unlocking screen, changing PIN and resetting MyIconWallet. A common lib utils/accessCode.js is implemented with saveAccessCode(), checkAccessCode() and clearAccessCode() methods, utilizing <a href="https://docs.expo.io/versions/latest/sdk/crypto/">expo-crypto</a> to enable encrypted data and <a href="https://docs.expo.io/versions/latest/sdk/securestore/">expo-secure-store</a> to enable encryption and secure store of key-value pairs.</p><h4><strong>Creating a PIN during initial setup</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Z7C_Bd2Bybr7Hjk0RdWgEw.png" /></figure><p>Users are prompted to input a new PIN, then confirm the PIN, through 2 screens. The corresponding files for the 2 screens are located in screens/onboarding/CreateAccessCode.js and screens/onboarding/ConfirmAccessCode.js with proper input validations. After confirmation SaveAccessCode() from the common lib is called, which encrypts the access code in SHA512, highest security level from the lib. unlock() fromcomponents/Data.js is also called, so users don’t have to re-enter PIN while creating/restoring wallet during onboarding process.</p><h4>Unlocking Screen</h4><p>The app only requires one PIN confirmation during a session in components/Navigation.js, or displays screens\UnlockApp.js which uses the common lib’s checkAccessCode() to check access code then calls for unlock() to reveal the main app screen.</p><h4>Changing PIN</h4><p>Change PIN confirms current PIN atscreens/CurrentAccessCode.js then chooses new PIN at screens/ChooseAccessCode.js and finally confirms at screens/ConfirmAccessCode.js. The entire process is utilizing the same functions from create PIN during initial setup.</p><h4>Resetting MyIconWallet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*sq0PFPzHFG9GI5IzSppggQ.png" /></figure><p>Resetting the app will remove user created/loaded wallets, this is initiated at screens/ResetApp.js then screens/ConfirmReset.js which checks the PIN usingcheckAccessCode() from the common library. Then resetWallets() is called from component/Wallet.js which calls clearAccessCode() from the common lib, which deletes the access code from the database.</p><h3>Private Key Usage</h3><p>Private keys are interacted with in 4 areas — creating a wallet, restoring a wallet, unlocking the app and signing transactions.</p><h4>Creating a wallet</h4><p>Users can create a wallet either during initial onboarding screen atscreens/onboarding/NameWallet.js or from settings -&gt; manage wallet -&gt; create wallet at screens/CreateWallet.js. createWallet()from components/Wallet.js is then invoked to create a wallet using icon’s javascript SDK. After the wallet is created and addWalletToDatabase() is called, the wallet’s private key will be securely encrypted and stored using SecureStore under the key of the wallet’s address to the local database of the mobile phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qS4O8J7sC8pSElSmc_auOA.png" /></figure><h4>Restoring a wallet</h4><p>Users can restore a wallet either during initial onboarding screen at screens/onboarding/UnlockKeystore.js or from settings -&gt; manage wallet -&gt; restore a wallet at screens/RestoreWallet.js. accessWalletWithKeystore() from components/Wallet.js which also calls addWalletToDatabase() to store to local database using SecureStore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*a6oRWMOAA80Yg7iUh7zsAg.png" /></figure><h4>Unlocking the app</h4><p>When the app is unlocked, Wallet.js invokes loadWallets() to retrieve wallets from the local database with getWalletsFromDatabase() at utils/database.js. This loads all private keys for each wallet from the local database stored by SecureStore. The retrieved keys are then passed to icon-sdk-js using IconWallet.loadPrivatekey() to load each wallet using the private key.</p><h4>Signing transactions</h4><p>Transactions are handled at components/IconService.js where most operations are usingSignedTransaction created by icon-sdk-js. The only exception is rpcTransaction() which utilizes IconWallet&#39;s sign()function directly.</p><h3>Private key storage</h3><p>MyIconWallet uses SecureStore for storing all private keys.</p><p><a href="https://docs.expo.io/versions/latest/sdk/securestore/">https://docs.expo.io/versions/latest/sdk/securestore/</a></p><p><strong>iOS</strong></p><p>Values are stored using the <a href="https://developer.apple.com/documentation/security/keychain_services">keychain services</a> as kSecClassGenericPassword. iOS has the additional option of being able to set the value&#39;s kSecAttrAccessible attribute, which controls when the value is available to be fetched.</p><p><strong>Android</strong></p><p>Values are stored in <a href="https://developer.android.com/training/basics/data-storage/shared-preferences.html">SharedPreferences</a>, encrypted with <a href="https://developer.android.com/training/articles/keystore.html">Android&#39;s Keystore system</a>.</p><p>This is the most secure place to store data on an iPhone and Android.</p><h3>Private keys are encrypted</h3><p>While private keys are stored in a secure storage on both Android and iPhone, the private keys also encrypted with a master key derived from the passcode users enter. This is via PBKDF2. This is the same method (and iterations) used by ICONex mobile.</p><h3>Upgrade PIN code to a Password</h3><p>Users have the option to increase security by changing their PIN code to a complex alphanumeric password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*nbYEKbINtQBP0Nk8SXz-CA.png" /></figure><h3>Confirm every transaction</h3><p>Users have the option to confirm every transaction with their passcode if they prefer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*hKuVCoUL90DyrGdv5An6Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*TH8G7C2DthKwF6eLcRo9rw.png" /></figure><h3>Summary</h3><p>In this audit we find MyIconWallet app’s implementation clean and intuitive without any obscurity. The app contains the same level of security as ICONex with the use of PBKDF2 to secure the storage of private keys on top of an already secure storage on Android and iPhone, providing double encryption. The app provides great usability for users with the flexibility of additional security where required. Keep in mind if you have multiple wallets they do share the same passcode.</p><p>The ReliantNode team have advised they are already working on Ledger support for MyIconWallet and with its release will provide the most secure key management available with a seamless user experience for ICON transfers, governance and DApp access.</p><p>Based on our review MyIconWallet has provided a great alternative to ICONex for mobile users with the same level of security while providing access to DApps and governance on the go.</p><p>2infiniti — ICX Station Tech Lead, ICON Foundation Global Team</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c56b4d5a2099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICON High Availability Cluster — Nginx + Corosync + Pacemaker]]></title>
            <link>https://medium.com/@2infiniti/icon-high-availability-cluster-nginx-corosync-pacemaker-e0840f953806?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0840f953806</guid>
            <category><![CDATA[ha]]></category>
            <category><![CDATA[prep]]></category>
            <category><![CDATA[no]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[icx]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Sun, 27 Oct 2019 12:51:04 GMT</pubDate>
            <atom:updated>2019-10-27T12:58:11.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Highly Available Nodes on ICON — Stage 2: HA Cluster with Nginx and P-Rep Node</h3><p>This guide is based on Ubuntu 18.04 on AWS</p><p>In the last tutorial: <a href="https://medium.com/@2infiniti/creating-highly-available-nodes-on-icon-stage-1-active-passive-failover-with-pacemaker-and-a9d56b1484da">Creating Highly Available Nodes on ICON — Stage 1: Active/Passive Failover with Pacemaker and Corosync</a>, we covered how to create an active/passive failover configuration using AWS Elastic IP. We utilized corosync and pacemaker for resource management and network pulse checks, and in case of node failure, a backup server will automatically take over node operations. In this tutorial we will extend on the previous one and create a highly available cluster using the same technology stack, this time with two docker containers in each host, nginx and P-Rep node. The main usage of nginx is to create a throttle in order to rate limit requests, and to filter requests based on whitelisted IPs, this creates a layer of protection in front of our real P-Rep node. For more information on nginx usage under ICON network, please consult this document: <a href="http://icondev.io/docs/how-to-use-nginx-to-prevent-ddos-attacks">How to use nginx to prevent DDoS attacks</a></p><h3><strong>Preparation</strong></h3><h4>AWS Instance</h4><p>Create two instances on AWS under two availability zones, instance 1 (az-a) on us-east-2a and instance 2 (az-b) on us-east-2b. Follow this previous tutorial on node installation using docker: <a href="https://medium.com/@2infiniti/icon-node-installation-docker-aws-35028e4a5819">ICON Node Installation — Docker + AWS</a>. Ignore docker-compose.yml as we’ll be creating a new one in this tutorial using newer P-Rep images, in addition an nginx docker image. This is the architecture we’re aiming to create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXpJXHkIU-k3kwwnVpZLYw.png" /><figcaption>Cluster under two availability zones</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGiHfOoUW2doItemNJgdtg.png" /><figcaption>Each host will run two docker containers, with nginx in front of p-rep node</figcaption></figure><p>Let’s rename the hostnames for better legibility <br>(both servers)</p><pre>change hostname<br>$ sudo hostnamectl set-hostname az-a<br># similarly for az-b, then reboot<br>$ systemctl reboot</pre><p>edit hosts file <br>(both servers)</p><pre>/etc/hosts</pre><pre>127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4<br>::1         localhost localhost.localdomain localhost6 localhost6.localdomain6</pre><pre>172.31.10.168    az-a-hb<br>172.31.16.135    az-b-hb</pre><p>ping the other server see if host is resolving<br>(both servers)</p><pre>$ ping az-b-hb</pre><pre>64 bytes from az-b-hb (172.31.16.135): icmp_seq=1 ttl=64 time=0.305 ms<br>64 bytes from az-b-hb (172.31.16.135): icmp_seq=2 ttl=64 time=0.286 ms<br>64 bytes from az-b-hb (172.31.16.135): icmp_seq=3 ttl=64 time=0.276 ms</pre><h4><strong>Docker Compose</strong></h4><p>(both servers)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a71e2e0dd923fd0f6c2af31df28a5c/href">https://medium.com/media/e4a71e2e0dd923fd0f6c2af31df28a5c/href</a></iframe><p>In this tutorial we’re adding in a new docker service, namely nginx, to handle traffic in front of our P-Rep node. Nginx will be able to rate limit the requests received in order to prevent DDoS attacks and we’ll also leverage nginx to receive requests from a whitelisted IP list(we’ll follow up with an automated script to update this list). The way to connect nginx to our prep node is via NODE_CONTAINER_NAME: &quot;prep-node&quot;. For a full list of nginx environment variables please consult this documentation: <a href="https://github.com/JINWOO-J/nginx_docker">https://github.com/JINWOO-J/nginx_docker</a></p><p>Spin up the containers per usual<br>(both servers)</p><pre>$ sudo docker-compose up -d</pre><p>next check on the status (it’ll take a while for p-rep node to sync all the blocks, then it’ll turn to healthy status)</p><pre>$ sudo docker ps -a</pre><p>You should have two containers, prep-node:1910211829xc2286d and nginx:1.17.1.</p><p>We’ll also need to create another docker-compose file, call it docker-compose.backup.yml. This is essentially the same as our docker-compose earlier but for our backup node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/656b076d120bf7168e85e8c94af2e92f/href">https://medium.com/media/656b076d120bf7168e85e8c94af2e92f/href</a></iframe><h4>Pacemaker and Corosync</h4><p>You can follow <a href="https://medium.com/@2infiniti/creating-highly-available-nodes-on-icon-stage-1-active-passive-failover-with-pacemaker-and-a9d56b1484da">this tutorial</a> for cluster setup using crm, in the last tutorial we configured a single EIP that acts as a floating IP, which points to the active server. In this tutorial we’ll also configure an active EIP that acts as a floating IP, in addition a backup EIP in case when our active EIP stops functioning. We’ll also configure using pcs this time as it seems to be the choice by the foundation, so instructions will become easier to follow.</p><p>(both servers)</p><pre># Update and install <br>$ sudo apt-get -y update<br>$ sudo apt-get install pacemaker<br>$ sudo apt install pcs<br># Verify <br>$ pacemakerd --version<br>Pacemaker 1.1.18<br>Written by Andrew Beekhof<br>$ corosync -v<br>Corosync Cluster Engine, version &#39;2.4.3&#39;<br>Copyright (c) 2006-2009 Red Hat, Inc.</pre><p>then configure the corosync.conffile</p><pre>/etc/corosync/corosync.conf</pre><pre>totem {<br>    version: 2<br>    cluster_name: peer_cluster<br>    secauth: off<br>    transport: udpu<br>}</pre><pre>nodelist {<br>    node {<br>        ring0_addr: az-a-hb<br>        nodeid: 1<br>    }</pre><pre>node {<br>        ring0_addr: az-b-hb<br>        nodeid: 2<br>    }<br>}</pre><pre>quorum {<br>    provider: corosync_votequorum<br>    two_node: 1<br>}</pre><pre>logging {<br>    to_logfile: yes<br>    logfile: /var/log/corosync/corosync.log<br>    to_syslog: yes<br>}</pre><p>enable the services on system boot</p><pre>$ systemctl enable corosync<br>$ systemctl enable pacemaker</pre><h4>Create Peer and Backup Peer Services</h4><p>(both servers)</p><p>Create peer.service under /lib/systemd/system/</p><pre>[Unit]<br>Description=Loopchain Peer<br>After=docker.service</pre><pre>[Service]<br>Type=oneshot<br>RemainAfterExit=yes<br>StandardError=null<br>StandardOutput=null<br>WorkingDirectory=/home/ubuntu<br>ExecStartPre=/home/ubuntu/cluster.sh<br>ExecStart=/usr/local/bin/docker-compose -f /home/ubuntu/docker-compose.yml up -d<br>ExecStop=/usr/sbin/pcs resource disable Backup<br>ExecStop=/usr/local/bin/docker-compose -f /home/ubuntu/docker-compose.yml down</pre><pre>[Install]<br>WantedBy=multi-user.target</pre><p>and backup_peer.service also under /lib/systemd/system/</p><pre>[Unit]<br>Description=Loopchain Backup_peer<br>After=docker.service</pre><pre>[Service]<br>Type=oneshot<br>RemainAfterExit=yes<br>StandardError=null<br>StandardOutput=null<br>WorkingDirectory=/home/ubuntu<br>ExecStartPre=/home/ubuntu/cluster.sh<br>ExecStart=/usr/local/bin/docker-compose -f /home/ubuntu/docker-compose.yml up -d<br>ExecStop=/usr/local/bin/docker-compose -f /home/ubuntu/docker-compose.yml down</pre><pre>[Install]<br>WantedBy=multi-user.target</pre><p>enable the services on system boot</p><pre>$ sudo systemctl enable peer.service<br>$ sudo systemctl enable backup_peer.service</pre><h4>Change DB Directory Name</h4><p>(both servers)</p><p>The services we just created, besides the basic docker up/down’s, we also inserted a bash script cluster.sh, this is to change the DB directory name based on the node IP. The reason for this is because the IP changes when the backup node becomes master. If the IP changes, the directory structure of LevelDB will also change. When the backup node is changed to the master node, the IPaddr also changes. Loopchain also changes the structure of LevelDB when IPaddr is changed. We’ll overcome this by changing the directory name based on IP, create the files under the same root as docker-compose</p><pre>#!/bin/bash</pre><pre>DBDIR=&quot;/home/ubuntu/data/loopchain&quot;<br>MYIP=`curl <a href="http://169.254.169.254/latest/meta-data/public-ipv4%60">http://169.254.169.254/latest/meta-data/public-ipv4`</a><br>ASISNAME=`ls -t ${DBDIR}/.storage| head -1`<br>TOBENAME=&quot;db_${MYIP}:7100_icon_dex&quot;</pre><pre>if [ &quot;$ASISNAME&quot; == &quot;$TOBENAME&quot; ];then<br>echo &quot;Match&quot;<br>else<br>        if [ ! -d &quot;$DBDIR/.storage&quot; ];then<br>        mkdir -p $DBDIR/.storage/$TOBENAME<br>        else<br>        mv ${DBDIR}/.storage/${ASISNAME} ${DBDIR}/.storage/${TOBENAME}<br>        fi<br>fi</pre><p>Add executable permission to the file</p><pre>$ sudo chmod +x cluster.sh</pre><h4><strong>AWS CLI Configuration</strong></h4><ol><li><a href="http://aws.amazon.com/">Log in to your AWS Management Console</a>.</li><li>Click on your user name at the top right of the page.</li><li>Click on the Security Credentials link from the drop-down menu.</li><li>Find the Access Credentials section, and copy the latest Access Key ID.</li><li>Click on the Show link in the same row, and copy the Secret Access Key.</li></ol><pre>$ sudo apt update<br>$ sudo apt install aws-cli<br># change to root, this is necessary<br>$ sudo su <br>$ aws configure</pre><p>For the region name, example is us-east-1</p><h4>Start Cluster</h4><p>Now we’re ready to start the cluster, setup a password first for our user hacluster<br>(both servers)</p><pre>$ passwd hascluster</pre><p>now run PaceMaker GUI daemon</p><pre>$ systemctl start pcsd<br>$ systemctl enable pcsd</pre><p>then configure the cluster</p><pre># authenticate the user first<br>$ pcs cluster auth az-a-hb az-b-hb<br>$ pcs cluster setup --name peer_cluster az-a-hb az-b-hb transport udpu</pre><p>start the cluster</p><pre>$ pcs cluster start --all --wait=60</pre><h4>Cluster Resources</h4><p>Create PCS config<br>(one server)</p><pre>$ sudo pcs cluster cib tmp-cib.xml<br>$ sudo cp tmp-cib.xml tmp-cib.xml.deltasrc<br>$ sudo pcs -f tmp-cib.xml property set stonith-enabled=false</pre><p>Create EIP agent<br>(one server)</p><pre>$ sudo pcs -f tmp-cib.xml resource create awseip-peer ocf:heartbeat:awseip allocation_id=<strong>{your EIP allocation ID}</strong> elastic_ip=<strong>{your elastic IP}</strong> op migrate_from interval=0s timeout=30s migrate_to interval=0s timeout=30s monitor interval=20s timeout=30s start interval=0s timeout=30s stop interval=0s timeout=30s validate interval=0s timeout=10s</pre><p>Enable Peer Service Resource</p><pre>$ sudo pcs -f tmp-cib.xml resource create peerservice systemd:peer op monitor interval=60 timeout=100 start interval=0s timeout=100 stop interval=0s timeout=100</pre><p>Backup Elastic IP</p><pre>$ sudo pcs -f tmp-cib.xml resource create awseip-backup ocf:heartbeat:awseip allocation_id=<strong>{your EIP allocation ID}</strong> elastic_ip=<strong>{your backup elastic IP}</strong> migrate_from interval=0s timeout=30s migrate_to interval=0s timeout=30s monitor interval=20s timeout=30s start interval=0s timeout=30s stop interval=0s timeout=30s validate interval=0s timeout=10s</pre><p>Backup Peer Resource</p><pre>$ sudo pcs -f tmp-cib.xml resource create backupservice systemd:backup_peer op monitor interval=60 timeout=100 start interval=0s timeout=100 stop interval=0s timeout=100</pre><p>Peer Group</p><pre>$ sudo pcs -f tmp-cib.xml resource group add Peer awseip-peer peerservice</pre><p>Backup Group</p><pre>$ sudo pcs -f tmp-cib.xml resource group add Backup awseip-backup backupservice</pre><p>Add Colocation</p><pre>$ sudo pcs -f tmp-cib.xml constraint colocation add Backup with Peer -INFINITY id=colocation-Backup-Peer--INFINITY</pre><p>Apply Configuration</p><pre>$ sudo pcs cluster cib-push tmp-cib.xml diff-against=tmp-cib.xml.deltasrc</pre><p>Now check the status of our cluster, if all is well, you should have something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*ZZg-fHulczT4jtYmMBR3UQ.png" /></figure><p>Which reflects exactly what we displayed in the first architecture diagram.</p><h4>Testing Failover State</h4><p>Right now the active node is az-a-hb, let’s take the node down and see what happens.</p><pre>$ sudo pcs cluster standby az-a-hb<br>$ sudo pcs status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*SgE_5hRA6yzJu0zAjGxy9w.png" /></figure><p>After some time (about a minute), check AWS, you’ll notice that our active EIP is reallocated to az-b-hb, effectively failing over to the backup node. To restore the node, run</p><pre>$ sudo pcs cluster unstandby az-a-hb</pre><p>The active node is still az-b-hb, reboot it see what happens</p><pre>$ sudo systemctl reboot</pre><p>Check back to AWS again, as expected, the EIP points back to az-a-hb. We now have an HA cluster with nginx in front of our p-rep node, next we will apply IP whitelist renewal described in this documentation: <a href="https://www.icondev.io/docs/how-to-use-nginx-to-prevent-ddos-attacks">How to use nginx to prevent DDoS attacks</a>, when the automation script becomes available. We will be writing another tutorial in part 3 to conclude our node architecture setup.</p><h4>Common Cluster Commands</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33d1d0587dba6d61ec7cebe16e9ba699/href">https://medium.com/media/33d1d0587dba6d61ec7cebe16e9ba699/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0840f953806" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Highly Available Nodes on ICON — Stage 1: Active/Passive Failover with Pacemaker and…]]></title>
            <link>https://medium.com/@2infiniti/creating-highly-available-nodes-on-icon-stage-1-active-passive-failover-with-pacemaker-and-a9d56b1484da?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9d56b1484da</guid>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[ha]]></category>
            <category><![CDATA[icx]]></category>
            <category><![CDATA[prep]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 12:34:55 GMT</pubDate>
            <atom:updated>2019-09-05T00:28:24.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Highly Available Nodes on ICON — Stage 1: Active/Passive Failover with Pacemaker and Corosync</h3><p>The result of our testnet phase 2 stress testing simulation was devastating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*odJNtNMx7mgEclSWzzynMg.jpeg" /></figure><p>100% of the nodes were down, this is somewhat expected as all nodes were on a single bare-minimum docker container with <a href="https://www.icondev.io/docs/p-rep-installation-and-configuration">testnet specs</a>. The instances were no where near the <a href="https://www.icondev.io/docs/p-rep-installation-and-configuration-1">recommended mainnet specs</a> and most P-Reps have not yet created a HA architecture with some ways of failover or service recovery mechanism. With t<a href="https://medium.com/helloiconworld/p-rep-testnet-3rd-phase-announcement-1ab9cc73d939">estnet phase 3 coming up</a>, and full decentralization in less than a month, we should be ready to face extreme conditions and secure our network by keeping nodes alive.</p><ul><li><em>This tutorial is based on Ubuntu 18.04 using </em><a href="https://aws.amazon.com/"><em>Amazon Web Services</em></a></li></ul><h4>Create P-Rep Node EC2 Instances</h4><p>P-Rep nodes communicate through port 7100 for gRPC (peer to peer communication between nodes) and port 9000 for JSON-RPC API Server. Under Group Secuirty, create two custom rules for these ports and allow all IPv4 and IPv6 sources. Throw port 22 in so we can SSH into the servers to work directly.</p><p>We’ll be installing Corosync as our heartbeat and internal communication among cluster resources. Corosync uses UDP transport between ports 5404 to5406. Let’s enabled these ports as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txq8Ud5FGQkhWrSaKlRiYw.png" /></figure><p>We’re aiming to build an Active/Passive configuration, having the passive node as a redundant failover node. For this basic setup we’ll need to create two instances, and an elastic IP address. Also, we’re going to purposely spin weaker instances, our ideal testing will be for the primary peer to fail and have secondary peer to recover the service during our testnet stress testing. Going up to the recommended specs, our primary node could possible handle all requests without any down time. We will scale up as soon as we’re done with testing the setup.</p><p>Once the EC2 instances are created, go to EC2 dashboard -&gt; Elastic IPs. An elastic IP is a static IP address that points to one of your EC2. It allows you<br>to redirect network traffic to any of your instances when needed. This is used when we configure a domain or IP for our node peers to whitelist and making requests with each other. Now if one of our nodes goes down, we’ll dynamically point the IP to a different node, making service available again before the faulty node is restored. Let’s assign an elastic IP to one of the P-Rep nodes.</p><h4><strong>Optional</strong></h4><p>You can also setup a DNS record for this IP, this can be our peer endpoint to whitelist which will be used to exchange requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2q7i5WNlV9917CcoNrgOQ.png" /></figure><h4><strong>Install Corosync and Pacemaker</strong></h4><p>Next we’ll install Corosync (to both servers) as our messaging layer to the client servers, and Pacemaker as our cluster resource manager. Corosync is a dependency of Pacemaker so we’ll only need to install it.</p><pre>$ sudo apt-get -y update<br>$ sudo apt-get install pacemaker</pre><p>We’ll also need to install a management shell, some prefer crm and some prefer pcs . Either one will work, install</p><pre>$ sudo apt install crmsh<br>$ sudo apt install pcs</pre><p>Verify we have everything installed.</p><pre>$ pacemakerd --version<br>Pacemaker 1.1.18<br>Written by Andrew Beekhof</pre><pre>$ corosync -v<br>Corosync Cluster Engine, version &#39;2.4.3&#39;<br>Copyright (c) 2006-2009 Red Hat, Inc.</pre><pre>$ crm --version<br>crm 3.0.1</pre><pre>$ pcs --version<br>0.9.164</pre><h4><strong>Configure Corosync</strong></h4><p>Next we’ll need to create an auth key for the cluster, install haveged on either one of the servers, and generate a key.</p><pre># install package<br>$ sudo apt-get install haveged<br># generate key<br>$ sudo corosync-keygen</pre><p>Copy the same key to PRep-02,</p><pre>$ sudo scp /etc/corosync/authkey username@PRep-02_ip:/tmp</pre><p>then on PRep-02 window, move the file to the corosync folder</p><pre>$ sudo mv /tmp/authkey /etc/corosync/</pre><p>Next we’ll define the corosync.conf file, to make configuration a bit more convenient, let’s jot down various instance IP addresses that we’ll need, namely public, private and elastic IP.</p><p>Now edit the file /etc/corosync/corosync.conf on both servers, the files are identical except the bindnetaddr parameter will be the working server’s private IP.</p><pre>$ sudo nano /etc/corosync/corosync.conf</pre><p>Your config should look something like this</p><pre>totem {<br>  version: 2<br>  cluster_name: nodecluster<br>  transport: udpu<br>  interface {<br>    ringnumber: 0<br>    bindnetaddr: <strong>current_instance_private_ip</strong><br>    broadcast: yes<br>    mcastport: 5405<br>  }<br>}</pre><pre>quorum {<br>  provider: corosync_votequorum<br>  two_node: 1<br>}</pre><pre>nodelist {<br>  node {<br>    ring0_addr: <strong>PRep-01_private_ip</strong><br>    name: PRep-01<br>    nodeid: 1<br>  }<br>  node {<br>    ring0_addr: <strong>PRep-02_private_ip</strong><br>    name: PRep-02<br>    nodeid: 2<br>  }<br>}</pre><pre>logging {<br>  to_logfile: yes<br>  logfile: /var/log/corosync/corosync.log<br>  to_syslog: yes<br>  timestamp: on<br>}</pre><pre>service {<br>  name: pacemaker<br>  ver: 1<br>}</pre><p>then start corosync on both servers</p><pre>$ sudo service corosync start</pre><p>Verify that our nodes have joined as a cluster,</p><pre>$ sudo corosync-cmapctl | grep members</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*nLxYk16oTVxh1XKqiC8S5Q.png" /></figure><p>then start pacemaker</p><pre>$ sudo service pacemaker start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*HFxiBhZfkOISyl_10GAZMA.png" /></figure><p>Our nodes should be online. Since we’re running a two node setup, both STONITH (a mode to remove faulty nodes) and quorum policy should be disabled.</p><pre>$ crm configure property stonith-enabled=false<br>$ crm configure property no-quorum-policy=ignore</pre><p>verify the configuration,</p><pre>$ crm configure show</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*iZat24UT0bkVZbWP64LWbg.png" /></figure><h4><strong>Configure AWS CLI</strong></h4><p>We will be using AWS CLI for the elastic IP reallocation, for this we first need to install the CLI executables and configure a few settings, you will need AWS Access Key ID and AWS Secret Access Key</p><ol><li><a href="http://aws.amazon.com/">Log in to your AWS Management Console</a>.</li><li>Click on your user name at the top right of the page.</li><li>Click on the Security Credentials link from the drop-down menu.</li><li>Find the Access Credentials section, and copy the latest Access Key ID.</li><li>Click on the Show link in the same row, and copy the Secret Access Key.</li></ol><pre>$ sudo apt update<br>$ sudo apt install aws-cli<br># change to root, this is necessary<br>$ sudo su -<br>$ aws configure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*WVdh3ga9s0Pwx3Jebw9Dkw.png" /></figure><p>Next we’ll need a resource agent to manage the elastic IP, we can use aws’s eip resource agent awseip, which is found in /usr/lib/ocf/resource.d/heartbeat/awseip</p><p>Also add, AWS_DEFAULT_REGION=&lt;AWS-Default-Region&gt; at the end of /etc/systemd/system/multi-user.target.wants/pacemaker.service</p><p>then we’ll create a primitive resource for the agent to manage. A primitive resource<strong> </strong>is a singular resource that can be managed by the cluster. That is the resource can be started only once. An IP address for example can be primitive and this IP address should be running once and once only in the Cluster</p><pre>$ sudo crm configure primitive elastic-ip ocf:heartbeat:awseip params elastic_ip=&quot;<strong>your_elastic_ip</strong>&quot; awscli=&quot;$(which aws)&quot; allocation_id=&quot;<strong>your_elastic_ip_allocation_id</strong>&quot; op start  timeout=&quot;60s&quot; interval=&quot;0s&quot; on-fail=&quot;restart&quot; op monitor timeout=&quot;60s&quot; interval=&quot;10s&quot; on-fail=&quot;restart&quot; op stop timeout=&quot;60s&quot; interval=&quot;0s&quot; on-fail=&quot;block&quot; meta migration-threshold=&quot;2&quot; failure-timeout=&quot;60s&quot; resource-stickiness=&quot;100&quot;</pre><p><strong>your_elastic_ip</strong> is the elastic IP we allocated and associated to PRep-01 earlier, its allocation ID can be found under EC2 Dashboard -&gt; Elastic IPs -&gt; Allocation ID. Check the status again,</p><pre>$ sudo crm status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*T2fICYL8IndQAJ5lzRuJ-w.png" /></figure><p>The elastic-ip resource should be started on our first peer node. At this moment, we have an active node (PRep-01), a passive node (PRep-02) and an elastic IP pointing to the active node. Whenever our node becomes inaccessible, the resource agent should automatically point the floating IP to the backup node. Let’s test this.</p><p>On a 3rd instance (I am using local computer here), curl the elastic IP address</p><pre>localhost$ while true; do curl <strong>elastic_ip</strong>; sleep 2; done</pre><p>Which should constantly pull the content of the index page. For testing purposes, modify the index page, (for nginx the default index page is /var/www/html/index.nginx-debian.html) with instance number and IP. Let’s simulate active node down time by,</p><pre>$ sudo crm node standby PRep-02</pre><p>You may or may not see service interruption like this message on the 3rd terminal</p><pre>curl: (7) Failed to connect to node.icxstation.com port 80: Connection refused</pre><p>But either way, you should see the curl to the elastic IP now showing contents from the backup instance within a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cvWHToNA5OE3Y7dygT4Kg.png" /></figure><p>Also if you go back to the EC2 dashboard, you’ll notice the elastic IP has been automatically reassigned to the 2nd instance. You can bring the node back up via</p><pre>$ sudo crm node online PRep-02</pre><p>At this point we have completed a basic failover setup in active/passive configuration, with a floating IP automatically reassigned when the active node goes down. Stay tuned for stage 2, where we’ll be configuring ICON’s citizen nodes, P-Rep nodes and nginx reverse proxy configurations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9d56b1484da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICON Fee 2.0 — Part 1]]></title>
            <link>https://medium.com/@2infiniti/icon-fee-2-0-part-1-b6eb5318135e?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6eb5318135e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[icx]]></category>
            <category><![CDATA[fee2]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[virtualstep]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Thu, 13 Jun 2019 00:40:44 GMT</pubDate>
            <atom:updated>2019-06-13T06:17:19.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>ICON Fee 2.0 — Part 1</h3><p>ICON Foundation recently announced open schedule notice for Fee 2.0, launching on ICON mainnet in June 2019. Fee 2.0 is the actual implementation of the buzzwords like Virtual Steps or SCORE staking that we heard a while back from the <a href="https://icon.foundation/resources/file/ICON_Yellowpaper_Transactionfee_EN_V1.0.pdf">Transaction Fee Yellow Paper</a>. Today we’ll take an early peek of Fee 2.0 features, as well as creating a SCORE to exercise fee sharing and SCORE deposits. We will also talk about what these features mean to the ICON Dapp ecosystem.</p><h4>What was Fee 1.0?</h4><p>Fee 1.0 was simply that users will pay for 100% of the transaction fees for SCORE (smart contract) execution, this is the case for most blockchain protocols and ICON was no different. Let’s review how transaction fees work in version 1,</p><p><strong>Transaction fees<br></strong>Transaction fees were solely paid for by transaction senders, there’s no concept of fee sharing in version 1. We covered transaction fee calculation in this article: <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-2-score-af5f627e97e8">ICON DAPP From A-Z part 2: SCORE</a> under “Step Calculation” section if you want to look under the hood.</p><p><strong>What are Steps<br></strong>Recall that transaction fees are measured in “Steps”, which is simply a smaller unit of ICX (100,000,000 Steps = 1 ICX). This is conceptually similar to gas in Ethereum and what Gwei is to ETH. Users specify a max value they’re willing to spend for the transaction, exceeding the limit will effectively nullify the transaction.</p><h4>What is Fee 2.0?</h4><blockquote>Transaction senders must pay the transaction fees to execute a smart contract on the blockchain. The result of this transaction fee system was that all DApp users were required to pay transaction fees to use the service. This has been a major hurdle in attracting more users into the DApp service. With the ICON Transaction Fee 2.0 (Fee Sharing and Virtual Step), DApp service operators can choose to pay the transaction fees on behalf of the service users.<br>By using Fee 2.0 feature, DApp providers can have service users to avoid paying fees or have them pay fees with Virtual Step, a system to mitigate the burden of transaction fees, generated through staking instead of the actual ICX.</blockquote><p>Recall, Virtual Steps are transaction fee credits, they have 1:1 Step ratio but non-redeemable, non-transferable, and non-tradable. You can use these credits to deduct transaction fees only. Virtual Steps have expiration date, same as your deposit period.</p><p>When SCORE operator deposits ICX into the contract, Virtual Step is immediately created in proportion to the amount of ICX and the duration of the deposit. SCORE operators can pay for transaction fees with Virtual Steps.</p><p>Fee 2.0 has two main objectives</p><ol><li>SCORE operators can share the transaction fees for their service users.</li><li>SOCRE operators can earn Virtual Steps by staking ICX to the SCORE, to ease the burden of fee sharing.</li></ol><p>In practice, fee 2.0 allows you to set_fee_sharing_proportion, which simply allows you to set a sharing proportion from 0 to 100%. This % is the transaction fee, you as the SCORE operator, will be paying for your users. Another key feature is the ability to make deposits into a SCORE, which will generate Virtual Steps that can be used to deduct transaction fees.</p><h4>How to Deploy Fee 2.0 SCORE?</h4><p>Fee 2.0 is pending to be deployed to the ICON network, so for this tutorial we’ll be using an early T-bears release candidate with Fee 2.0 features, you can pull the image from</p><pre>$ docker pull iconloop/tbears:1.3.0-rc1</pre><p>then run the container</p><pre>$ docker run -it -p 9000:9000 iconloop/tbears:1.3.0-rc1</pre><p>Let’s experiment by creating a new SCORE that implements fee sharing functionalities,</p><pre>$ tbears init fee_sharing FeeSharing</pre><p>IconScoreBase provides two APIs that can be invoked inside the SCORE&#39;s external methods, namely get_fee_sharing_proportion and set_fee_sharing_proportion. Proportion is between 0 to 100, if its set to 100, the SCORE will pay 100% of transaction fees on behalf of the transaction sender. We will also register wallets to a whitelist to prevent abusing, each wallet can have a different sharing proportion depending on the SCORE logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dbf187726be843a14fcfdf8d0de8023/href">https://medium.com/media/2dbf187726be843a14fcfdf8d0de8023/href</a></iframe><p>Now deploy this to your localhost,</p><pre># tbears_cli_config.json<br>{<br>    &quot;uri&quot;: &quot;http://127.0.0.1:9000/api/v3&quot;,<br>    &quot;nid&quot;: &quot;0x3&quot;,<br>    &quot;keyStore&quot;: null,<br>    &quot;from&quot;: &quot;hxe7af5fcfd8dfc67530a01a0e403882687528dfcb&quot;,<br>    &quot;to&quot;: &quot;cx0000000000000000000000000000000000000000&quot;,<br>    &quot;deploy&quot;: {<br>        &quot;stepLimit&quot;: &quot;0x59682f00&quot;,<br>        &quot;mode&quot;: &quot;install&quot;,<br>        &quot;scoreParams&quot;: {}<br>    },<br>    &quot;txresult&quot;: {},<br>    &quot;transfer&quot;: {<br>        &quot;stepLimit&quot;: &quot;0x200000&quot;<br>    }<br>}</pre><p>We’ll use these default settings and keystore to deploy</p><pre>$ tbears deploy fee_sharing </pre><p>Check txresult as usual,</p><pre>$ tbears txresult 0x4e570c0d4bbb99b670c5852655938cb1b4b91190d386fe814c6bd270f13b139e</pre><p>Copy down the SCORE address.</p><p>Now let’s create a new JSON-RPC call to make deposit to the SCORE, replace “to” address with what you just copied from the last step.</p><pre># deposit.json</pre><pre>{<br>    &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>    &quot;method&quot;: &quot;icx_sendTransaction&quot;,<br>    &quot;id&quot;: 1,<br>    &quot;params&quot;: {<br>        &quot;version&quot;: &quot;0x3&quot;,<br>        &quot;nid&quot;: &quot;0x3&quot;,<br>        &quot;from&quot;: &quot;hxe7af5fcfd8dfc67530a01a0e403882687528dfcb&quot;,<br>        &quot;to&quot;: &quot;cxff74e566e30e9ccd2ba6291183876e3350d47942&quot;,<br>        &quot;value&quot;: &quot;0x10f0cf064dd59200000&quot;,<br>        &quot;stepLimit&quot;: &quot;0x3000000&quot;,<br>        &quot;timestamp&quot;: &quot;0x58a1be6dac367&quot;,<br>        &quot;nonce&quot;: &quot;0x1&quot;,<br>        &quot;signature&quot;: &quot;Z+sc78SjGGsdch5kalcNqaK8+7ZX8M6SwaRYjrFopOoepLBok/sJ9EPulGxrDN4OodTqqYRA6KnuwGrNStomwAA=&quot;,<br>        &quot;dataType&quot;: &quot;deposit&quot;,<br>        &quot;data&quot;: {<br>            &quot;action&quot;: &quot;add&quot;<br>        }<br>    }<br>}</pre><p>Execute it, for icx_sendTransaction we should use tbears sendtx</p><pre>$ tbears sendtx deposit.json</pre><p>Check the transaction result</p><pre>$ tbears txresult 0x9c74f320e8415c4abd341e8b1ee38d1451b83e9d1e6e7c8110b6119930ad8164</pre><p>Now the transaction result is something we’ve not seen before, if our deposit was successful in the last step, you should see an eventlog in our transaction result DepositAdded.</p><pre>Transaction result: {<br>    &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>    &quot;result&quot;: {<br>    &quot;txHash&quot;: &quot;0x9c74f320e8415c4abd341e8b1ee38d1451b83e9d1e6e7c8110b6119930ad8164&quot;,<br>    &quot;blockHeight&quot;: &quot;0x33d&quot;,<br>    &quot;blockHash&quot;: &quot;0xf0bfacc8873947333a3f7fd26ec006b2cdc88a20dc4c4677bf2554d22d522133&quot;,<br>    &quot;txIndex&quot;: &quot;0x0&quot;,<br>    &quot;to&quot;: &quot;cxff74e566e30e9ccd2ba6291183876e3350d47942&quot;,<br>    &quot;stepUsed&quot;: &quot;0x1ba94&quot;,<br>    &quot;stepPrice&quot;: &quot;0x2540be400&quot;,<br>    &quot;cumulativeStepUsed&quot;: &quot;0x1ba94&quot;,<br>    &quot;eventLogs&quot;: [<br>        {<br>            &quot;scoreAddress&quot;: &quot;cxff74e566e30e9ccd2ba6291183876e3350d47942&quot;,<br>            &quot;indexed&quot;: [<br>                &quot;DepositAdded(bytes,Address,int,int)&quot;,<br>&quot;0x9c74f320e8415c4abd341e8b1ee38d1451b83e9d1e6e7c8110b6119930ad8164&quot;,<br>                &quot;hxe7af5fcfd8dfc67530a01a0e403882687528dfcb&quot;<br>            ],<br>            &quot;data&quot;: [<br>                &quot;0x10f0cf064dd59200000&quot;,<br>                &quot;0x13c680&quot;<br>            ]<br>        }<br>    ],<br>    &quot;logsBloom&quot;: &quot;0x00000000000000000000000000000000000000000000000000000000000000000010000000008000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000800000000000000000000000000001000000000004000000000004000000000001000000000000000000000000010000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000&quot;,<br>    &quot;status&quot;: &quot;0x1&quot;<br>},<br>    &quot;id&quot;: 1<br>}</pre><p>DespositAdded is defined as follows,</p><pre>@eventlog(indexed=2)<br>def DepositAdded(self, id: bytes, from_: Address, amount: int, term: int):<br>    pass</pre><p>where id is the deposit id (i.e., the transaction hash), from_ is the transaction sender, amount is the amount of deposited ICX, and term is the deposit period in blocks, which is currently fixed to 1 month (1,296,000 blocks in 30 days).</p><p>In our example, our transaction hash 0x9c74f320e8415c4abd341e8b1ee38d1451b83e9d1e6e7c8110b6119930ad8164</p><p>from the transaction sender<br>hxe7af5fcfd8dfc67530a01a0e403882687528dfcb</p><p>deposit amount <br>0x10f0cf064dd59200000 (5000 ICX, <a href="https://icon.support/toolbox/uc/">unit converter</a>)</p><p>and term <br>0x13c680 (1296000 blocks or 30-day deposit period)</p><p>We will demonstrate more features once Fee 2.0 gets deployed to the ICON testnet. We will show you how to add wallets to the whitelist using different proportions (variable sharing fees), and illustrate how this can fit into actual use cases. We will also cover how to check SCORE deposit status using getScoreStatus API and withdrawal operations, as well as early withdrawal penalties.</p><p>For more information please visit the official document: <a href="https://www.icondev.io/docs/how-to-set-the-policy-for-the-transaction-fee">Set the policy for the transaction fee</a></p><p>Also check out <a href="https://github.com/icon-project/icon-sdk-java/commits/IS-522-fee-20-support">development branch of Java SDK</a> for more examples on fee 2.0.</p><h4>ICON — A Dapp Friendly Blockchain</h4><p>ICON is a Dapp friendly blockchain for a number of reasons. It is based in Python, which is the preferred language for many developers and has a large existing community. ICON Dapps can benefit directly from DAPP Booster Program (DBP) where DApps on the network will receive a portion of the block rewards based on their ranking. ICON Dapps can also benefit indirectly from Ecosystem Expansion Projects (EEP), Dapp incentive programs like the <a href="https://txchallenge.icon.foundation/#/?lang=en">tx challenge</a>, ICONgress initiatives and more. ICON also has VC arms such as Deblock and ICX Station that can support ICON Dapp teams from incubation to acceleration and funding support. With the implementation of Fee 2.0, ICON continues to add more reasons for devs to come develop their next Dapp on top of the ICON Network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6eb5318135e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collusion in Delegated Proof of Contribution Models]]></title>
            <link>https://medium.com/iconcm/collusion-in-delegated-proof-of-contribution-models-c77bc16bcfe4?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c77bc16bcfe4</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[collusion]]></category>
            <category><![CDATA[dpoc]]></category>
            <category><![CDATA[icx]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Thu, 06 Jun 2019 07:00:16 GMT</pubDate>
            <atom:updated>2019-08-28T12:23:08.362Z</atom:updated>
            <content:encoded><![CDATA[<p>As we’re approaching the upcoming P-Rep election, where 22 main P-Reps will be elected to govern the network, and ICON will be entering its first phase of decentralization. Questions start to unfold, is the network truly decentralized? How do we prevent the rich from taking complete control, bribe attacks, and cartel formation? Today’s we will explore collusion problems under Delegated Proof of Stake models, and more specifically collusion under Delegated Proof of Contribution model — ICON.</p><h4>Background on DPoS</h4><p>DPoS was designed to solve a specific problem of poor voter participation, where majority of stakeholders simply don’t have the time, knowledge and skills to vote responsibly. Instead, it centralizes the decision making process to a smaller set of elected nodes known as delegates. These delegates play major roles within the network, from providing computing resources to block production and validation. They also compete against one another should one act maliciously, bad actors will be voted out and replaced with trustworthy ones.</p><h4>Public Representatives (P-Reps)</h4><p>Similar to DPoS (Delegated Proof of Stake), ICON is also under a proxy voting mechanism where ICONists will delegate their ICX to P-Rep candidates. With enough votes, these public representatives will receive control of the network and produce/verify blocks on behalf of their delegating ICONists.</p><p>P-Reps not only possess the power to vote on governance and monetary policies, network and protocol upgrades; they’re also<a href="https://m.icon.foundation/download/Introduction_for_Public_Representative_of_ICON_Network_EN_V1.0.pdf#page=6"> incentivized handsomely</a> with representative rewards, as well as block production and verification rewards. Significant amount of ICX is at stake and competition is fierce.</p><h4>Delegated Proof of Contribution (DPoC)</h4><p>From <a href="https://icon.foundation/resources/file/ICON_Yellowpaper_ICONstitution_and_Governance_EN_V1.0.pdf?v=180914#page">ICONstitution and Governance yellow paper</a>,</p><blockquote>The central philosophy of the ICON Network reward distribution is fair compensation based on relative contribution. Each participant can demonstrate their contribution through the ICON Network’s unique contribution evaluation system. In the end, contribution is the most important value shared within the ICON Network, and therefore will be the sole standard in the network. Delegated Proof of Contribution (DPoC), as described herein, is the sole justification for electing representatives.</blockquote><p>In plain words, incentive schemes are designed around network participation, and one of the most important ‘participation criteria’ is ICX delegation. This is commonly used interchangeably with staking, which effectively freezes the tokens in reserve.</p><h4>Problem: Low Voting Rate &amp; Collusion</h4><p>We briefly covered low voting rate problem in a general consensus model, and the attempt to centralize decisions to elected representatives (DPoS). However, even under DPoS, voting without enough economic incentive, people are less willing to participate. From <a href="https://twitter.com/RickyLeeDodds">Ricky Dodds</a>’ research on DPoC (<a href="https://medium.com/@ricky_96150/delegated-proof-of-contribution-40bfac995c1">part 1</a> and <a href="https://medium.com/@ricky_96150/delegated-proof-of-contribution-8e83bdb9c19a">part 2</a>)</p><blockquote>As a point of reference, there is no economic incentive for voting for an EOS BP. The only benefit is governance. As of now, ~25% of EOS community members have voted, and 47% of EOS outstanding is staked. For Tron, the amount voted for super representatives is even smaller at ~7% based on total supply. However, the 27 Super Representative Nodes with the most votes create new blocks and share the rewards with their voters. Based on estimates, this annual return is close to ~5%.</blockquote><p>Furthermore, of the 25% voting accounts, many of which could be sock-puppet accounts from the same owner, or ‘friends helping each other out’. This can be observed from the actual votes, eg: <a href="https://eosauthority.com/voting_periodic">EOS Voting Analytics</a> to analyze vote patterns or <a href="https://eosauthority.com/producers_relation">BP relationships</a> to find the correlations. Unfortunately, proxy voting models like DPoS depend on high voting rate from the entire community in order to work. If majority of delegates were governed by a plutocracy of the rich, they can undermine the decision making process and security of the network will be compromised.</p><p>As a consequence of low voting rates, it becomes much easier to dominate and collude on the network. Very wealthy individuals can vote themselves in and secure positions as block producers and decision makers. They can also exchange and sell votes, eg: <a href="https://www.trustnodes.com/2018/09/29/rampant-collusion-in-eos-exposed-by-huobi-leak">Rampant Collusion in EOS Exposed by Huobi Leak</a> and always stay in power.</p><h4>ICON’s Mitigation: Improved Voting Rate in DPoC</h4><p>ICONists have every reason to stake, I am expecting the delegation rate of circulating ICX tokens, close to that of the token swap rate (98.7%) over a span of one year. Even with some margin of error, we can expect the staking rate to be extremely high, since all participants are financially encouraged to do so. This not only applies to representative delegation rewards, but also staking rewards for Dapps and EEPs (Ecosystem Expansion Projects), the financial incentives make no sense to ignore.</p><p>With high participation from the entire community, it becomes difficult to cheat. High delegation rate increases the amount of ICX needed to win, making it extremely expensive to win majority power. Greater the total number of accounts, harder it will be to organize bribes. When the community acts together, they can also create and vote on policies to combat against bad actors. When overall difficulty to cheat increases, collusion problems naturally becomes lesser of a problem.</p><h4>Collusion — Game Theory and Beyond</h4><p>Let’s dig in a bit further on collusion by looking at Vitalik’s recent publication: <a href="https://vitalik.ca/general/2019/04/03/collusion.html">On Collusion</a>, where he discussed cooperative game theory that focuses on predicting which coalitions will form, the joint actions that groups take and the resulting collective payoffs. Under this class of games,</p><blockquote><em>Majority games</em>, formally described as games of N agents where any subset of more than half of them can capture a fixed reward and split it among themselves, a setup eerily similar to many situations in corporate governance, politics and many other situations in human life, are <a href="https://web.archive.org/web/20180329012328/https://www.math.mcgill.ca/vetta/CS764.dir/Core.pdf">part of that set of inherently unstable games</a>. That is to say, if there is a situation with some fixed pool of resources and some currently established mechanism for distributing those resources, and it’s unavoidably possible for 51% of the participants can conspire to seize control of the resources, no matter what the current configuration is there is always some conspiracy that can emerge that would be profitable for the participants. However, that conspiracy would then in turn be vulnerable to potential new conspiracies, possibly including a combination of previous conspirators and victims… and so on and so forth.</blockquote><p>He proposes two ways to get around this issue. One of which is to avoid being in the class of games that are identity-free and collusion-safe, so we do not need to worry about bribes or identities. Second is to attack the problems directly heads on and actually solve them well enough that we can implement non-collusion-safe games. He went on to discuss details on identity-free and collusion-safe game design, as well as collusion resistance and identity. Concluding thought was that building out the infrastructure for making collusion-resistant mechanism possible is a difficult challenge and the aim is to succeed at making something secure enough, for at least some use cases.</p><h4>Will ICON be Collusion-Safe?</h4><p>I would say that the answer is no and argue that it is likely impossible for most if not all blockchain protocols to be completely collusion-safe. ICON however will be collusion-safe until a high bound, and fairly collusion-resistant overall. Even under Proof of Work protocols, they’re only collusion-safe up to the bound of one actor possessing over 50% of total hash power. Most protocols, PoW or PoS or DPoS, are relatively collusion-safe up until a high bound. Some protocols reach the high bound easily and some don’t. For example, projects with high concentration of tokens such as EOS where top 100 wallets own 75% and top 10 wallets own 50% of all tokens, in-group collusion can be plain as day as the Huobi incident we mentioned earlier. This makes it possible to cement their positions as BPs, and if at one point they reach the high bound, namely 2/3+1 or 15 block producers, they can freely act in self-interest and maximize their own profit. For ICON, besides the exchange wallets, tokens are <a href="https://tracker.icon.foundation/addresses">relatively spread out </a>, suggesting that we don’t have high concentration of tokens to select few individuals. In this case, reaching the high bound will require many more accounts colluding. We also talked about high voting rate making collusion extremely expensive, and that buying out the network will be financially discouraged and chances are, people won’t do it.</p><h4>What Else Can be Done?</h4><p>Another idea came from Block.one, who holds 10% of EOS tokens, <a href="https://medium.com/block-one/10-1-2018-statement-eos-public-blockchain-governance-cb2b5675ddc8">talks about using their tokens to vote</a> and to reinforce the integrity of their election. While this may seem counter-intuitive to the decentralization process, it is to ensure network safety in the mean time, before the next optimal design for future decentralized governance comes up. ICON could also take on a similar approach, voting in say, an ICON Foundation P-Rep node, just like what EOS and Tron and several other projects have done.</p><h4>Even More Parties Involved</h4><p>Community Representatives (C-Reps) will be introduced down the road. Recall,</p><blockquote>A C-Rep, representing a Community connected to the ICON Network, is elected via autonomous decision-making within the respective Community in accordance to sufficient contribution verified. A C-Rep is a connection between ICON Network and Community, validating transactions on the ICON Network. A C-Rep proposes and votes on policies that represents interests of each Community.</blockquote><p>So C-Reps will be well vetted and will be proposing and voting policies of best interest to their respective community. We will have a complementary system among the two sectors of representatives (P-Reps and C-Reps), making our governance structure more balanced and reliable. Also, from <a href="https://icon.foundation/resources/file/ICON_Yellowpaper_ICONstitution_and_Governance_EN_V1.0.pdf#page=08">ICONstitution and Governance Yellow Paper</a>, we know that the number of C-Reps and the P-Reps will roughly be equal. This makes collusion at least twice as difficult, and prevents biased-decision making.</p><h4>TL;DR</h4><p>Most protocols may never be completely collusion-safe, and it is not the goal for ICON either. ICON tries to mitigate by making it expensive and difficult to collude and stays very collusion-resistant overall.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c77bc16bcfe4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iconcm/collusion-in-delegated-proof-of-contribution-models-c77bc16bcfe4">Collusion in Delegated Proof of Contribution Models</a> was originally published in <a href="https://medium.com/iconcm">iconcm</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICON Node Installation — Docker + AWS]]></title>
            <link>https://medium.com/@2infiniti/icon-node-installation-docker-aws-35028e4a5819?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/35028e4a5819</guid>
            <category><![CDATA[prep]]></category>
            <category><![CDATA[iconsensus]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[icx]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Mon, 27 May 2019 11:57:51 GMT</pubDate>
            <atom:updated>2019-05-28T10:26:50.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>ICON Node Installation — Docker + AWS</h3><p>In this tutorial article we will be setting up a P-Rep node on the ICON network (TestNet) using docker images, deploying the instances to Amazon Web Services (AWS).</p><p>Let’s first examine the requirements and make sure we have everything needed,</p><h4>SW Requirements</h4><h4>OS requirements</h4><ul><li>Linux (CentOS 7 or Ubuntu 16.04+)</li></ul><h4>Package requirements</h4><ul><li>Docker 18.x or higher</li></ul><p>For your reference, ICON node depends on the following packages. The packages are included in the P-Rep docker image that we provide, so you don’t need to install them separately.</p><ul><li>Python 3.6.5 or higher (3.7 is not supported)</li><li>RabbitMQ 3.7 or higher</li></ul><h3>AWS EC2</h3><p>In this tutorial we will go with Ubuntu 18.04, we’ll be working on <a href="https://aws.amazon.com/">AWS</a> so make sure you have an account there.</p><p>Log in and launch EC2 dashboard, launch a new EC2 instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*541nJhUMY6hrSiQ9NkryCw.png" /></figure><p>From instance types, pick Ubuntu 18.04</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rvY5jV-xqyHgrlspENg-w.png" /></figure><p>Make sure to create a new private key, name it however you like. For security, we’ll be using the private key to log into the instance in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Zp_982Q5NbJfakTbhZSbeg.png" /></figure><p>Download the privatekey .pem</p><p>Next we’ll allocate a static IP and associate it to the instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*yu7AeN-TeZp_JgFgkiM-Qg.png" /></figure><p>Top right of the EC2 dashboard you’ll find “Elastic IPs”, click on it and allocate from the Amazon pool. Right click on the newly allocated IP and associate it to the instance that we just created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*zKQnLNNth6hL-ialKRxGXA.png" /></figure><p>Now we’re ready for installation, log into the instance with the private key we downloaded earlier.</p><p>For windows users using PuTTY, follow this guide <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html</a> to convert the .pem into .ppk file.</p><p>For mac users you can simply SSH from terminal with the downloaded .pem</p><p>Log into the server (ubuntu@public_dns_name), port 22 (load ppk under SSH-&gt;auth menu for PuTTY).</p><p>Let’s inspect the installation document <a href="https://www.icondev.io/docs/p-rep-installation-and-configuration">https://www.icondev.io/docs/p-rep-installation-and-configuration</a></p><p>We see the first requirement is to download an IP whitelist from the</p><blockquote>IP List: <a href="https://download.solidwallet.io/conf/prep_iplist.json">https://download.solidwallet.io/conf/prep_iplist.json</a></blockquote><blockquote>ICON foundation will maintain the IP list of P-Reps. The JSON file will contain the list of IPs. You should configure your firewalls to allow in/outbound traffic from/to the IP addresses. Following TCP ports should be open.</blockquote><blockquote>Port 7100: Used by gRPC for peer to peer communication between nodes.</blockquote><blockquote>Port 9000: Used by JSON-RPC API server.</blockquote><p>This has been updated to dynamic IP update, P-Reps no longer need to download an IP list manually. The IP list will be updated automatically on a daily basis from the endpoint of the seed node inside the P-Rep Node Docker.</p><h3><strong>Install P-Rep Node</strong></h3><pre>## Update the apt package index:<br>$ sudo apt-get update<br><br>## Install necessary packages:<br>$ sudo apt-get install  -y systemd apt-transport-https ca-certificates curl gnupg-agent software-properties-common <br><br>## Add Docker&#39;s official GPG key:<br>$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -<br><br>## Add the apt repository<br>$ sudo add-apt-repository &quot;deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot;<br><br>## Update the apt package index:<br>$ sudo apt-get update<br><br>## Install docker-ce:<br>$ sudo apt-get -y install docker-ce docker-ce-cli containerd.io<br><br>## Add your user to the docker group with the following command.<br>$ sudo usermod -aG docker $(whoami)<br><br>## Set Docker to start automatically at boot time:<br>$ sudo systemctl enable docker.service<br><br>## Finally, start the Docker service:<br>$ sudo systemctl start docker.service<br><br>## Then we&#39;ll verify docker is installed successfully by checking the version:<br>$ sudo docker version</pre><p>If everything was installed correctly you should get something similar to</p><pre>Client:<br> Version:           18.09.6<br> API version:       1.39<br> Go version:        go1.10.8<br> Git commit:        481bc77<br> Built:             Sat May  4 02:35:57 2019<br> OS/Arch:           linux/amd64<br> Experimental:      false</pre><pre>Server: Docker Engine - Community<br> Engine:<br>  Version:          18.09.6<br>  API version:      1.39 (minimum version 1.12)<br>  Go version:       go1.10.8<br>  Git commit:       481bc77<br>  Built:            Sat May  4 01:59:36 2019<br>  OS/Arch:          linux/amd64<br>  Experimental:     false</pre><p>Next install docker compose</p><pre>## Install python-pip<br>$ sudo apt-get install -y python3-pip<br><br>## Then install Docker Compose:<br>$ sudo pip3 install docker-compose<br><br>## To verify the successful Docker Compose installation, run:<br>$ docker-compose version</pre><p>By now we have docker installed and we can simply pull the latest iconloop prep-node image</p><pre>$ sudo docker pull iconloop/prep-node:1904111713xdde258</pre><p>Create a new docker-compose.yml</p><pre>$ sudo touch docker-compose.yml<br>$ sudo nano docker-compose.yml</pre><p>And paste the following content</p><pre>version: &#39;3&#39;<br>services:<br>    container:<br>        image: &#39;iconloop/prep-node:1904111713xdde258&#39;<br>        container_name: &#39;prep-node&#39;<br>        volumes:<br>            - ./data:/data<br>        ports:<br>           - 9000:9000<br>           - 7100:7100</pre><p>Now we’ll run docker-compose with the above file</p><pre>$ sudo docker-compose up -d</pre><p>You can run</p><pre>$ sudo docker ps</pre><p>at any time to see which containers are running (and its health state under Status). You can also run</p><pre>$ curl localhost:9000/api/v1/status/peer</pre><p>to view node status similar to the following</p><pre>{<br>    &quot;made_block_count&quot;: 0,<br>    &quot;status&quot;: &quot;Service is online: 0&quot;,<br>    &quot;state&quot;: &quot;Vote&quot;,<br>    &quot;peer_type&quot;: &quot;0&quot;,<br>    &quot;audience_count&quot;: &quot;0&quot;,<br>    &quot;consensus&quot;: &quot;siever&quot;,<br>    &quot;peer_id&quot;: &quot;hx1787c2194f56bb550a8daba9bbaea00a4956ed58&quot;,<br>    &quot;block_height&quot;: 184,<br>    &quot;round&quot;: 1,<br>    &quot;epoch_height&quot;: 186,<br>    &quot;unconfirmed_block_height&quot;: 0,<br>    &quot;total_tx&quot;: 93, <br>    &quot;unconfirmed_tx&quot;: 0,<br>    &quot;peer_target&quot;: &quot;20.20.1.195:7100&quot;,<br>    &quot;leader_complaint&quot;: 185,<br>    &quot;peer_count&quot;: 5,<br>    &quot;leader&quot;: &quot;hx7ff69280a1483c660695039c14ba954bb101bb66&quot;,<br>    &quot;epoch_leader&quot;: &quot;hx7ff69280a1483c660695039c14ba954bb101bb66&quot;,<br>    &quot;mq&quot;: {<br>         &quot;peer&quot;: {<br>               &quot;message_count&quot;: 0<br>          },<br>         &quot;channel&quot;: {<br>               &quot;message_count&quot;: 0<br>         },<br>         &quot;score&quot;: {<br>              &quot;message_count&quot;: 0<br>         }<br>     }<br>}</pre><p>Also notice data folder should be created with the following structure</p><pre>.<br>|---- data  <br>|     |---- PREP-TestNet   → Default ENV directory  <br>|          |---- .score_data  <br>|          |      |-- db      → root directory that SCOREs will be installed<br>|          |      |-- score   → root directory that the state DB file will be created<br>|          |---- .storage     → root directory that the block DB will be stored<br>|          |---- log          → root directory that log files will be stored</pre><p>Where you will find miscellaneous logs, for instance, this node isn’t whitelisted by ICON P-Rep team yet, so running the docker container will result in the following error under booting log</p><pre>[2019-05-23 15:54:12.600] Your IP: 3.15.102.228<br>[2019-05-23 15:54:12.602] RPC_PORT: 9000 / RPC_WORKER: 3<br>[2019-05-23 15:54:12.605] DEFAULT_PATH=/data/PREP-TestNet in Docker Container<br>[2019-05-23 15:54:12.607] DEFAULT_LOG_PATH=/data/PREP-TestNet/log<br>[2019-05-23 15:54:12.610] DEFAULT_STORAGE_PATH=/data/PREP-TestNet/.storage<br>[2019-05-23 15:54:12.613] scoreRootPath=/data/PREP-TestNet/.score_data/score<br>[2019-05-23 15:54:12.615] stateDbRootPath=/data/PREP-TestNet/.score_data/db<br>[2019-05-23 15:54:12.618] P-REP package version info - 1904111713xdde258<br>[2019-05-23 15:54:14.979] iconcommons 1.0.5.1 iconrpcserver 1.2.6 iconservice 1.2.2 loopchain 2.1.2<br>[2019-05-23 15:54:16.152] [ERROR] Download Failed - <a href="https://download.solidwallet.io/cert/3.15.102.228_public.der">https://download.solidwallet.io/cert/3.15.102.228_public.der</a> status_code=403<br>[2019-05-23 15:54:16.155] [ERROR] Unauthorized IP address, Please contact our support team<br>[2019-05-23 15:54:16.158] [ERROR] Your External IP:3.15.102.228 / Your Enviroment IPADDR:3.15.102.228</pre><p>You node should be configured now. Let’s visit security settings again, recall that we needed to enable TCP 7100 and 9000 to the peers (whitelisted IPs). This was the case during testnet phase 1, in testnet phase 2 and onwards, the foundation will register all P-Rep IPs on-chain daily, so we no longer need to keep track of whitelisted IPs. For now we’ll configure port 7100 and 9000 to everyone, go to security group, I am using launch-wizard-1 which is the default security policy created by AWS at launch. Add Custom TCP Rule to allow traffic from port 9000 and 7100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnPC-i5XLanWWSL8oLquJg.png" /></figure><p>This should be it, you’ll be able to produce and verify blocks on the testnet once whitelisted to our testnet program. We’ll explore more about node security, failover strategies and high availability operations in future articles.</p><p>Also check back to the official installation and configuration documentation frequently: <a href="https://www.icondev.io/docs/p-rep-installation-and-configuration">https://www.icondev.io/docs/p-rep-installation-and-configuration</a>, the document will be kept up-to-date when new information become available.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35028e4a5819" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICON Workshop — Blackjack Part 1: SCORE]]></title>
            <link>https://medium.com/@2infiniti/icon-workshop-blackjack-part-1-score-a724cff7bb15?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a724cff7bb15</guid>
            <category><![CDATA[icx]]></category>
            <category><![CDATA[icondev]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[blackjack]]></category>
            <category><![CDATA[cores]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 02:03:33 GMT</pubDate>
            <atom:updated>2019-04-16T02:03:33.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>ICON Workshop — Blackjack Part 1: SCORE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*g2MV4cvwGItAEaES49hZmw.png" /></figure><p>In this tutorial we’re going to build one of the most classic casino games — blackjack! This tutorial series is broken down into two parts, part 1 focusing on SCORE development and part 2 focusing on web interface and ICONex integration. At the end of this tutorial series you will have a functional blackjack game on a website, and be able to play the game using IRC-2 tokens on the ICON network!</p><p>We’ll be building two SCOREs for this game, one token SCORE to mint our custom IRC-2 token to serve as blackjack chips and allow users to exchange with their ICX tokens. We’ll implement another SCORE to handle the game logic, from room creation to in-game rules etc.</p><p>Let’s start off with our custom token contract, recall from the tutorial <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-2-score-af5f627e97e8">ICON DAPP From A-Z Part 2: SCORE</a>, we learned that to stay IRC-2 compliant, we must implement these 6 methods: name , symbol , decimals , totalSupply , balanceOf , and transfer.</p><p>Let’s first initiate a new SCORE</p><pre>$ mkdir blackjack %% cd blackjack<br>$ tbears init chip Chip</pre><p>As usual, this will generate a SCORE skeleton with a dummy hello method. Let’s go right ahead and get the IRC-2 methods implemented.</p><pre># chip.py</pre><pre>from iconservice import *</pre><pre>TAG = &#39;Chip&#39;<br></pre><pre>class Chip(IconScoreBase):<br>    _BALANCES = &#39;balances&#39;<br>    _TOTAL_SUPPLY = &#39;total_supply&#39;<br>    _DECIMALS = &#39;decimals&#39;</pre><pre>    @eventlog(indexed=3)<br>    def Transfer(self, _from: Address, _to: Address, _value: int, _data: bytes):<br>        pass</pre><pre>    def __init__(self, db: IconScoreDatabase) -&gt; None:<br>        super().__init__(db)<br>        self._total_supply = VarDB(self._TOTAL_SUPPLY, db, value_type=int)<br>        self._decimals = VarDB(self._DECIMALS, db, value_type=int)<br>        self._balances = DictDB(self._BALANCES, db, value_type=int)</pre><pre>    def on_install(self, _decimals: int = 8) -&gt; None:<br>        super().on_install()<br>        self._total_supply.set(0)<br>        self._decimals.set(_decimals)</pre><pre>    def on_update(self) -&gt; None:<br>        super().on_update()<br>        pass<br>    <br>    @external(readonly=True)<br>    def name(self) -&gt; str:<br>        return &quot;Blackjack chips&quot;</pre><pre>    @external(readonly=True)<br>    def symbol(self) -&gt; str:<br>        return &quot;BJC&quot;</pre><pre>    @external(readonly=True)<br>    def decimals(self) -&gt; int:<br>        return self._decimals.get()</pre><pre>    @external(readonly=True)<br>    def totalSupply(self) -&gt; int:<br>        return self._total_supply.get()</pre><pre>    @external(readonly=True)<br>    def balanceOf(self, _owner: Address) -&gt; int:<br>        return self._balances[_owner]</pre><pre>    @external<br>    def transfer(self, _to: Address, _value: int, _data: bytes = None):<br>        if _value &lt; 0:<br>            revert(&#39;Transfer value cannot be less than zero&#39;)</pre><pre>        if self._balances[self.msg.sender] &lt; _value:<br>            revert(&quot;Out of balance&quot;)</pre><pre>        self._balances[self.msg.sender] = self._balances[self.msg.sender] - _value<br>        self._balances[_to] = self._balances[_to] + _value</pre><pre>        # Emits an event log `Transfer`<br>        self.Transfer(self.msg.sender, _to, _value, _data)</pre><p>The above should be fairly straight forward with basic IRC-2 methods defined. We’re only doing the most basic checks during a transfer, to see if balance is enough to make the transfer or if the transaction amount is &gt; 0. We will need a few more functions to make this game work, to mint/burn the blackjack tokens and a bet function to transfer balances for bets.</p><pre># chip.py</pre><pre>class Chip(IconScoreBase):<br>...</pre><pre>@external<br>def mint(self, _amount: int):<br>    <em>&quot;&quot;&quot;<br>    This method should be invoked by CA not EOA.<br><br>    </em><strong><em>:param</em></strong><em> _amount: the amount of Chips to mint<br>    &quot;&quot;&quot;<br>    </em>if not self.msg.sender.is_contract:<br>        revert(&quot;This method should be invoked by CA not EOA&quot;)<br><br>    self._total_supply.set(self._total_supply.get() + _amount)<br>    self._balances[self.tx.origin] = self._balances[self.tx.origin] + _amount * (10 ** self._decimals.get())</pre><p>Here we check to see if the caller is from contract address (in ICON that’d be addresses starting with cx…), and not externally owned account (hx…). For the burn function we’ll do some condition checks before doing the actual burn , in a privately accessed function _burn.</p><pre>@external<br>def burn(self, _amount: int):<em><br>    </em>if not self.msg.sender.is_contract:<br>        revert(&quot;This method should be invoked by CA not EOA&quot;)</pre><pre>    if self._balances[self.tx.origin] &gt; _amount:<br>        self._burn(self.tx.origin, _amount * (10 ** self._decimals.get()))<br>        self.Burn(self.tx.origin, _amount * (10 ** self._decimals.get()))<br>    else:<br>        revert(f&quot;You don&#39;t have enough chips to burn. Your balance: {self._balances[self.tx.origin]}&quot;)</pre><pre>def _burn(self, address: Address, amount: int):<br>    self._total_supply.set(self._total_supply.get() - amount)<br>    self._balances[address] = self._balances[address] - amount</pre><p>Lastly, we’ll implement a bet function to facilitate and simulate the actual betting action and transfer the balances.</p><pre>@external<br>def bet(self, _from: Address, _to: Address, _value: int):<br>    if not self.msg.sender.is_contract:<br>        revert(&quot;This method should be invoked by CA not EOA.&quot;)<br>    self._balances[_from] = self._balances[_from] - _value<br>    self._balances[_to] = self._balances[_to] + _value<br>    # emit the events to eventlogs    <br>    self.Bet(_from, _to, _value)<br>    self.Transfer(_from, _to, _value, None)</pre><p>IRC-2 is based on ERC-223 standard (for IRC-2, ERC-20, ERC-223 and rationales behind each standard, please read: <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-2-score-af5f627e97e8">https://medium.com/@2infiniti/icon-dapp-from-a-z-part-2-score-af5f627e97e8</a>). The transfer function in ERC-223 checks to see whether the receiving address is a contract, if it is, it will assume there’s a tokenFallback method, let’s define the interface</p><pre>class TokenFallbackInterface(InterfaceScore):<br>    @interface<br>    def tokenFallback(self, _from: Address, _value: int, _data: bytes):<br>        pass</pre><p>That’s it, we now have a SCORE that allows minting blackjack chips, burning chips, and facilitating bet actions. Here’s the code in its entirety.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d735080259ebb52c204ae655c05d500/href">https://medium.com/media/1d735080259ebb52c204ae655c05d500/href</a></iframe><p>Let’s deploy the SCORE to the bicon testnet.</p><pre># Create a new testnet deployment configuration file<br>$ touch tbears_cli_config_testnet.json</pre><p>Fill it with testnet configurations,</p><pre># tbears_cli_config_testnet.json<br>{<br>    &quot;uri&quot;: &quot;https://bicon.net.solidwallet.io/api/v3&quot;,<br>    &quot;nid&quot;: &quot;0x3&quot;,<br>    &quot;keyStore&quot;: null,<br>    &quot;from&quot;: &quot;hx5638ee91e18574a1f0a29b4813578389f0e142a7&quot;,<br>    &quot;to&quot;: &quot;cx0000000000000000000000000000000000000000&quot;,<br>    &quot;deploy&quot;: {<br>        &quot;stepLimit&quot;: &quot;0x77359400&quot;,<br>        &quot;mode&quot;: &quot;install&quot;,<br>        &quot;scoreParams&quot;: {}<br>    },<br>    &quot;txresult&quot;: {},<br>    &quot;transfer&quot;: {<br>        &quot;stepLimit&quot;: &quot;0x300000&quot;<br>    }<br>}</pre><p>Then deploy (note iconkeystore3 is a keystore that we created during past tutorials, you can use any wallet you like, just make sure to fill it with some testnet ICX from <a href="http://52.88.70.222/">http://52.88.70.222/</a>)</p><pre>$ tbears deploy chip -k iconkeystore3 -c tbears_cli_config_testnet.json</pre><p>As usual, check to see if transaction was successful</p><pre>$ tbears txresult 0x517f3e8cd042deee550c5e7a7d14531b42b1b6a18bc24925cf1778bde8b2b871 -u <a href="https://bicon.net.solidwallet.io/api/v3">https://bicon.net.solidwallet.io/api/v3</a></pre><p>Alternatively you can check this on the live <a href="https://bicon.tracker.solidwallet.io/">testnet tracker</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjXROY_wZdwdKNS7vplSUw.png" /></figure><p>Let’s also take this opportunity to check out the contract features from our official <a href="https://chrome.google.com/webstore/detail/iconex/flpiciilemghbmfalicajoolhkkenfel?hl=en">ICONex Chrome extension</a></p><p>First, launch your ICONex, and under ‘Contract’ tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RB2y8nZyDMompO4k7xfXNA.png" /></figure><p>paste the SCORE address that you just deployed to the testnet, you should see all the external functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SV96qN33Sc0kwG7Mo8s1w.png" /></figure><p>In the past tutorials, we did JSON-RPC calls from tbears CLI for SCORE quests, which can be a bit of a hassle for simple testing purposes. This built-in contract invocation directly from ICONex makes SCOREs much easier to interact with. Let’s do an experiment, we’ll call the bet function from an EOA (Externally Owned Account), see if that throws an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rARc7asXyRg2EyoGCjJt-A.png" /></figure><p>Now let’s sign this transaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*SaOjnwTq8eQt210DyqZnnQ.png" /></figure><p>Check the tracker to see if this transaction was successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJcb9xxDo9e0BTNKsDNfuQ.png" /></figure><p>As expected, the transaction responded with an error by our built-in check for CA or EOA. Play with the contract calls and become familiar, you can leverage this feature to save some development time in the future.</p><p>We now have a functional IRC-2 SCORE to mint, burn and bet blackjack chips. We’re now ready to develop our game SCORE, which will handle our in-game logic, and the ability to create / leave game rooms.</p><p>Initiate a new SCORE template,</p><pre># Go back to the root level /blackjack<br>$ tbears init game Game</pre><p>For the game SCORE, we’ll divide into different packages,</p><pre>blackjack/<br>├── chip/<br>│   ├── __init__.py<br>│   ├── chip.py<br>│   └── package.json<br>├── game/<br>│   ├── __init__.py<br>│   ├── game.py<br>│   └── package.json<br>│─────── card/<br>│─────── deck/<br>│─────── gameroom/<br>│─────── hand/</pre><p>Let’s start with card.py</p><pre>$ cd game<br>$ mkdir card &amp;&amp; mkdir deck &amp;&amp; mkdir gameroom &amp;&amp; mkdir hand<br>$ cd card<br># add __init__.py to be treated as a python package for imports<br>$ touch __init__.py &amp;&amp; touch card.py</pre><p>A card is simply one suit plus one rank.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fbbb3061be11194af7cd874480042da/href">https://medium.com/media/8fbbb3061be11194af7cd874480042da/href</a></iframe><p>Now go into deck directory</p><pre>$ cd ../deck<br>$ touch __init__.py &amp;&amp; touch deck.py</pre><p>A deck has 52 cards, 4 suits and 13 ranks each. We’ll fill the deck with all 52 cards on init and a deal function to randomly draw a card.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6974b05dc87c835e666eb598fbe0399/href">https://medium.com/media/e6974b05dc87c835e666eb598fbe0399/href</a></iframe><p>Next we’ll implement a hand’s logic</p><pre>$ cd ../hand<br>$ touch __init__.py &amp;&amp; touch hand.py</pre><p>We’ll cover the basic case of a blackjack game, without complex logic from hand splitting, doubling, or buying insurance. We’ll deal with “hitting” only, which is to add cards to your hand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/683546603ce15f5cfcc7b45c282f897b/href">https://medium.com/media/683546603ce15f5cfcc7b45c282f897b/href</a></iframe><p>Ace is a special case where it can have a value of 1 or 11, depending on if your hand is over 21 or not, you can arbitrarily use it as 1 or 11.</p><p>Now we have the cards logic defined, let’s create a new class for game rooms, where we can host multiple participants in separate rooms.</p><pre>$ cd ../gameroom<br>$ touch __init__.py &amp;&amp; touch gameroom.py</pre><p>For game room, we’ll implement join to join a room, escape to leave a room, game_start to start a game and game_top to stop a game. For the sake of this tutorial, we’ll also fix the ante to a fixed amount per game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f415d5bbbf565a89ffa900713307032/href">https://medium.com/media/2f415d5bbbf565a89ffa900713307032/href</a></iframe><p>We’ll be creating a web interface for the game in part 2 of this tutorial series, for that we’ll need to implement a few functions to accommodate these front-end features.</p><p>Let’s first incorporate the Chip SCORE we implemented earlier, we’ll define an interface (interfaceScore) that contains designated methods of Chip SCORE, enabling our game to use methods without repeat implementations. This is done by recording the chip SCORE’s CA via VarDB and the SCORE address to use when referenced.</p><pre># game.py</pre><pre>from iconservice import *<br><br>from .deck.deck import Deck<br>from .gameroom.gameroom import GameRoom<br>from .hand.hand import Hand<br><br>TAG = &#39;BLACKJACK&#39;<br><br><br>class ChipInterface(InterfaceScore):<br><br>    @interface<br>    def mint(self, _value: int):<br>        pass<br><br>    @interface<br>    def burn(self, _amount: int):<br>        pass<br><br>    @interface<br>    def balanceOf(self, _owner: Address):<br>        pass<br><br>    @interface<br>    def transfer(self, _to: Address, _value: int, _data: bytes = None):<br>        pass<br><br>    @interface<br>    def bet(self, _from: Address, _to: Address, _value: int):<br>        pass</pre><p>We’ll demonstrate how to instantiate a new interface score later. Let’s get the basics down first,</p><pre># game.py</pre><pre>class Game(IconScoreBase):<br>    _TOKEN_ADDRESS = &quot;token_address&quot;<br>    _GAME_ROOM = &quot;game_room&quot;<br>    _GAME_ROOM_LIST = &quot;game_room_list&quot;<br>    _IN_GAME_ROOM = &quot;in_game_room&quot;<br>    _DECK = &quot;deck&quot;<br>    _HAND = &quot;hand&quot;<br>    _RESULTS = &quot;results&quot;<br>    _READY = &quot;ready&quot;<br>    _GAME_START_TIME = &quot;game_start_time&quot;</pre><pre>    # Here we passed our chip CA on_install <br>    def on_install(self, _tokenAddress: Address) -&gt; None:<br>        super().on_install()<br>        if _tokenAddress.is_contract:<br>            self._VDB_token_address.set(_tokenAddress)<br>        else:<br>            revert(&quot;Input params must be Contract Address&quot;)<br><br>    def on_update(self, **kwargs) -&gt; None:<br>        super().on_update()<br>        pass<br><br>    def __init__(self, db: &#39;IconScoreDatabase&#39;) -&gt; None:<br>        super().__init__(db)<br>        self._db = db<br>        self._VDB_token_address = VarDB(self._TOKEN_ADDRESS, db, value_type=Address)<br>        self._DDB_game_room = DictDB(self._GAME_ROOM, db, value_type=str)<br>        self._DDB_game_start_time = DictDB(self._GAME_START_TIME, db, value_type=int)<br>        self._DDB_in_game_room = DictDB(self._IN_GAME_ROOM, db, value_type=Address)<br>        self._DDB_deck = DictDB(self._DECK, db, value_type=str)<br>        self._DDB_hand = DictDB(self._HAND, db, value_type=str)<br>        self._DDB_ready = DictDB(self._READY, db, value_type=bool)</pre><p>This should be fairly intuitive with SCORE initiation and class variables that we need. Next let’s build some functions relating to game rooms, to show the list of rooms, join and escape, ante size, participants info etc.</p><pre>@property<br>def game_room_list(self):<br>    return ArrayDB(self._GAME_ROOM_LIST, self._db, value_type=str)</pre><pre>@external(readonly=True)<br>def showGameRoomList(self) -&gt; list:<br>    response = []<br>    game_room_list = self.game_room_list<br><br>    for game_room in game_room_list:<br>        game_room_dict = json_loads(game_room)<br>        game_room_id = game_room_dict[&#39;game_room_id&#39;]<br>        creation_time = game_room_dict[&#39;creation_time&#39;]<br>        prize_per_game = game_room_dict[&#39;prize_per_game&#39;]<br>        participants = game_room_dict[&#39;participants&#39;]<br>        room_has_vacant_seat = &quot;is Full&quot; if len(participants) &gt; 1 else &quot;has a vacant seat&quot;<br>        response.append(f&quot;{game_room_id} : ({len(participants)} / 2). The room {room_has_vacant_seat}. Prize : {prize_per_game}. Creation time : {creation_time}&quot;)<br><br>    return response<br><br>@external<br>def createRoom(self, _prizePerGame: int = 10):<br>    # Check whether &#39;self.msg.sender&#39; is now participating to game room or not<br>    if self._DDB_in_game_room[self.msg.sender] is not None:<br>        revert(&quot;You already joined to another room&quot;)<br><br>    # Check whether the chip balance of &#39;self.msg.sender&#39; exceeds the prize_per_game or not<br>    chip = self.create_interface_score(self._VDB_token_address.get(), ChipInterface)<br>    if chip.balanceOf(self.msg.sender) &lt; _prizePerGame:<br>        revert(&quot;Set the prize not to exceed your balance&quot;)<br><br>    # Create the game room &amp; get into it &amp; Set the prize_per_game value<br>    game_room = GameRoom(self.msg.sender, self.msg.sender, self.block.height, _prizePerGame)<br>    game_room.join(self.msg.sender)<br>    self._DDB_game_room[self.msg.sender] = str(game_room)<br><br>    game_room_list = self.game_room_list<br>    game_room_list.put(str(game_room))<br>    self._DDB_in_game_room[self.msg.sender] = self.msg.sender<br><br>    # Initialize the deck &amp; hand for the participant<br>    new_deck = Deck()<br>    self._DDB_deck[self.msg.sender] = str(new_deck)<br>    new_hand = Hand()<br>    self._DDB_hand[self.msg.sender] = str(new_hand)<br><br>def _crash_room(self, game_room_id: Address):<br>    game_room_to_crash_dict = json_loads(self._DDB_game_room[game_room_id])<br><br>    game_room_to_crash = GameRoom(Address.from_string(game_room_to_crash_dict[&#39;owner&#39;]), Address.from_string(game_room_to_crash_dict[&#39;game_room_id&#39;]), game_room_to_crash_dict[&#39;creation_time&#39;],<br>                         game_room_to_crash_dict[&#39;prize_per_game&#39;], game_room_to_crash_dict[&#39;participants&#39;], game_room_to_crash_dict[&#39;active&#39;])<br>    participants_to_escape = game_room_to_crash.participants<br>    for partcipant in participants_to_escape:<br>        self._DDB_in_game_room.remove(Address.from_string(partcipant))<br><br>    self._DDB_game_room.remove(game_room_id)<br>    game_room_list = list(self.game_room_list)<br>    game_room_list.remove(json_dumps(game_room_to_crash_dict))<br>    for count in range(len(self.game_room_list)):<br>        self.game_room_list.pop()<br><br>    for game_room in game_room_list:<br>        self.game_room_list.put(game_room)<br><br>@external<br>def joinRoom(self, _gameRoomId: Address):<br>    # Check whether the game room with game_room_id is existent or not<br>    if self._DDB_game_room[_gameRoomId] is &quot;&quot;:<br>        revert(f&quot;There is no game room which has equivalent id to {_gameRoomId}&quot;)<br><br>    # Check to see if the participant already joined to another game_room<br>    if self._DDB_in_game_room[self.msg.sender] is not None:<br>        revert(f&quot;You already joined another game room : {self._DDB_in_game_room[self.msg.sender]}&quot;)<br><br>    game_room_dict = json_loads(self._DDB_game_room[_gameRoomId])<br>    game_room = GameRoom(Address.from_string(game_room_dict[&#39;owner&#39;]), Address.from_string(game_room_dict[&#39;game_room_id&#39;]), game_room_dict[&#39;creation_time&#39;],<br>                         game_room_dict[&#39;prize_per_game&#39;], game_room_dict[&#39;participants&#39;], game_room_dict[&#39;active&#39;])<br>    game_room_list = self.game_room_list<br><br>    # Check the chip balance of &#39;self.msg.sender&#39; before getting in<br>    chip = self.create_interface_score(self._VDB_token_address.get(), ChipInterface)<br>    if chip.balanceOf(self.msg.sender) &lt; game_room.prize_per_game:<br>        revert(f&quot;Not enough chips to join this game room {_gameRoomId}. Require {game_room.prize_per_game} chips&quot;)<br><br>    # Check the game room&#39;s participants. Max : 2<br>    if len(game_room.participants) &gt; 1:<br>        revert(f&quot;Full : Can not join to game room {_gameRoomId}&quot;)<br><br>    # Get into the game room<br>    game_room.join(self.msg.sender)<br>    self._DDB_in_game_room[self.msg.sender] = _gameRoomId<br>    self._DDB_game_room[_gameRoomId] = str(game_room)<br><br>    game_room_index_gen = (index for index in range(len(game_room_list)) if game_room.game_room_id == Address.from_string(json_loads(game_room_list[index])[&#39;game_room_id&#39;]))<br><br>    try:<br>        index = next(game_room_index_gen)<br>        game_room_list[index] = str(game_room)<br>    except StopIteration:<br>        pass<br><br>    # Initialize the deck &amp; hand for the participant<br>    new_deck = Deck()<br>    self._DDB_deck[self.msg.sender] = str(new_deck)<br>    new_hand = Hand()<br>    self._DDB_hand[self.msg.sender] = str(new_hand)<br><br>@external<br>def escape(self):<br>    # Check whether &#39;self.msg.sender&#39; is already participating or not<br>    if self._DDB_in_game_room[self.msg.sender] is None:<br>        revert(f&#39;No game room to escape&#39;)<br><br>    # Retrieve the game room ID &amp; check the game room status<br>    game_room_id_to_escape = self._DDB_in_game_room[self.msg.sender]<br>    game_room_to_escape_dict = json_loads(self._DDB_game_room[game_room_id_to_escape])<br>    game_room_to_escape = GameRoom(Address.from_string(game_room_to_escape_dict[&#39;owner&#39;]), Address.from_string(game_room_to_escape_dict[&#39;game_room_id&#39;]),<br>                                   game_room_to_escape_dict[&#39;creation_time&#39;], game_room_to_escape_dict[&#39;prize_per_game&#39;],<br>                                   game_room_to_escape_dict[&#39;participants&#39;], game_room_to_escape_dict[&#39;active&#39;])<br><br>    if game_room_to_escape.active:<br>        revert(&quot;The game is ongoing.&quot;)<br><br>    # Escape from the game room<br>    if game_room_to_escape.owner == self.msg.sender:<br>        if len(game_room_to_escape.participants) == 1:<br>            game_room_to_escape.escape(self.msg.sender)<br>            self._crash_room(game_room_id_to_escape)<br>        else:<br>            revert(&quot;Owner can not escape from room which has the other participant&quot;)<br>    else:<br>        game_room_to_escape.escape(self.msg.sender)<br>        self._DDB_game_room[game_room_id_to_escape] = str(game_room_to_escape)<br><br>    # Set the in_game_room status of &#39;self.msg.sender&#39; to None<br>    game_room_list = self.game_room_list<br>    game_room_index_gen = (index for index in range(len(game_room_list)) if game_room_to_escape.game_room_id == Address.from_string(json_loads(game_room_list[index])[&#39;game_room_id&#39;]))<br><br>    try:<br>        index = next(game_room_index_gen)<br>        game_room_list[index] = str(game_room_to_escape)<br>    except StopIteration:<br>        pass<br><br>    self._DDB_in_game_room.remove(self.msg.sender)<br><br>def _ban(self, game_room_id: Address, participant_to_ban: Address):<br>    game_room_dict = json_loads(self._DDB_game_room[game_room_id])<br>    game_room = GameRoom(Address.from_string(game_room_dict[&#39;owner&#39;]), Address.from_string(game_room_dict[&#39;game_room_id&#39;]), game_room_dict[&#39;creation_time&#39;],<br>                         game_room_dict[&#39;prize_per_game&#39;], game_room_dict[&#39;participants&#39;], game_room_dict[&#39;active&#39;])<br>    if game_room.owner == participant_to_ban:<br>        for participant in game_room.participants:<br>            self._DDB_in_game_room.remove(Address.from_string(participant))<br>            game_room.escape(Address.from_string(participant))<br>        self._crash_room(game_room_id)<br>    else:<br>        game_room.escape(participant_to_ban)<br>        self._DDB_game_room[game_room_id] = str(game_room)<br>        self._DDB_in_game_room.remove(participant_to_ban)<br>        game_room_list = self.game_room_list<br>        game_room_index_gen = (index for index in range(len(game_room_list)) if game_room.game_room_id == Address.from_string(json_loads(game_room_list[index])[&#39;game_room_id&#39;]))<br><br>        try:<br>            index = next(game_room_index_gen)<br>            game_room_list[index] = str(game_room)<br>        except StopIteration:<br>            pass</pre><p>Let’s inspect the createRoom function, notice</p><pre>chip = self.create_interface_score(self._VDB_token_address.get(), ChipInterface)</pre><p>In this initiation, we used the interfaceScore that maps to the varDB holding our chip SCORE. We can then use the functions implemented in the SCORE, in this case we check requester’s chip balance using chip.balanceOf , without implementing balanceOf again.</p><p>we can implement this into an external method to query like so</p><pre>@external(readonly=True)<br>def getChipBalance(self) -&gt; int:<br>    chip = self.create_interface_score(self._VDB_token_address.get(), ChipInterface)<br>    return chip.balanceOf(self.msg.sender)</pre><p>Rest of the game logic include gameStart that checks to see if the room has been filled or if the caller is in another room. A hit function to simulate hit in a hand, for demonstration purposes we’re fixing this up to 4 hits and the player will simply hold. Finally we need a calculate function to determine the winning logic. There are up to 2 participants per room, so the losing hand will simply transfer to the winning hand based on the fixed ante.</p><p>Here’s the entire game.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/500ff87536165895e9e743141ec8e0fe/href">https://medium.com/media/500ff87536165895e9e743141ec8e0fe/href</a></iframe><p>Now we’re ready to deploy this to the testnet, we need to pass the _tokenAddress parameter, this would be the CA of the chip SCORE that you deployed earlier. Let’s modify the tbears config file,</p><pre># tbears_cli_config_testnet.json</pre><pre>{<br>    &quot;uri&quot;: &quot;https://bicon.net.solidwallet.io/api/v3&quot;,<br>    &quot;nid&quot;: &quot;0x3&quot;,<br>    &quot;keyStore&quot;: null,<br>    &quot;from&quot;: &quot;hx5638ee91e18574a1f0a29b4813578389f0e142a7&quot;,<br>    &quot;to&quot;: &quot;cx0000000000000000000000000000000000000000&quot;,<br>    &quot;deploy&quot;: {<br>        &quot;stepLimit&quot;: &quot;0x77359400&quot;,<br>        &quot;mode&quot;: &quot;install&quot;,<br>        &quot;scoreParams&quot;: {<br>            &quot;_tokenAddress&quot;: &quot;cx2070cdae8e8c268ca5125921222968f9110617bb&quot;<br>        }<br>    },<br>    &quot;txresult&quot;: {},<br>    &quot;transfer&quot;: {<br>        &quot;stepLimit&quot;: &quot;0x300000&quot;<br>    }<br>}</pre><p>Replace the _tokenAddress with your chip SCORE, then deploy</p><pre>tbears deploy game -k iconkeystore3 -c tbears_cli_config_testnet.json</pre><p>and see if the transaction was successful</p><pre>tbears txresult 0x3fe5b6a1c712ea7b69bcc1d1be4255796ab72260d3f182274d839be80ef70e90 -u <a href="https://bicon.net.solidwallet.io/api/v3">https://bicon.net.solidwallet.io/api/v3</a></pre><p>Let’s try to run our new SCORE, launch ICONex Chrome and go to ‘Contract’ tab, paste the new SCORE address and you should see the external functions. Let’s experiment mintChips ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C6gZNQAfqa8AJft8HBmg0A.png" /></figure><p>Write the transaction first. Go back to the home screen where your wallets are, click on the far right settings button to add the blackjack token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*QHsjfIKG-wW5rToT8I4QjA.png" /></figure><p>Input your chip SCORE address, the rest should be auto-filled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*MbJq3iREFg3n0SssfCKhiA.png" /></figure><p>Add it to your wallet, and see if the BJC balance is reflected from the mintChips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6E_N3BS_PXtI8eOVnIJOLg.png" /></figure><p>Voila, you now have plenty of blackjack chips to start gambling! Feel free to experiment other methods to see if each functions properly.</p><p>In this tutorial we implemented two SCOREs, one token contract for the blackjack IRC-2 tokens and another SCORE to build the blackjack game logic. We also learned iconscore_interface in order to re-use SCORE functions, and we learned how to invoke contract calls directly from ICONex to avoid JSON-RPC calls every time. In the next tutorial, we’ll be building a web interface for our game using the <a href="https://www.djangoproject.com/">Django web framework</a>, and allow users to play the game on a website without worrying about the blockchain technology behind! Players will be able to use their IRC-2 tokens from an ICONex wallet to start betting on the ICON network, stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a724cff7bb15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To ICON Community]]></title>
            <link>https://medium.com/@2infiniti/to-icon-community-fab7c4103627?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab7c4103627</guid>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[icx]]></category>
            <category><![CDATA[ama]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[community]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 08:35:15 GMT</pubDate>
            <atom:updated>2018-11-19T09:39:59.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I want to talk about the state of ICON community, an opinion piece you rarely see from me. I just have one question to ask before you read on, am I the only person who is more and more frustrated with our own community members?</p><p><strong>Who the hell is 2infiniti?</strong></p><p>You might not know who I am but you should’ve seen some of my contributions at one point. Just to brief you, I was around pretty much since day 1, I was among the early contributors and one of the first to fully review ICON project from due diligence to detailed technical analysis. I was also the creator of the first ICON fan site icon.support, creator of DAPPs portal site dapps.icon.support, creator of ICON Community Alliance HX57 hx57.io. Administrator/CM/Ambassador of our main channel, creator/admin of many other ICON related channels. Misc efforts you might’ve seen like ICON FAQ Bot, ICON markets, Virtual Step Calculator, etc. Lately you may have seen several ICON DAPP building tutorials from this medium account or my tweets about ICON issuance model/IISS/P-rep governance etc. I might’ve answered you on TG, we could’ve chatted about the project, about crypto, or maybe just random shit in life. The point is, I was there, I am one of you. I’ve gotten to known many by first name, and have even met a few in real life. I have also visited Korea office, SF office, and met with many team members and foundation councils. I am quite positive that my observations are not only thorough but also quite confident about being objective.</p><p><strong>A throwback to presale days</strong></p><p>During this period, everyone was exploring the project, learning, and exchanging thoughts, very good thoughts. Visiting our channel was almost always the first thing I did every morning. I was eager to learn new information, there were always interesting conversations that I wanted to take part in, and I could always learn a thing or two from community members. It was a very healthy and fun community to be in, and the focus was always the long term vision and how we plan to accomplish it. Without price being in the equation (ICX was not listed then), everyone spoke with great rationale and activities were without intentions but to learn from each other.</p><p><strong>Fast forwarding to today</strong></p><p>Lately highlights are centered around FUD, sometimes FOMO and memes, but rarely any good discussions.</p><p>This is probably okay for someone like me who spends several hours a day doing research and has the patience to explore. I can’t imagine what its like for an average person who only has 30 minutes to spare for ICON during their busy day, visiting our social channels and forums just to get mind fucked with senseless rants.</p><p>No, I am not talking about constructive criticisms, I am talking about personal attacks, racial slurs, conspiracy theories, accusations or people who just build unrealistic expectations and act entitled and demanding all day long.</p><p>Let’s get to criticisms, they’re fine, really. I think this is one of the easiest ways to contribute to the project. Yes complaints can be contributions, if they’re presented constructively, well organized and thought out. By doing so, someone from the community or the team can help resolve and improve upon these suggestions. One example is the recent <a href="https://www.reddit.com/r/helloicon/comments/9vsj98/ama_community_edition/">reddit AMA</a> thread I started, these are all the questions that I collected from other community members. To me these were suggestions for improvement or questions needing research. I was able to provide most of the answers correctly, this is evident with the team’s <a href="https://medium.com/helloiconworld/icon-foundation-addressing-the-community-7cec5e852d42">latest announcement</a>. Did I have more information than the rest of you? No. Did I know more than most people? Yes, because I have the luxury to read everything published, sometimes twice. I understand some of you just don’t have the time to read everything, but this is the purpose of a community, we help each other out. During this process I also had to weed out many unrealistic expectations, things like “Show me team members’ wallets so I can monitor their movement because this is a blockchain company” or “the team needs to announce the buyback wallet and timeline so we know they’re actually doing it”. My only suggestion is, have better expectations, they really just don’t make any sense. I also get requests like “Explain why the team sold 5% of their tokens in the open market, someone told me”. I am sure even you don’t believe that, you just want to throw it out there.</p><p><strong>A consistent trend</strong></p><p>There’s only one consistent trend currently — Toxic people speaking louder and louder, well researched people becoming much quieter.</p><p>From my observation, this is mostly due to <strong>sentiments are directly correlated to price</strong>, much less project progress. Whenever I visit our subreddit or telegram channel, what I am about to see is quite predictable. Price goes down, the team did something wrong, fuck ICX, exit scam. Price goes up, best project in the entire universe, I just loaded up my bag, to the moon.</p><p>I am no longer looking at any goals or problems to solve, I am just looking at every reason an angry investor can think of, mostly to justify for the price drop/inaction.</p><p>Let’s also face the reality that, even if the project is progressing well for the most part, if the price drops, we’re probably still going to blame the team with something.</p><p>Personally I am just a bit exhausted and burned out, having to deal with people who can’t think beyond their own reasons, and that’s on a good day. On a bad day, people won’t even read digestible bites presented to them. They choose to criticize everything they can think of and stay in their anger zone, this trend has also become quite prevalent.</p><p>These nonconstructive criticisms only degenerate the community, where people start taking frustrations out on each other and the team.</p><p>This is also a vicious cycle, people stopped teaching each other, people stopped learning from each other. The rooms are consistently getting more and more toxic, and it only goes downhill from there.</p><p><strong>So what is it that we want?</strong></p><p>We need to somehow normalize this experience, maybe consolidate criticisms into fewer threads and discuss solutions there. Or start new initiatives and spark interesting ideas. Perhaps look into the technology and start some actual development. Or even just sharing industry news and analyze our competitive advantage will be interesting. There’s plenty of things to talk about and there’s plenty of knowledgeable community members to discuss with. I remember the day when I brought up the community alliance idea, people got so excited and all swarmed in ready to help, sometimes all we need is for someone to take this first step. It is really in all of our hands, how exactly do we go about this I do not know, but I do know that this is definitely fixable. We just need to remember the goal of having a community, it’s really all about <strong>improvement</strong>.</p><p>I can think of a few advice to give to our community members,</p><ul><li>Stay informed, stick to facts</li><li>Be mature, discuss rationally</li><li>Be forgiving, then create realistic expectations</li><li>Be optimistic, even during down times</li><li>Have patience</li></ul><p>I know these are moot points that have been repeated too many times, but it is what it is, you won’t help the situation staying pissed the whole time. This leads to another point that I wanted to remind everyone. I believe the majority of our community base are all after one thing — <strong>protecting your investment</strong>. I know I am doing everything to achieve just that, are you?</p><p><strong>Why is ICX is among the top worst performers?</strong></p><p>I can’t speak for every project, but at least the projects that I closely follow, ICON’s development progress both tech and business are among the top performers. Most of you would probably disagree with tech progress, but most of you probably also never looked into the code. It is sometimes happening so fast that I have a hard time keeping up. Feel free to ask any community members who track closely with tech development, members like spl3en, Jerome, nicolas, the folks at ICON Dev channel, we know better. Tech development is not just “when YP pt3”,“why no dex”. T-bears improvement, additional SDKs, refactoring and testing ICON Service Core, upgrades in JSON RPC Server, Governance API specification, general technical documentation, there’s a lot of things happening concurrently, necessary steps to ensure a long term robust, secure, scalable and extensible system. It is one thing to hack out something that more or less work, just to meet deadlines. Quite another to be build with highest standards every step of the way, even at the expense of missing deadlines and taking heat from the community.</p><p>So why is ICX among the worst performers? Is it simply BTC correlation? I think not. Is it team’s poor performance? I just disagreed. My observation is that, our community members generally have better clarity of thought, more experienced in life, and very capable of convincing others with their own reasons, this is a double-sided blade. During the bull market, we were mooning harder than all others. It took us a little over 2 months to go 100x from ICO. In the history of cryptocurrency, only a handful of ICOs pulled this off, we also started with one of the highest market cap at $43m. I felt our community members were definitely a great contributing factor.</p><p>Now we’re in a bear market, our thoughts turn negative. Our community members as usual provided great analysis how things might’ve gone wrong, at first. They’ve gone great lengths providing further thoughts, some emotional and irrational, to a point they started name calling getting personal, making stuff up, looking for every way to let out their angers, just mere vengeance for a sense of satisfaction. They basically got lost in their intentions, which is to protect their investment, instead they’re sabotaging in every way possible.</p><p>Unfortunately during this process, weak hands got shaken out, new investors are afraid to come in given what we’re presenting to them, buyers stopped accumulating just observing if the sentiment or market will turn at some point.</p><p>Other communities all have FUDs of some sort during this bear market, they all criticize their team one way or another, but not many do it as well as ours (lol?). Of course this is not the main reason of such a drastic drop in price, but it is definitely a contributing factor that we all possess some power to make a change.</p><p>We should also take a step back and inspect what’s changed fundamentally since our ICO. More top talents recruited, more work is done, more partnerships signed, ETH raised barely spent, ICX tokens still at a healthy 3x+. Is the team in a bad shape in any way? Not at all. What has changed fundamentally? It’s our community.</p><p>Now my question back to you, do we want to get together and turn this around, together with the team, and make ICX great again? Or do we want to go down that rabbit hole and never see the light again? If you can think of one thing the team didn’t do well, so can you with one thing the community can do better.</p><p><strong>You reap what you sow</strong></p><p>Now enough about our community, what about the team? Are they doing everything so perfectly that you have to blame us for everything? Definitely not. The source of anger really boils down to two major categories.</p><p><strong>Communication</strong></p><p>This include transparency in business developments, like I also have been wondering what the team is currently doing with all these different partnerships and MOUs. What projects are in active development, what type of collaborations can we expect from LINE or SKPlanet etc. People want transparency because it shows progress, and progress tells us if the team is on the right track, at what speed, then naturally we can build better expectations.</p><p>From team’s stance, a lot of the information just cannot be disclosed ahead of time, especially for the intention of speculation. Plus releasing information prematurely will lead to all sorts of false expectations, we’re just really good at doing that.</p><p>So what is the middle ground here? Things that can be communicated should be communicated, be more proactive. I am not talking about some top-level classified initiatives that competitors have the chance to front-run you if they find out. I am talking about smaller updates with new information, “Yes we have been working closely with LINE, some of these plans will be announced when things are ready, and this goes way beyond a simple partnership agreement” basically what Henry revealed in <a href="https://youtu.be/paFYyt1hVWc?t=155">this interview</a>. More of these, we want to hear them.</p><p>Communication also includes clearer explanations. I have on many many occasions seen the same information interpreted very differently. This includes things like 800m total supply, 20% issuance upper-bound, to latest announcement of the 5m buyback. Even though I felt things were explained perfectly clear, but if this is a common problem, it is a problem.</p><p>We should also treat ICON members with respect, just like how they have been treating us. Yes we have concerns / criticisms / frustrations, but you really don’t have to be rude about it. We did have a communication bridge, Min. He has been active on twitter, shows up to our telegram channel from time to time to help answer questions and provide insights and look at what you guys are doing to him. The guy who has the most answers and you spend the opportunity to bash him because the price is down? Try to get answers instead, even if its not immediately responded, you know the message is delivered to the right person who will try to resolve it for you.</p><p>Obviously the team also has new plans to improve communication, the new head of contributor relations Ricky and this new FAQ portal that’s supposed to serve as curated AMA. Let’s leverage these, as these are your best bets at getting answers directly from the team. Ranting on telegram will never get you answers.</p><p><strong>Roadmap</strong></p><p>This is another raging point, and I don’t expect everyone to understand delays or reasons for not delivering (pivoting, priority shift with resource re-delegation, projections vs actual deadlines etc). I know the crowd expects a deadline the team adheres to and deliver as promised, and that’s perfectly acceptable. This is however extremely difficult for a large-scaled, fast-paced project like ICON. Again in a situation like this, instead of abandoning the roadmap altogether, we need to have a middle ground. I have been suggesting a percentage based (or at least change log updates) roadmap instead, as far as I can tell, most people are more interested in progress, less deadlines. More about honoring promises, less about deliverable.</p><p>The above two areas I am with everyone here, there’s definitely room for improvement. The team can think of their improvement ideas, but we should also let them know what the popular opinions are within the community, properly. “The team has zero communication” just won’t cut it, extend on that, suggest your way of improvement if you don’t like what the team is doing. Email the team with your plan, submit your suggestion via the new FAQ portal, write a <a href="https://github.com/hx57/ICIPs">community improvement proposal</a> and get the whole alliance on board, ask your favorite YouTuber to request for a formal interview. Whatever you think works better, but you need to put in some efforts to be taken seriously, shouting out loud on Telegram really doesn’t do anything but escalate your own anger. Don’t stop at rant, lead legit criticisms to actual improvements through proper channels.</p><p><strong>TL;DR</strong></p><p>The purpose of having a community is <strong>improvement</strong>, criticisms should lead to <strong>solutions</strong>, remember your goal is to <strong>protect your investment.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab7c4103627" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICON Workshop — ICONex Web Connect]]></title>
            <link>https://medium.com/@2infiniti/icon-workshop-iconex-web-connect-164ff3cd6792?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/164ff3cd6792</guid>
            <category><![CDATA[icondev]]></category>
            <category><![CDATA[coinex]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[icx]]></category>
            <category><![CDATA[dapps]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 07:35:55 GMT</pubDate>
            <atom:updated>2018-11-08T01:19:20.309Z</atom:updated>
            <content:encoded><![CDATA[<h3>ICON Workshop — ICONex Web Connect</h3><p>In the past tutorials we have been invoking SCORE calls and making ICX transfers through hardcoded wallet files, this obviously isn’t ideal nor practical for DAPP users. Today I am going to show you how to connect to <a href="https://chrome.google.com/webstore/detail/iconex/flpiciilemghbmfalicajoolhkkenfel?hl=en">ICONex Chrome Extension</a> from your web app, thereby enabling users to interact with your DAPP via their own wallets.</p><p>In this tutorial, since everything is frontend development, we’ll be working under one single html file, using the new <a href="https://github.com/icon-project/icon-sdk-js">ICON SDK for Javascript</a> to invoke the core ICON Service methods.</p><p><strong>Demo: https://dapps.icon.support/iconex-webconnect/</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*11w68USqdE2KkOXEJr9Alw.png" /></figure><p>Create a new environment for our project,</p><pre># Create a new environment</pre><pre>$ mkdir iconex-webconnect &amp;&amp; cd iconex-webconnect<br>$ touch index.html</pre><p>ICON SDK for Javascript can be installed via npm or you can simply include the js file via CDN host.</p><pre>&lt;script src=&quot;https://cdn.jsdelivr.net/gh/icon-project/icon-sdk-js/build/icon-sdk-js.min.js&quot;&gt;&lt;/script&gt;</pre><p>For this exercise we’ll use <a href="https://getbootstrap.com/">bootstrap 4</a> to stylize the page a little.</p><p>Create the bare-bone index.html</p><pre># index.html</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>   &lt;meta charset=&quot;UTF-8&quot;&gt;<br>   &lt;title&gt;ICONex Web Connect Demo&lt;/title&gt;<br>   &lt;!-- bootstrap 4 style --&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;!-- ICON SDK for Javascript --&gt;<br>&lt;script src=&quot;http://cdn.jsdelivr.net/gh/icon-project/icon-sdk-js@latest/build/icon-sdk-js.min.js&quot;&gt;&lt;/script&gt;<br>&lt;!-- bootstrap 4 --&gt;<br>&lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4><strong>CustomEvent</strong></h4><p>We need to use CustomEvent for dispatching and listening event. The type and payload of events are assigned to the detail field. type is a string of pre-defined type of events, and payload can be any type, that contains the body of your request or response. We’ll explain more by actual implementation in a bit.</p><p>We’ll start off by exploring the available types of events, they are</p><p><strong>HAS_ACCOUNT</strong>:REQUEST_HAS_ACCOUNT, RESPONSE_HAS_ACCOUNT</p><p><strong>HAS_ADDRESS</strong>:REQUEST_HAS_ADDRESS, RESPONSE_HAS_ADDRESS</p><p><strong>ADDRESS:</strong>REQUEST_ADDRESS<strong>, </strong>RESPONSE_ADDRESS</p><p><strong>JSON-RPC:</strong>REQUEST_JSON-RPC, RESPONSE_JSON-RPC</p><p><strong>SIGNING:</strong>REQUEST_SIGNING, RESPONSE_SIGNING</p><h4>HAS_ACCOUNT</h4><p>This event will allow us to determine whether the client’s ICONex has any wallets. We’ll demonstrate here how to create a CustomEvent and dispatch that event with our request’s type, how to access type and payload data for the event handler to work with the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ffeac13d00056777506ed5703644df6/href">https://medium.com/media/0ffeac13d00056777506ed5703644df6/href</a></iframe><p>Access the page via a local webserver, clicking the button will invoke the event and return true if you have wallets in ICONex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yhsjql5c8ifHOU6CVoUlwQ.png" /></figure><h4>HAS_ADDRESS</h4><p>Following a very similar implementation to HAS_ACCOUNT, we’ll register the onclick event to the button and dispatch a custom event to request for REQUEST_HAS_ADDRESS and add this to one of our event cases.</p><pre>&lt;!-- HAS_ADDRESS --&gt;<br>&lt;div class=&quot;my-3 p-3 bg-white rounded shadow-sm&quot;&gt;<br>    &lt;h5 class=&quot;pb-2 mb-3 ml-3&quot;&gt;HAS_ADDRESS&lt;/h5&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;label for=&quot;formGroupExampleInput&quot;&gt;ICX Address: &lt;/label&gt;<br>        &lt;input id=&quot;request-has-address-data&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;hx0000000000000000000000000000000000000000&quot;&gt;&lt;br&gt;<br>        &lt;button id=&quot;request-has-address&quot; type=&quot;button&quot; class=&quot;btn btn-outline-primary&quot;&gt;Is this address in my ICONex?&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div id=&quot;response-has-address&quot; class=&quot;mt-3 ml-3&quot;&gt;&gt; Result : &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>...</pre><pre><strong>var </strong>requestHasAddress = document.getElementById(&quot;request-has-address&quot;);<br><strong>var </strong>requestHasAddressData = document.getElementById(&quot;request-has-address-data&quot;);<br><strong>var </strong>responseHasAddress = document.getElementById(&quot;response-has-address&quot;);</pre><pre>...</pre><pre><strong>case </strong>&quot;RESPONSE_HAS_ADDRESS&quot;:<br>    responseHasAddress.innerHTML = &quot;&gt; Result : &quot; + payload.hasAddress + &quot; (&quot; + <strong>typeof </strong>payload.hasAddress + &quot;)&quot;;<br>    <strong>break</strong>;<br><strong>default</strong>:</pre><pre>...</pre><pre>requestHasAddress.onclick = <strong>function </strong>() {<br>    window.dispatchEvent(<strong>new </strong>CustomEvent(&#39;ICONEX_RELAY_REQUEST&#39;, {<br>        detail: {<br>            type: &#39;REQUEST_HAS_ADDRESS&#39;,<br>            payload: requestHasAddressData.value || requestHasAddressData.placeholder<br>        }<br>    }))<br>};</pre><h4>ADDRESS</h4><p>We’ll allow the user to select an active wallet they wish to use, in order to make requests, this is done via REQUEST_ADDRESS. The server will respond with RESPONSE_ADDRESS.</p><pre>&lt;!-- ADDRESS --&gt;<br>&lt;div class=&quot;my-3 p-3 bg-white rounded shadow-sm&quot;&gt;<br>    &lt;h5 class=&quot;pb-2 mb-3 ml-3&quot;&gt;ADDRESS&lt;/h5&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;button id=&quot;request-address&quot; type=&quot;button&quot; class=&quot;btn btn-outline-primary&quot;&gt;Which wallet to use for this session?&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div id=&quot;response-address&quot; class=&quot;mt-3 ml-3&quot;&gt;&gt; Result : &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>...</pre><pre><strong>var </strong>requestAddress = document.getElementById(&quot;request-address&quot;);<br><strong>var </strong>responseAddress = document.getElementById(&quot;response-address&quot;);</pre><pre>...</pre><pre><strong>case </strong>&quot;RESPONSE_ADDRESS&quot;:<br>    fromAddress = payload;<br>    responseAddress.innerHTML = &quot;&gt; Selected ICX Address : &quot; + payload;<br>    <strong>break</strong>;<br><strong>default</strong>:</pre><pre>...</pre><pre>requestAddress.onclick = <strong>function </strong>() {<br>    window.dispatchEvent(<strong>new </strong>CustomEvent(&#39;ICONEX_RELAY_REQUEST&#39;, {<br>        detail: {<br>            type: &#39;REQUEST_ADDRESS&#39;<br>        }<br>    }))<br>};</pre><h4>JSON-RPC</h4><p>This allows us to make requests by calling ICON JSON-RPC API, note you’re required to select an ICX wallet from previous step, as we’ll be calling from the wallet you chose. We’ll demonstrate Custom, which you can use an arbitrary JSON method of your choice. ReadOnly, which calls a read-only method of a SCORE that does not cost anything. SendTransaction that calls a SCORE function (not read-only) and ICX Transfer which are transactions that’ll cost ICX so you’re required to confirm with wallet password.</p><pre><strong>var </strong>iconService = window[&#39;icon-sdk-js&#39;];<br><strong>var </strong>IconAmount = iconService.IconAmount;<br><strong>var </strong>IconConverter = iconService.IconConverter;<br><strong>var </strong>IconBuilder = iconService.IconBuilder;<br><strong>var </strong>requestScore = document.getElementById(&quot;request-score&quot;);<br><strong>var </strong>requestScoreForm = document.getElementById(&quot;request-score-form&quot;);<br><strong>var </strong>responseScore = document.getElementById(&quot;response-score&quot;);<br><strong>var </strong>jsonRpc0 = document.getElementById(&quot;json-rpc-0&quot;);<br><strong>var </strong>jsonRpc1 = document.getElementById(&quot;json-rpc-1&quot;);<br><strong>var </strong>jsonRpc2 = document.getElementById(&quot;json-rpc-2&quot;);<br><strong>var </strong>jsonRpc3 = document.getElementById(&quot;json-rpc-3&quot;);<br><strong>var </strong>scoreData = document.getElementById(&quot;score-data&quot;);</pre><pre>...</pre><pre><strong>case </strong>&quot;RESPONSE_ADDRESS&quot;:<br>    fromAddress = payload;<br>    responseAddress.innerHTML = &quot;&gt; Selected ICX Address : &quot; + payload;<br>    jsonRpc0.disabled = <strong>false</strong>;<br>    jsonRpc1.disabled = <strong>false</strong>;<br>    jsonRpc2.disabled = <strong>false</strong>;<br>    jsonRpc3.disabled = <strong>false</strong>;<br>    <strong>break</strong>;<br><strong>case </strong>&quot;RESPONSE_JSON-RPC&quot;:<br>    responseScore.value = JSON.stringify(payload);<br>    <strong>break</strong>;<br><strong>case </strong>&quot;CANCEL_JSON-RPC&quot;:<br>    responseScore.value = <strong>null</strong>;<br>    <strong>break</strong>;<br><strong>default</strong>:</pre><pre>...</pre><pre><strong>function </strong>setRequestScoreForm() {<br>    <strong>var </strong>data = <strong>new </strong>FormData(requestScoreForm);<br>    <strong>var </strong>type = &#39;&#39;;<br>    <strong>for </strong>(<strong>const </strong>entry <strong>of </strong>data) {<br>        type = entry[1]<br>    }<br>    <strong>switch </strong>(type) {<br>        <strong>case </strong>&#39;read-only&#39;:<br>            <strong>var </strong>callBuilder = <strong>new </strong>IconBuilder.CallBuilder;<br>            <strong>var </strong>readOnlyData = callBuilder<br>                .from(fromAddress)<br>                .to(&#39;cx43f59485bd34d0c7e9312835d65cb399f6d29651&#39;)<br>                .method(&quot;hello&quot;)<br>                .build();<br>            scoreData.value = JSON.stringify({<br>                &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>                &quot;method&quot;: &quot;icx_call&quot;,<br>                &quot;params&quot;: readOnlyData,<br>                &quot;id&quot;: 50889<br>            });<br>            <strong>break</strong>;<br><br>        <strong>case </strong>&#39;send-transaction&#39;:<br>            <strong>var </strong>callTransactionBuilder = <strong>new </strong>IconBuilder.CallTransactionBuilder;<br>            <strong>var </strong>callTransactionData = callTransactionBuilder<br>                .from(fromAddress)<br>                .to(&quot;cxb20b5ff06ba50aef42c7832958af59f9ae0651e7&quot;)<br>                .nid(IconConverter.toBigNumber(3))<br>                .timestamp((<strong>new </strong>Date()).getTime() * 1000)<br>                .stepLimit(IconConverter.toBigNumber(1000000))<br>                .version(IconConverter.toBigNumber(3))<br>                .method(&#39;createToken&#39;)<br>                .params({<br>                    &quot;price&quot;: IconConverter.toHex(10000),<br>                    &quot;tokenType&quot;: IconConverter.toHex(2)<br>                })<br>                .build();<br>            scoreData.value = JSON.stringify({<br>                &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>                &quot;method&quot;: &quot;icx_sendTransaction&quot;,<br>                &quot;params&quot;: IconConverter.toRawTransaction(callTransactionData),<br>                &quot;id&quot;: 50889<br>            });<br>            <strong>break</strong>;<br><br>        <strong>case </strong>&#39;icx-transfer&#39;:<br>            <strong>var </strong>icxTransactionBuilder = <strong>new </strong>IconBuilder.IcxTransactionBuilder;<br>            <strong>var </strong>icxTransferData = icxTransactionBuilder<br>                .from(fromAddress)<br>                .to(&quot;hx04d669879227bb24fc32312c408b0d5503362ef0&quot;)<br>                .nid(IconConverter.toBigNumber(3))<br>                .value(IconAmount.of(1, IconAmount.Unit.ICX).toLoop())<br>                .timestamp((<strong>new </strong>Date()).getTime() * 1000)<br>                .version(IconConverter.toBigNumber(3))<br>                .stepLimit(IconConverter.toBigNumber(100000))<br>                .build();<br>            scoreData.value = JSON.stringify({<br>                &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>                &quot;method&quot;: &quot;icx_sendTransaction&quot;,<br>                &quot;params&quot;: IconConverter.toRawTransaction(icxTransferData),<br>                &quot;id&quot;: 50889<br>            });<br>            <strong>break</strong>;<br>        <strong>default</strong>:<br>    }<br>}</pre><pre>...</pre><pre>requestScore.onclick = <strong>function </strong>() {<br>    responseScore.value = <strong>null</strong>;<br><br>    <strong>if </strong>(!scoreData.value) {<br>        alert(&#39;Check the param data&#39;);<br>        <strong>return<br>    </strong>}<br><br>    <strong>var </strong>parsed = JSON.parse(scoreData.value);<br>    <strong>if </strong>(parsed.method === &quot;icx_sendTransaction&quot; &amp;&amp; !fromAddress) {<br>        alert(&#39;Select the ICX Address&#39;);<br>        <strong>return<br>    </strong>}<br><br>    window.dispatchEvent(<strong>new </strong>CustomEvent(&#39;ICONEX_RELAY_REQUEST&#39;, {<br>        detail: {<br>            type: &#39;REQUEST_JSON-RPC&#39;,<br>            payload: parsed<br>        }<br>    }))<br>};</pre><p>You can experiment with one of the JSON-RPC calls, we’ll select ICX transfer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFEQtWVlyUmnxAtNENwSUg.png" /></figure><p>Make the call and you should be prompted an ICONex window, enter your password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*Ife4EK8QmP8X5p-ZSkvfdw.png" /></figure><p>Make sure you’re selecting testnet YEOUIDO for the transfer, so you don’t actually spend any real ICX</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*KuJurJwji_MLOyl6JG6C1w.png" /></figure><p>The amount is set in the JSON-RPC call, IconAmount.of(1, IconAmount.Unit.ICX).toLoop() <a href="https://icon.support/toolbox/uc/">which is “0xde0b6b3a7640000” in hex</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ts70neNr-DHI_wF2zzByow.png" /></figure><p>You can check the transaction on the <a href="https://bicon.tracker.solidwallet.io/">live tracker</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fq6QMQhFeaJAA0W1WUdxhw.png" /></figure><h4>SIGNING</h4><p>REQUEST_SIGNING sends a request to sign tx hash, so user confirmation is required, RESPONSE_SIGNING will return the signature.</p><p>Make sure a wallet is selected first before you sign, then request signing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*b_LXFulN9RWVnszdgwvb6A.png" /></figure><p>You’ll be prompted to enter your password to confirm, once that’s done and submitted, you’ll get the signature back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZV5rYa-vpe_YzaylAyIEA.png" /></figure><p>The entire code,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b71778d9b75d378368dba72ca2c3cf7f/href">https://medium.com/media/b71778d9b75d378368dba72ca2c3cf7f/href</a></iframe><p><strong>Demo: </strong><a href="https://dapps.icon.support/iconex-webconnect/"><strong>https://dapps.icon.support/iconex-webconnect/</strong></a></p><p>That’s it for this ICONex web connect tutorial. This takes our DAPPs one step closer to being more practical and user friendly. We could apply this to <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-3-icon-dice-roll-dapp-7f0ca72057f5">tutorial series part 3 — ICON Dice Roll DAPP</a>, so the users will not have to leave the site to their ICONex to make the bets, a much friendlier experience. We could also apply this to the workshop <a href="https://medium.com/@2infiniti/icon-workshop-voting-dapp-c9581b1238d4">ICON Voting</a>, where instead of hardcoding 3 wallets for 3 votes, we could have unlimited number of votes, as long there’s more unique wallet addresses.</p><p>Follow me on Twitter for most up-to-date ICON related content: <a href="https://www.twitter.com/2infiniti">https://www.twitter.com/2infiniti</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164ff3cd6792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICON Workshop — Voting DAPP]]></title>
            <link>https://medium.com/@2infiniti/icon-workshop-voting-dapp-c9581b1238d4?source=rss-39cf298c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9581b1238d4</guid>
            <category><![CDATA[cores]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[icx]]></category>
            <category><![CDATA[icondev]]></category>
            <category><![CDATA[dapps]]></category>
            <dc:creator><![CDATA[2infiniti (Justin Hsiao)]]></dc:creator>
            <pubDate>Mon, 05 Nov 2018 06:29:26 GMT</pubDate>
            <atom:updated>2018-11-06T12:16:43.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>ICON Workshop — Voting DAPP</h3><p><a href="https://ibriz.ai/">ibriz inc</a> prepared another workshop item that was not presented at the ICON workshop during SF blockchain week. Unfortunately there’s no presentation available, but if you had done all previous tutorials <a href="https://medium.com/@2infiniti/creating-icon-dapp-from-a-z-part-1-tools-environment-dd56f8dfc905">part 1</a>, <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-2-score-af5f627e97e8">part 2</a>, and <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-3-icon-dice-roll-dapp-7f0ca72057f5">part3</a>, this one should be fairly easy to implement.</p><p>It is a simple voting DAPP using ICONex wallet, one vote per wallet, and the results are displayed on a webpage. Let’s go over the code in this tutorial, first get the project files from their gitlab repository,</p><pre>$ git clone <a href="https://gitlab.com/ibriz/icon-polling.git">https://gitlab.com/ibriz/icon-polling.git</a></pre><h4><strong>SCORE</strong></h4><p>Take a quick glance as our SCORE polling.py,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a0e0f13d5f5cd02ed30254d8205c9f4/href">https://medium.com/media/4a0e0f13d5f5cd02ed30254d8205c9f4/href</a></iframe><p>I’ve made some additional comments to the source file, the SCORE is really simple. It takes a contract call vote to receive votes, checks to see if the sender has voted, then log the results, that’s about it.</p><p>You can test locally first, we’ll skip this and deploy directly to testnet.</p><p>You need to fix tbears_cli_config_testnet.json as it is using some deprecated code,</p><pre>config/tbears_cli_config_testnet.json<br>{<br>    <em>&quot;uri&quot;</em>: &quot;https://bicon.net.solidwallet.io/api/v3&quot;,<br>    <em>&quot;nid&quot;</em>: &quot;0x3&quot;,<br>    <em>&quot;keyStore&quot;</em>: null,<br>    <em>&quot;from&quot;</em>: &quot;hxe9d75191906ccc604fc1e45a9f3c59fb856c215f&quot;,<br>    <em>&quot;to&quot;</em>: &quot;cx0000000000000000000000000000000000000000&quot;,<br>    <em>&quot;deploy&quot;</em>: {<br>        <em>&quot;stepLimit&quot;</em>: &quot;0x5a000000&quot;,<br>        <em>&quot;contentType&quot;</em>: &quot;zip&quot;,<br>        <em>&quot;mode&quot;</em>: &quot;install&quot;,<br>        <em>&quot;scoreParams&quot;</em>: {<br>        }<br>    },<br>    <em>&quot;txresult&quot;</em>: {},<br>    <em>&quot;transfer&quot;</em>: {}<br>}</pre><p>then deploy directly to testnet,</p><pre>$ tbears deploy polling -k keystores/keystore1.json -c config/tbears_cli_config_testnet.json</pre><pre># password <strong>p@ssword1</strong></pre><p>Check the result as usual,</p><pre>$ tbears txresult 0x3948fbf6ca67dd04801283c47123064e54d7324a358add345c8c4fd05fa1d385 -u <a href="https://bicon.net.solidwa/">https://bicon.net.solidwa</a><br>llet.io/api/v3</pre><p>keep scoreAddress somewhere, we’ll need to paste the address in a few places,</p><pre>&quot;scoreAddress&quot;: &quot;cx4e739b203b92498b6b6fb6d205f1cb62a6d4f88d&quot;</pre><p>Edit webapp/main.py and change default_score to our new SCORE address, also enable localhost on port 5000.</p><pre># webapp/main.py<br>default_score = &quot;cx4e739b203b92498b6b6fb6d205f1cb62a6d4f88d&quot;</pre><pre># Last line<br>app.run(debug=<em>True</em>, host=&#39;localhost&#39;, port=5000)</pre><p>Test run it and visit <a href="http://localhost:5000/">http://localhost:5000</a></p><pre>$ python main.py<br># Visit <a href="http://localhost:5000/">http://localhost:5000</a></pre><p>You should see an empty page without any votes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHzZ3XBF-Jk_Px2Lc8_oCg.png" /></figure><p>Replace keystore2.json and keystore3.json with your keystore files from testnet wallets, we’ll use iconkeystore3 and iconkeystore4. Copy these files from earlier tutorials into keystores/ folder. You can also use any wallets with some balance on the testnet.</p><p>Change the password under wallets in line 23 of webapp/main.py accordingly.</p><pre># webapp/main.py</pre><pre>wallets = {<br>    &#39;wallet1&#39;: KeyWallet.load(&quot;../keystores/keystore1.json&quot;, &quot;p@ssword1&quot;),<br>    &#39;wallet2&#39;: KeyWallet.load(&quot;../keystores/iconkeystore3&quot;, &quot;@icon333&quot;),<br>    &#39;wallet3&#39;: KeyWallet.load(&quot;../keystores/iconkeystore4&quot;, &quot;@icon444&quot;),<br>}</pre><p>Now cast our first vote with keystore1.json (wallet1), &quot;_vote&quot;: &quot;0x1&quot; = yes, &quot;_vote&quot;: &quot;0x2&quot; = no. In this example, we’re voting yes.</p><pre># testcmd/send.json<br>{<br>    <em>&quot;jsonrpc&quot;</em>: &quot;2.0&quot;,<br>    <em>&quot;method&quot;</em>: &quot;icx_sendTransaction&quot;,<br>    <em>&quot;params&quot;</em>: {<br>        <em>&quot;version&quot;</em>: &quot;0x3&quot;,<br>        <em>&quot;from&quot;</em>: &quot;hxe9d75191906ccc604fc1e45a9f3c59fb856c215f&quot;,<br>        <em>&quot;value&quot;</em>: &quot;0x0&quot;,<br>        <em>&quot;stepLimit&quot;</em>: &quot;0x200000&quot;,<br>        <em>&quot;nid&quot;</em>: &quot;0x3&quot;,<br>        <em>&quot;nonce&quot;</em>: &quot;0x2&quot;,<br>        <em>&quot;to&quot;</em>: &quot;cx4e739b203b92498b6b6fb6d205f1cb62a6d4f88d&quot;,<br>        <em>&quot;dataType&quot;</em>: &quot;call&quot;,<br>            <em>&quot;data&quot;</em>: {<br>                <em>&quot;method&quot;</em>: &quot;vote&quot;,<br>                <em>&quot;params&quot;</em>: {<br>                    <em>&quot;_vote&quot;</em>: &quot;0x1&quot;<br>                }<br>            }<br>    },<br>    <em>&quot;id&quot;</em>: 1<br>}</pre><p>execute it,</p><pre>$ tbears sendtx -k keystores/keystore1.json testcmdline/send.json -u <a href="https://bicon.net.solidwallet.io/api/v3">https://bicon.net.solidwallet.io/api/v3</a></pre><p>then check the txresult,</p><pre>$ tbears txresult 0xad6e8058a8f992f6b7312848853437c9639280e436e5391dd6254d8593d637ec -u <a href="https://bicon.net.solidwallet.io/api/v3">https://bicon.net.solidwallet.io/api/v3</a></pre><p>Visit our webpage <a href="http://localhost:5000/">http://localhost:5000</a> again, you should see wallet1 voted yes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cK84Xn_y_mpqVXB_-vhOg.png" /></figure><p>You cannot repeat votes from the same wallet, for wallets that haven’t voted (iconkeystore3, iconkeystore4), you can vote via JSON RPC like we did for wallet1, or you can simply vote through the webapp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*4TDJqhJKt_FcxW7HtK1AWg.png" /></figure><p>You can also check the tally results from T-Bears by calling our get_vote_talley from SCORE.</p><pre># testcmdline/call.json<br>{<br>  <em>&quot;jsonrpc&quot;</em>: &quot;2.0&quot;,<br>  <em>&quot;method&quot;</em>: &quot;icx_call&quot;,<br>  <em>&quot;params&quot;</em>: {<br>    <em>&quot;from&quot;</em>: &quot;hxe9d75191906ccc604fc1e45a9f3c59fb856c215f&quot;,<br>    <em>&quot;to&quot;</em>: &quot;cx4e739b203b92498b6b6fb6d205f1cb62a6d4f88d&quot;,<br>    <em>&quot;dataType&quot;</em>: &quot;call&quot;,<br>    <em>&quot;data&quot;</em>: {<br>      <em>&quot;method&quot;</em>: &quot;get_vote_talley&quot;<br>    }<br>  },<br>  <em>&quot;id&quot;</em>: 1<br>}</pre><p>Execute,</p><pre>$ tbears call testcmdline/call.json -u <a href="https://bicon.net.solidwallet.io/api/v3">https://bicon.net.solidwallet.io/api/v3</a></pre><p>you should see the same result</p><pre>response : {<br>    &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>    &quot;result&quot;: {<br>        &quot;yes&quot;: &quot;0x2&quot;,<br>        &quot;no&quot;: &quot;0x1&quot;<br>    },<br>    &quot;id&quot;: 1<br>}</pre><h4><strong>Web App</strong></h4><p>The main.py has some unused and irrelevant code, don’t worry about those. The main flow is basically getAllVotesIcon from polling-script.js, which routes to result/&lt;wallet&gt; calling votingResults on our main.py then draw the chart. The main function vote in our webapp would create a signed transaction and call our SCORE’s vote method to cast the vote.</p><p>Optionally you can deploy the app to a production server, follow the steps from the <a href="https://medium.com/@2infiniti/icon-dapp-from-a-z-part-3-icon-dice-roll-dapp-7f0ca72057f5">previous tutorial</a></p><p><strong>Demo: </strong><a href="https://dapps.icon.support/icon-polling"><strong>https://dapps.icon.support/icon-polling</strong></a></p><p>That’s it for this voting DAPP, this demonstrates another great use case for blockchain decentralized applications. Paper ballots have been used in voting since the Roman Empire and results are counted by hand till this day. Online voting in a centralized application has a few fundamental flaws that are usually overcome by higher security standards, but votes stored in a centralized database can be breached and altered. Application code can also change, meaning election rules can change. Blockchains enhance voting integrity with secure transactions and traceability, so every vote can be vetted and records are permanent, transparent and immutable. It’s time to evolve.</p><p>Follow me on Twitter for most up-to-date ICON related content: <a href="https://www.twitter.com/2infiniti">https://www.twitter.com/2infiniti</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9581b1238d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>