<?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 Primoz Kocevar on Medium]]></title>
        <description><![CDATA[Stories by Primoz Kocevar on Medium]]></description>
        <link>https://medium.com/@primozkocevar?source=rss-874682c0be50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*93xb2aGaWtvWvuGoqOFomw@2x.jpeg</url>
            <title>Stories by Primoz Kocevar on Medium</title>
            <link>https://medium.com/@primozkocevar?source=rss-874682c0be50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:24:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@primozkocevar/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[How to provide secrets to a container at build time.]]></title>
            <link>https://faun.pub/how-to-provide-secrets-to-a-container-at-build-time-ff5267134bbd?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff5267134bbd</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Sat, 13 Jul 2019 22:19:34 GMT</pubDate>
            <atom:updated>2019-07-15T14:00:41.506Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide for using environment variables to provide secrets to a Docker container in a GitLab runner to deploy to Kubernetes.</h4><p>This quick guide provides insight into providing production secret variables to a Docker container containing production code. This procedure is automated in the GitLab runner that contains the secrets in the environment variables and deploys the container to a Kubernetes cluster. However, the deploying part of the solution is omitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VpSr1u0c9gwpp3z7" /><figcaption>Photo by <a href="https://unsplash.com/@tinaflour?utm_source=medium&amp;utm_medium=referral">Kristina Flour</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the example used for this article, <strong>Django </strong>is used as a web framework. Using an environment variable as a secret in the settings.py can be done like:</p><pre>import os<br>...<br>SECRET_SETTING = os.environ[&quot;SECRET_ENV_VAR&quot;]</pre><p>For this setup to work, the environment variable must be set beforehand. If using <strong>bash </strong>this is done like:</p><pre>export SECRET_ENV_VAR=&lt;secret_value&gt;</pre><p>However, the used deployment architecture is using <strong>Docker </strong>containers to start a production environment and therefore the environment variable must be defined in a Dockerfile used to build the image.</p><p><strong>ARG </strong>and <strong>ENV </strong>keywords are considered for that use-case in a Dockerfile. It is important to understand that ARG provides environment variables that are accessible at the time when a container is built but are not available when the container is used after. And ENV provides quite the opposite and provides environment variables after when the built container is used.</p><p>As we are using the container to run migrations during the build stage and to run the server later in the Kubernetes, both keywords should be used as recommended <a href="https://vsupalov.com/docker-build-time-env-values/">here</a>. First, an ARG keyword is used to define the variable at build time and later the value of the ARG variable is passed to the ENV variable so that it can also be accessed after when a container is run. An example of the Dockerfile that uses secret variables and :</p><pre><strong>ARG </strong>SECRET_ENV_VAR_BUILD<br><strong>ENV </strong>SECRET_ENV_VAR=$SECRET_ENV_VAR_BUILD</pre><p>If an ARG is defined in a Dockerfile, a default value can be provided. However, for our use case we want to set the value when building and pass the ARG values when building using the <em>— </em><strong><em>build-arg</em> </strong>flag. Example of providing ARG values while building a Dockerfile:</p><pre>docker build <strong>--build-arg</strong> SECRET_ENV_VAR_BUILD=$SECRET_ENV_VAR -t registry/name:tag .</pre><p>When running it in a GitLAb runner this is just one step in the deployment pipeline and is run on a runner. The implementation provided here uses an environment variable of the GitLab runner to get the secret like <strong>$<em>SECRET_ENV_VAR</em></strong>. That means this variable should be set in the GitLab control panel to be accessed by the runner. It can be set here by the maintainers of the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*sqB8YnykCwWLQF5HTh0VyA.png" /><figcaption>CI/CD tab in the GitLab project settings is used to set environment variables.</figcaption></figure><p>The examples in this article only use one secret variable which is really unrealistic. In reality, there are a couple of secret variables for different components like databases, email server passwords …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qu4sKRwluA5mmpkFXAOoxg.png" /><figcaption>Path of the secrets during the build and deployment process.</figcaption></figure><p>If everything is set up correctly with the deployment pipeline and Kubernetes as well, the source code should not contain any secret variables as those are added when building the project in the GitLab project. This usually presents a more secure implementation as the attack surface of the architecture shrinks considerably if the code can be compromised.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff5267134bbd" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/how-to-provide-secrets-to-a-container-at-build-time-ff5267134bbd">How to provide secrets to a container at build time.</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What really is DevOps?]]></title>
            <link>https://faun.pub/what-really-is-devops-87b8a21019d4?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/87b8a21019d4</guid>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[animals]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 23:26:06 GMT</pubDate>
            <atom:updated>2019-06-25T23:26:23.153Z</atom:updated>
            <content:encoded><![CDATA[<h4>A definition of DevOps with examples, from the perspective of feedback loops.</h4><p>This article talks about the <strong>magic </strong>of DevOps, what it represents and what benefits it brings. Every organization usually has its own definition of DevOps. That is why I try to present it as a general definition with <strong>examples </strong>so that even us ordinary people can finally understand what it means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rWxDJjaOAXXZXLDJ" /><figcaption>Photo by <a href="https://unsplash.com/@javier_virues_ortega?utm_source=medium&amp;utm_medium=referral">Javier Virues-Ortega</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some people define DevOps as a cultural movement, others as a set of tools. I think it both at the same time. However, I would put more importance on culture, as it can make systems work really effectively, even without the latest tools.</p><p>Let us switch the context a little and think about animals. Animals right? Why am I reading this? … Stay with me.</p><p>Imagine a tiger, yeah just like the one in the picture. When a tiger is very hungry he is really focused and senses every change in his environment to achieve his goal of getting food. When he senses that there are other animals in his vicinity that he could eat, he can very quickly respond to that information and act on it. He can start hunting very quickly and catch that poor zebra. If his feedback loops are fast and he can act on the change quickly, he can be a very successful hunter, which will benefit his whole family of tigers. For the zebra that is not such good news, unfortunately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vshxlbf0QEjx4vbD" /><figcaption>Photo by <a href="https://unsplash.com/@imedianamibia?utm_source=medium&amp;utm_medium=referral">Alan J. Hendry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Feedback loops, generally, are very important in life and different systems as they define flexibility. How flexible a system can be, is usually very correlated to long-term success. If we think of a business that can not adapt quickly to change like for example Kodak did not adapt to the mainstream use of digital cameras and therefore deteriorated from a very successful business to a failing one.</p><p>If you can make your system (usually an architecture of code, infrastructure and/or services) be very responsive to the environment (users needs, bugs, market changes…) and to the changing internal properties of the system (inclusion of new technologies, changes of architecture…), the system can be very successful and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWM40rkmjtc0nTMU3Af2SQ.png" /><figcaption>A comparison of two different systems and their feedback loops.</figcaption></figure><p>I think about DevOps from a perspective of feedback loops. If you can implement fast feedback loops in your system, as described, it will bring a lot of business and technological benefits to your organization.</p><p>If you read my thoughts, I congratulate you. I have probably disappointed you, no technical description was really provided, but this is a perspective I want you to think about. I will provide a more technical and detailed description in a later article that will work with this perspective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87b8a21019d4" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/what-really-is-devops-87b8a21019d4">What really is DevOps?</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Static Upload to AWS S3 using GitLab Runners]]></title>
            <link>https://faun.pub/continuous-static-upload-to-aws-s3-using-gitlab-runners-17f0260a5af2?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f0260a5af2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 23:42:05 GMT</pubDate>
            <atom:updated>2019-07-19T17:35:12.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial using GitLab Runners to sync static files served on S3 at each commit to production branch.</h4><p>Uploading static files at each deployment (to the <strong>production</strong> branch) automatically, comes quite useful when dealing with static files being served using AWS S3. The files need <strong>public</strong> <strong>read</strong> permission for the serving to work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_j7mjJbcfNz1AevW" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks.org</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The final version of .<strong>gitlab-ci.yml</strong> that defines the deployment procedure looks like this and will be explained in this post.</p><pre><strong>static push job</strong>:<br>  <strong>stage</strong>: static_push<br>  <strong>tags</strong>:<br>    - python<br>  <strong>script</strong>:<br>    - echo &quot;Pushing the static files&quot;<br>    - mkdir ~/.aws/<br>    - touch ~/.aws/credentials<br>    - pip install awscli<br>    - printf &quot;[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\n&quot; &quot;$AWS_ACCESS_KEY_ID&quot; &quot;$AWS_SECRET_ACCESS_KEY&quot; &gt;&gt; ~/.aws/credentials<br>    - aws s3 sync static/ s3://zeleniplanet-static-s3-bucket/static/ --acl public-read<br>  <strong>only</strong>:<br>    - production</pre><p>Firstly it is important to have a version of GitLab runner available that has python preinstalled. For the <a href="https://docs.gitlab.com/runner/executors/README.html"><strong>executor</strong></a> on the runner, I choose Docker with a python alpine image (<strong>alpine:latest</strong>). As is presented in the official documentation:</p><p><a href="https://docs.gitlab.com/runner/register/">Registering runners | GitLab</a></p><p>Also, we must make sure to set a <a href="https://docs.gitlab.com/ce/ci/yaml/README.html#tags"><strong>tag</strong></a><strong> </strong>on the runner that describes the environment which is in our case <strong>python. </strong>We will specify this tag than in the .<strong>gitlab-ci.yml </strong>to define that a python runner must be used for this part of the deployment and thus <a href="https://gitlab.com/gitlab-org/gitlab-runner/issues/2503">separate</a> it from the rest of the deployment strategy that is in this case done on a Docker inside of Docker runner with a docker tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*WftyZ8gS5VGA3MWv22PEXg.png" /><figcaption>Runners set up in the GitLab console. An additional runner</figcaption></figure><p>Python environment is needed so that the <strong>pip</strong> command is going to work for installing the <strong>awscli </strong>as this is our next step. For this, we need to add this command to our deployment job specification in .<strong>gitlab-ci.yml.</strong></p><p>Now we have to provide the <strong>credentials</strong> for logging into awscli so we can access S3 bucket with static files. We save the credentials as <strong>environment</strong> <strong>variables</strong> in the GitLab console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2P9u2w4ZZ4e69k0-k-T7A.png" /></figure><p>Nextly there is the most important part of <strong>authenticating</strong> with awscli. This is done in the config by creating the ~/.<strong>aws/configure</strong> file and putting the credentials in using the two environment variables previously added by this command in the config:</p><pre>... <br><strong>- printf &quot;[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\n&quot; &quot;$AWS_ACCESS_KEY_ID&quot; &quot;$AWS_SECRET_ACCESS_KEY&quot; &gt;&gt; ~/.aws/credentials<br>...</strong></pre><p>At the end we can finally run the command itself to synchronize the folders and set the public-read permissions:</p><pre>...<br>- <strong>aws s3 sync static/ s3://your-bucket/static/ --acl public-read<br>...</strong></pre><p>When something is committed on the <strong>production</strong> branch we can see that the sync of the commited static folder and S3 bucket static folder is successful and the Job succeeded!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*Ycis9wwMLet00Ql_R-Ys0A.png" /><figcaption>The upload of static files to S3 bucket was successful</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f0260a5af2" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/continuous-static-upload-to-aws-s3-using-gitlab-runners-17f0260a5af2">Continuous Static Upload to AWS S3 using GitLab Runners</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLab CI/CD for Django on AWS.]]></title>
            <link>https://faun.pub/gitlab-ci-cd-for-django-on-aws-f0f009bf8eaf?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f009bf8eaf</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 22:07:22 GMT</pubDate>
            <atom:updated>2019-07-18T18:22:14.041Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setting up a local Gitlab repository on the same machine as a runner for deployment on AWS EB.</h4><p>A tutorial for a specific case of using Gitlab on Docker to set up a local Gitlab repository on an Ubuntu machine. This machine can also be used for CI/CD purposes by running a Gitlab Runner, which starts a local staging server running Django and deploys the project to AWS when specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QTX81cUI06xaT14L" /><figcaption>Photo by <a href="https://unsplash.com/@sarahleejs?utm_source=medium&amp;utm_medium=referral">Jongsun Lee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Setting up a GitLab repository</h3><p>To set up your own GitLab repository on Ubuntu there are a few options. You can install it locally or using a <strong>Docker</strong> image. We will do it using Docker as it is more structured and optimal.</p><h4>Installing Docker</h4><p>Firstly as already mentioned we must install Docker so we can run an image containing everything GitLab needs. If the command <em>docker</em> does not work please refer <a href="https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-using-the-repository">here</a> for more details on how to install Docker.</p><h4>Running a GitLab image</h4><p>As Docker is installed we must run the Docker image that contains everything a GitLab server needs to function. The following command worked for me:</p><pre>sudo docker run --detach --hostname <em>&lt;insert your ip&gt;</em><strong><em> --</em></strong>publish 443:443 --publish 80:80 --publish 23:23 --name gitlab --restart always --volume /srv/gitlab/config:/etc/gitlab --volume /srv/gitlab/logs:/var/log/gitlab --volume /srv/gitlab/data:/var/opt/gitlab gitlab/gitlab-ce:latest</pre><p>This sets up a GitLab Docker container that runs on a specified <strong>hostname</strong> and <strong>ports</strong>. It also <strong>restarts</strong> it when we reboot the machine. More details about the command can be found <a href="https://docs.gitlab.com/omnibus/docker/">here</a>.</p><p>With this command, you can check your running Docker containers and see if the GitLab image was correctly set up.</p><pre>docker ps</pre><p>Very important here is that all the <strong>parameters</strong> are <strong>set correctly</strong> and by understanding them as etc. an incorrectly set hostname can produce errors later with not finding the host.</p><h4><strong>Testing it</strong></h4><p>If everything is set up correctly we will find a version of GitLab on a specified IP inside the network that can access it. You should see a login page like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AV8Twlh6RJ6gjpRLAxA38w.png" /><figcaption>Example of a GitLab instance on a local IP.</figcaption></figure><p><strong>Congrats</strong>! Now you have your own GitLab instance!</p><p>Here you have to Register for a new account as this is separate from the official GitLab.com instance. If we would like to access this GitLab instance from outside the local network some port forwarding must be configured and preferably a static IP obtained and combined with a DNS service.</p><h3>Setting up Continous Integration and Continous Deployment</h3><p>GitLab is a great tool for version control, but lately, it also excels in DevOps tasks as CI/CD. It combines the two tasks in one platform and makes it easy to implement both.</p><h4><strong>Set up your own Runner</strong></h4><p>A GitLab Runner is a separate service usually ran on top of Docker Container that performs commands which are defined in a <strong><em>.gitlab-ci.yml </em></strong>file in your repository.</p><p>Let’s first mention that we do not have to set-up our own GitLab Runner for running tasks and can opt for a shared Runner which is done by default. However, this comes with a cost as you are not able to fully use it always and have to wait for others to finish using it or you can literally pay to use it.</p><p>How to <strong>install</strong> a runner on an Ubuntu machine is best described in the official <a href="https://docs.gitlab.com/runner/install/linux-manually.html"><strong>documentation</strong></a>.</p><p>After we have created a Runner we must <strong>register</strong> it for our GitLab project to use. This is again best described in the official <a href="https://docs.gitlab.com/runner/register/index.html"><strong>documentation</strong></a>. When following commands in the docs it is important to use a <strong>Docker</strong> executer as that is what we will use later for execution. When adding <strong>tags</strong> to the Runner make sure they are<strong> in sync</strong> with your projects tags as the worker might not work otherwise and it is best to not assign them at all in that case.</p><p>If Registration is successful we must firstly Disable Shared Runners for a specific Project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FD_-eRvech6iXpNDKm95DA.png" /><figcaption>You can find this under Settings / CI.CD / Runners for a specific project.</figcaption></figure><p>Now, if everything was successful, we can see a working Runner and enable it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*rDIjCvCH5g_Tlh86Y4f5Xg.png" /></figure><p>Congrats now you have a Runner to run your deployment scripts!</p><h4><strong><em>POSSIBLE PROBLEMS WITH DOCKER NOT CONNECTING</em></strong></h4><p>When I finished setting up runners I came across a problem where I get this error when trying to use docker-compose in a staging script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*oGn5clv8Bspc7gzTGhyUgQ.png" /><figcaption>Possible error with Docker not connecting even if installed before.</figcaption></figure><p>I checked and I already install docker-compose in one command before so it should work right? NO! The solution is in modifying <strong>config.toml</strong> file that configures Runners and I found the solution here:</p><p><a href="https://gitlab.com/gitlab-org/gitlab-runner/issues/1986#note_38545966">DinD - Cannot connect to the Docker daemon. Is the docker daemon running on this host? (#1986) · Issues · GitLab.org / gitlab-runner</a></p><h4><strong>Prepare project for CI/CD</strong></h4><p>Creating a <strong><em>.gitlab-ci.yml </em></strong>in your projects root directory is the next thing to do. This file is very important as it defines the behaviour of the project when new code gets pushed to it. How to set it up for a Python application (etc. Django) is described in the <a href="https://docs.gitlab.com/ee/ci/examples/test-and-deploy-python-application-to-heroku.html">documentation</a>. Also, we must take care of <strong><em>requirements.txt</em></strong> file as al the packages defined there get installed on our Runner every time.</p><p><a href="https://docs.gitlab.com/ee/ci/examples/test-and-deploy-python-application-to-heroku.html">Test and deploy a Python application with GitLab CI/CD</a></p><h4>Local staging server and AWS deployment</h4><p>My requirements were to have a<strong> local test server</strong> for testing a platform everytime new code gets pushed and deploying the code to AWS Elastic Beanstalk only when the code is pushed to a certain deploy branch. This was not described in official documentation so I had to adapt. Used deployment files that are needed by Docker and GitLab are contained in this repository:</p><p><a href="https://gitlab.com/primozkocevar/djangotoaws">Sign in</a></p><p>To achieve local staging server running <em>runserver </em>command simply on the <em>manage.py </em>file was more difficult than expected as a Runner is not meant to run a server. Thus we have to run Docker inside Docker Runner and we need some additional files describing this Container. This part was adapted using this <a href="http://matejgazda.com/02-crypto-dev-info-django-with-docker-and-gitlab-runner/#comment-5916">tutorial</a>.</p><p>Adding <strong><em>Dockerfile</em></strong><em> </em>to the project directory is the first step and describes how to set up a Docker Container and what ports to open for the server to work. The following code was used for my case:</p><pre>FROM python:3.5</pre><pre>RUN mkdir /spinnerStage<br>WORKDIR /spinnerStage<br>ADD . /spinnerStage</pre><pre>EXPOSE 8000</pre><pre>RUN pip install -r requirements.txt</pre><p>Now we need to define the commands that are run when composing a Docker container that will serve a Django server on port 8000. This is done by adding a file <strong><em>docker-compose.yml</em></strong> to the project directory. Example of mine:</p><pre>version: “2.2”<br>services:<br>db:<br>image: postgres<br>django:<br>build: .<br>restart: always<br>container_name: spinnerStage<br>command: python manage.py runserver 0.0.0.0:8000<br>ports:<br>- “8000:8000”<br>depends_on:<br>- db</pre><p>How Docker files and set-up work is nicely described <a href="https://docs.docker.com/compose/overview/">here</a> and an example of using Docker with python is available <a href="https://docs.docker.com/compose/gettingstarted/">here</a>.</p><p><strong>AWS deployment</strong></p><p>Firstly we need files for deploying to AWS that describe what to connect to. This is described <a href="https://medium.com/dowebthings/how-to-deploy-from-gitlab-to-elastic-beanstalk-aws-cdac7b701004">here</a> in 2., 3. and 4. step so that <em>eb deploy</em> command works on the Runner. Secret variables for deployment must be <strong>specifically</strong> provided to a runner by GitLab and set specifically for each project in Settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_aGXJxYjjzP1nGmzXk94Xw.png" /><figcaption>Setting Variables in Settings / CI/CD / Variables.</figcaption></figure><p>Finally, after setting things up it is very important to have the final <strong><em>.gitlab-ci.yml </em></strong>file correctly set as it defines most things. The final version of mine: stages:</p><pre>- staging<br>- deploy</pre><pre>staging:<br>stage: staging<br>script:<br>- echo “Deploying the app”<br>- pip install docker-compose<br>- docker-compose build<br>- docker-compose up -d</pre><pre>development:<br>type: deploy<br>script:<br>- mkdir ~/.aws/<br>- touch ~/.aws/credentials<br>- pip install -r deployReq.txt<br>- printf “[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\n” “$AWS_ACCESS_KEY_ID” “$AWS_SECRET_ACCESS_KEY” &gt;&gt; ~/.aws/credentials<br>- touch ~/.aws/config<br>- printf “[profile eb-cli]\nregion=ap-southeast-1\noutput=json” &gt;&gt; ~/.aws/config<br>- export PATH=~/.local/bin:$PATH<br>- eb deploy<br>only:<br>- deployed</pre><h3>Result</h3><p>A result of this configuration is that every push on the master branch gets compiled on a runner server in a Docker container which serves a Django server on port 8000 for testing. More importantly, when we are sure that our code is as bugless as possible, we can push the code to the branch named <strong>deployed</strong> and then the code gets deployed to AWS automatically.</p><p><em>Comment: This article is under construction and will improve with time thus corrections are welcome. For any questions contact the Author and refer to a file GitLab Insights.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Join our community Slack and read our weekly Faun topics ⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f009bf8eaf" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/gitlab-ci-cd-for-django-on-aws-f0f009bf8eaf">GitLab CI/CD for Django on AWS.</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Environment sensing using IoT]]></title>
            <link>https://medium.com/@primozkocevar/environment-sensing-using-iot-c291639cd50b?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c291639cd50b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Thu, 22 Nov 2018 12:24:59 GMT</pubDate>
            <atom:updated>2018-11-22T12:24:59.746Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>ESP8266 based IoT solution that collects data from different sensors and sends it wirelessly to the server on a PC.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLLnP_JWrgrhc4xTOOJzcw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/y9csmronT3s?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alberto Restifo</a> on <a href="https://unsplash.com/search/photos/environment?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p><strong>Context awareness</strong> is a term usually associated with mobile devices, but with our IoT solution, we can also provide context to other kinds of applications and <strong>machine learning</strong> problems. In this case, we shall be talking about the context from the environment or <strong>ambient</strong>.</p><h3>Resources</h3><p>First, we needed a source of information about the ambient that would bring us a context aware solution. For this we needed some sensors. We decided to use <strong>DHT22</strong> sensor for measuring temperature and humidity, <strong>BMP180</strong> sensor for measuring air pressure and a simple <strong>photoresistor</strong> for measuring the amount of light in the room.</p><p>For the client side we needed a microcontroller which would collect data from mentioned sensors and send it to the PC server. First we tried using one of the Arduino boards which seemed the best supported, but then we found a cheaper and better wireless solution in the form of <strong><em>ESP8266 NodeMCU 0.9. </em></strong>The I/O pins on the NodeMCU kit work on <strong>3.3V</strong>, which makes it compatible with our sensors. It contains 10 GPIO pins using Pulse Width Modulation (PMW) that can be configured to use <strong>I2C</strong> interface. It can also be programmed and flashed through micro <strong>USB</strong> just like an Arduino.</p><p>Our version of the development kit was designed to work with NodeMCU firmware which provides a <strong>Lua</strong> development and execution environment, but we were not going to use it since it is still in the early stages of development and lacks support. Instead we have been using it with the <strong><em>Arduino Integrated Development Environment (IDE)</em></strong><em>,</em> which is better supported and has plenty of <strong>libraries</strong> to choose from.</p><p>Server part of the solution runs on a PC in the <strong>same LAN</strong> with the help of a framework in Python called <em>Bottle</em>. <strong>Bottle</strong> is a lightweight Web Server Gateway Interface, which is distributed as a single file module and has no dependencies other than the Python Standard Library. For <strong>storing</strong> the data which is sent to our server, we decided to use <strong><em>MongoDB</em></strong> database with the help of the tools provided by <strong><em>PyMongo</em></strong><em>.</em></p><p>To see and <strong>analyze</strong> the stored data we now needed to pull the data out of the database and draw a <strong>graph</strong>. The tool we used for that is a Python library <strong><em>Pandas</em></strong><em>.</em></p><h3>Architecture</h3><p>First we started connecting the sensors to ESP8266 development kit through different interfaces and GPIO’s. Data pin from the temperature and humidity sensor DHT22 is connected to a <strong>digital input pin</strong> on a development kit, and with the combination of DHT22 Arduino library, which also controls the timing of the digital readings, we can get temperature and humidity readings every 2 seconds. The simplest <strong>one-wire communication</strong> is implemented in this case, therefore every additional sensor must be connected to a different pin. Photoresistor is connected to the <strong>single analog input </strong>on the development kit, and with measuring the voltage drop on the resistor, we can measure the amount of light in the room. The values returned from analog readings are between 0–1024, we only scale them down to 0–100% of light in the room, therefore we do not use any specific units. Sensor BMP108 has the most sophisticated communication with the development kit, as it uses <strong>I2C</strong> protocol. This protocol enables <strong>multiple</strong> <strong>devices</strong> connected to a single bus, which can be really useful if we have multiple sensors that use I2C and only two I2C-enabled pins. First we needed to connect SDA and SCL pins on BMP180 to two I2C enabled pins on our development platform (specifically D1 and D2). To implement I2C protocol, we used BMP180 library combined with the examples on how to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xCktR3VW-HWZ-TynM8yJg.png" /><figcaption>Architecture of the whole IoT solution</figcaption></figure><p>But only measuring the required data was not enough, we also needed to add a <strong>timestamp</strong>, when the measurement happened. Here we stumbled upon a small problem, either Arduino, or our ESP development kit, do not have an internal clock. Therefore, we should connect a Real Time Clock (<strong>RTC</strong>) Module to the I2C serial bus, and it would keep track of time even if there is no power. However, instead of adding another module to our board, we decided to get time from our server every time the module is reset, and save it as a <em>setSyncProvider(unixTime)</em> that runs the clock with the help of the function <em>millis().</em> We also set <em>setSyncInterval(syncInterval) </em>to regularly update the time we have set. Described functions that provide easy <strong>manipulation with time</strong> are a part of Arduino Time Library:</p><p><a href="https://github.com/primozkocevar/Rtc">primozkocevar/Rtc</a></p><p>The foundation for getting time from the server and then sending measured data to it is communication based on <strong>HTTP</strong> protocol. Specifically, we use GET requests to send a request for time and also measured data packed in the Uniform Resource Identifier (URI).</p><p>Creating URI is the most important thing that contains all of the information relevant to the server. In order to get time from the server, we need to send the URI that contains ”/getDateTime”. But every few seconds we want to send the measurement data, the timestamp and the device ID to the server, in which case we create a <strong>URI</strong> like this:</p><pre>”<em>/</em><strong><em>data</em></strong><em>?</em><strong><em>temperature</em></strong><em>=”+String(t)+”&amp;</em><strong><em>humidity</em></strong><em>=”+String(h)+”&amp;</em><strong><em>light</em></strong><em>=”+String(l)+”&amp;</em><strong><em>pressure</em></strong><em>=”+String(p)+”&amp;</em><strong><em>deviceid</em></strong><em>=”+device+”&amp;</em><strong><em>time</em></strong><em>=”+String(sendingTime);</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*j3kmUyoe3u_KJYZm7XRJkQ.png" /><figcaption>Communication diagram between our client ESP8266 and a laptop server running bottle.</figcaption></figure><p>On the server side, running bottle in a Python script, we are expecting two different URI’s. If the server gets a “/getDateTime” URI request, it sends back a response containing time in unix format.</p><p>But if it gets a request on URI “/data”, then it takes the containing information about the measurements out of the whole URI and saves them in a <strong>JSON-style </strong>document e.g.:</p><pre><em>{“ Temperature”:</em> <em>request.query.temperature,</em></pre><pre>“<em>Humidity”: request.query.humidity , …}</em></pre><p>If MongoDB is already running, we now only need to select a <strong>database</strong> and a collection in which we want to save our document and then save it with PyMongo :</p><pre><em>collection.insert_one(document)</em></pre><p>Analysis and plotting of our data is done in a different Python script, and also works with the help of PyMongo and a Python <strong>plotting</strong> and <strong>analysis</strong> library <strong>Pandas</strong>. First we load a MongoDB collection into a list which we need to create a Pandas structure <strong>DataFrame</strong>.</p><p>When we have our data stored in a DataFrame as a string, we can easily convert it to numeric or datetime format, so that we can analyze and plot it:</p><pre><em>data.describe() </em>and<em> plt.plot(data.Temperature)</em></pre><h3>Results</h3><p>On this graph it can be seen that some useful data can be extracted about the state of environment. We could use this data in machine learning, with the combination of other parameters, trying to predict different states of the user in a room or a different environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*d5SiFNCtdxfJPcsomLv2Jg.png" /><figcaption>Data gathered in approximately 12 hours, with a sampling frequency of 30 seconds</figcaption></figure><p>Thanks goes to my mentor on this project Marko Meža.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c291639cd50b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3-Wire SPI Library implementation]]></title>
            <link>https://medium.com/@primozkocevar/3-wire-spi-library-implementation-c6f480a341ef?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6f480a341ef</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 16:28:06 GMT</pubDate>
            <atom:updated>2018-11-29T14:54:20.804Z</atom:updated>
            <content:encoded><![CDATA[<h4>Contelec Vert-X 13 encoders communicate via 3-wire SPI library implementation of which is described here.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d2-wUb0HVvFIykkP" /><figcaption>Photo by <a href="https://unsplash.com/@argtone?utm_source=medium&amp;utm_medium=referral">Alex Dukhanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Communication with <strong>Contelec Vert-X 13</strong> encoders is done by a special 3-wire Serial Peripheral Interface Bus (SPI). This interface is different from a classic SPI interface, such that it only has <strong>ONE Data</strong> line for communication between master and slaves which makes this a <strong>half-duplex</strong> communication.</p><p>As observed from the datasheet and the reading from the oscilloscope, data in this communication is captured on the falling edge (<strong>CPOL=0</strong>) and SCLK line is LOW when idle and HIGH when active (<strong>CPHA=1</strong>). A combination of these two parameters defines a <strong>SPI_MODE1</strong> way of communication. Another important fact for communication is that data bits from the slave are sent Most Significant Bit (<strong>MSB</strong>) first. All of these parameters are necessary for making an SPI connection work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*8ZCvmRVYO-cpPV1p4zAyuw.png" /><figcaption>3-wire SPI communication procedure.</figcaption></figure><p>In the case of a <strong>3-wire SPI</strong> communication used by Contelec encoders, setting up a working communication is a <strong>bigger challenge</strong> than expected. There are <strong>no</strong> already developed libraries working with this kind of sensors through this odd interface. Therefore a custom 3-wire, half-duplex SPI library had to be developed which produced a lot of headaches as the documentation is really basic. The library is written in <strong>C++</strong> using registers of pins to set the states and delays to time the communication correctly. A working implementation of this library is presented in this repository:</p><p><a href="https://github.com/primozkocevar/3WireSPI-ContelecVertX">primozkocevar/3WireSPI-ContelecVertX</a></p><p>All of this development had to be debugged with an oscilloscope until it finally worked as shown in an oscilloscope recording figure. Observing the yellow data line, in the first part <strong>synchronizing</strong> bits sent from the Master to the Slave can be seen. Alternating bits present 0xAA and constant HIGH presents 0xFF in hexadecimal format. In the second part, the actual data bits are sent from the Slave, which has Slave Select line set to LOW, to the Master where they are then decoded into degrees by C++ code. The speed of this communication is set by the clock line in pink.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TXcfHnegk_gMD2CC8zk9xw.png" /><figcaption>Timeline of a working 3-wire SPI connection. Yellow — data, green — slave select, pink — clock</figcaption></figure><p>Applying this custom written library to a single master and single slave architecture worked perfectly. However, after testing it with <strong>multiple</strong> slaves some problems arose as communication started <strong>failing</strong> when adding another slave. This issue took some time to figure out as a problem was searched for in the code, but was actually in the hardware. When a multiple slave architecture was implemented as shown in the circuit scheme everything worked <strong>perfectly</strong> without any change to the code. A crucial change in the implementation was <strong>removing the pull-up resistors</strong> indicated by red crosses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*UCILFduxAGd08eR7H3TGoA.png" /><figcaption>Implemented circuit for 3-wire SPI communication. Some pull-up resistors are removed from the datasheet implementation for multiple slaves communication.</figcaption></figure><p>Special thanks to my supervisor Quentin Leboutet on provided help with this project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6f480a341ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forwarder contract for Ether and ERC-20 tokens]]></title>
            <link>https://medium.com/valus/forwarder-contract-for-ether-and-erc-20-tokens-e257a621889d?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/e257a621889d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[exchange]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 12:26:46 GMT</pubDate>
            <atom:updated>2018-11-23T21:26:17.967Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generating address contracts for each user to transfer their Ether and ERC-20 tokens to one main wallet.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*HZjnfARjLLwGPYdgJZEZJw.png" /></figure><p>The final solution is presented in this GitHub repository:</p><p><a href="https://github.com/primozkocevar/SigWallet-ERC20">primozkocevar/SigWallet-ERC20</a></p><h3>Reformatting a different solution</h3><p>For this task code from this git repository was used and <strong>reformated</strong>:</p><p><a href="https://github.com/BitGo/eth-multisig-v2">BitGo/eth-multisig-v2</a></p><p>However already when just trying to call a <em>createForwarder()</em> function of a deployed <strong>WalletSimple</strong> contract there was a problem. A call to the contract was made by signing it locally like so:</p><pre>walletContract = web3.eth.contract(address=&quot;0xE81ab8f77a3Bbf2d19088D1d941270A2E3160825&quot;, abi=WalletSimple.ABI)<br><br>nonce = web3.eth.getTransactionCount(mainAccount.address)<br><br>tx = walletContract.buildTransaction({  <br>    &#39;from&#39;: mainAccount.address,<br>    &#39;gasPrice&#39;: web3.toWei(&#39;14&#39;, &#39;gwei&#39;),<br>    &#39;gas&#39;: 900000,<br>    &#39;nonce&#39;: nonce}).<strong>createForwarder</strong>()<br>signed = web3.eth.account.<strong>signTransaction</strong>(tx)<br>transaction_address = web3.eth.<strong>sendRawTransaction</strong>(signed.rawTransaction)<br>txReceipt = web3.eth.waitForTransactionReceipt(transaction_address)</pre><p>However after the transaction was processed the <em>txReceipt</em> did <strong>not</strong> contain an <strong>address</strong> of a produced forwarder, which is a <strong>crucial</strong> piece of information for sending funds. Although this was required in the <strong>solidity</strong> <strong>constructor</strong> of the <strong>WalletSimple</strong> contract like:</p><pre><strong>constructor</strong>() public returns (address) {<br> return new Forwarder();<br> }</pre><p>The reason this function did not return an address as specified is that this address is probably <strong>yet not</strong> <strong>defined</strong> the moment a constructor is called and thus can not be returned as the <strong>real</strong> network needs some time for this to process (this is probably why it <strong>worked</strong> testing on a <strong>local</strong> network).</p><h3>Let us fix it</h3><p>Thus a simple and quick fix was applied that admittedly consumes some additional gas. Adding <strong>two</strong> additional <strong>global</strong> <strong>variables</strong> was implemented.</p><p>A global variable is defined as soon as the constructor of Forwarder.sol is called so it is <strong>aware</strong> of its own address.</p><pre><strong>forwarderAddress</strong> = address(this);</pre><p>This one is the <strong><em>forwarderAddress</em></strong> in the Forwarder.sol contract itself and it is necessary so that it could be called from the WalletSimple contract to set it as a second global variable <strong><em>latestForwarder</em></strong> like so:</p><pre>Forwarder f = new Forwarder();<br> <strong>latestFowarder</strong> = f.forwarderAddress();</pre><p>Needless to say, these two global variables automatically get <strong>getters</strong> defined in Solidity so they can be called and their value is <strong>publicly</strong> <strong>accessible </strong>on the Ethereum main net.</p><p>Adding an additional line to the <strong>web3.py</strong> part when calling <strong>WalletSimple</strong> is crucial:</p><pre>walletContract = web3.eth.contract(address=&quot;0xE81ab8f77a3Bbf2d19088D1d941270A2E3160825&quot;, abi=WalletSimple.ABI)<br><br>nonce = web3.eth.getTransactionCount(mainAccount.address)<br><br>tx = walletContract.buildTransaction({  <br>    &#39;from&#39;: mainAccount.address,<br>    &#39;gasPrice&#39;: web3.toWei(&#39;14&#39;, &#39;gwei&#39;),<br>    &#39;gas&#39;: 900000,<br>    &#39;nonce&#39;: nonce}).createForwarder()<br>signed = web3.eth.account.signTransaction(tx)<br>transaction_address = web3.eth.sendRawTransaction(signed.rawTransaction)<br><strong>forwarderAddress = walletContract.functions.latestFowarder().call()</strong><br>txReceipt = web3.eth.waitForTransactionReceipt(transaction_address)</pre><p>Explanation: <em>we could not get the address through the constructor as on the real network an address of the deployed contract is not yet available at the same moment as constructor is called but a bit later, so that we have to get it via a global public variable of walletSimple contract named latestForwarder (a getter for this variable is simply called with () as any other function!</em></p><h4>EFFICIENCY?</h4><p>This approach is maybe not optimal as it consumes extra gas and the <em>latestForwarder</em> variable can be sensitive to multiple addresses calling it at once and could bring some <strong>unpredicted</strong> behaviour. Thus an approach mentioned in the <strong>documentation</strong> is also to be considered to more thoroughly refurbish mentioned contracts to return a correct address after the constructor:</p><p><a href="https://solidity.readthedocs.io/en/v0.4.24/contracts.html#creating-contracts">Contracts - Solidity 0.4.24 documentation</a></p><p>However, this approach <strong>did</strong> <strong>not</strong> <strong>work</strong> for us, thus the first recommended approach was still a good call we decided as we call fowarderAddress getter <strong>immediately</strong> after receiving a receipt so it should always get the right address as we also do it in sequence one after the other and thus it should always <strong>work</strong>!</p><p><strong>IMPROVEMENTS</strong></p><p>However, the first approach could still be improved by using an array of addresses for saving all the forwarder addresses in the contract but this would probably be too expensive with gas. However, we could always read all of the created forwarders and export all the unused ones! An even better would be to send the new forwarder address using events and catch in on the server, however according to previous experiences with<strong> EVENTS, which are horribly unpredictable,</strong> especially using <strong>INFURA</strong>, this would be recommended at a <strong>later</strong> <strong>stage</strong>, and all the created forwarders could change their parent addresses using the newly implemented function <strong>changeParent()</strong>.</p><h4>On data formatting</h4><p>It is crucial that inputting data is done using <strong>bytes32</strong> format. Oddly enough the format must be in <strong>HEX</strong> and <strong>not in bytes</strong> (as the name would suggest) :</p><p><a href="https://ethereum.stackexchange.com/questions/48092/solidity-error-when-encoding-arguments-to-call-a-function-with-bytes32-type-para">Solidity error when encoding arguments to call a function with Bytes32 Type Parameters</a></p><p>Therefore before inputting a string to a <strong>bytes32</strong> variable in solidity contract, a <strong>conversion</strong> like this must be done:</p><pre><strong>bytesVariable = Web3.toHex(string)</strong></pre><p>Why use <strong>bytes over strings</strong>:</p><p><a href="https://ethereum.stackexchange.com/questions/11556/use-string-type-or-bytes32">Use string type or bytes32?</a></p><h3>FINAL SOLUTION</h3><p>For the final solution, <strong>events</strong> were used as a means of transferring created forwarder address to the caller of this action. It was somehow a lucky strike as it was obvious that a receipt of a createForwarder() includes some logs that include event logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*59sM6Z0AZoEsypBEw5tFyA.png" /><figcaption>an example of createForwarder() receipt in Remix that includes event logs in logs.</figcaption></figure><p><em>COMMENTS:</em></p><p><em>Here it must be said that in Remix if we only import WalletSimple contract as address without ABI the logs are empty when calling createForwarder(). This means that it is crucial to supply the </em><strong><em>correct</em></strong><em> </em><strong><em>ABI</em></strong><em> </em><strong><em>in</em></strong><em> </em><strong><em>web3.py</em></strong><em> so that we know events were called when calling createForwarder() and can thus get a return from it!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*bju8pVEFbY_0K6sNBCu7Sg.png" /><figcaption>Calling createForwarder() <strong>without</strong> returned logs as it was imported as an address. (probably no ABI supplied)</figcaption></figure><p>The event about generating forwarders was <strong>emitted</strong> in solidity in a contract like:</p><pre>function createForwarder() public payable returns (address) {<br> Forwarder f = new Forwarder();<br> <strong>emit ForwarderCreated(address(f));</strong><br> }</pre><p>Reading this using python:</p><pre><strong>txReceipt</strong> = web3.eth.waitForTransactionReceipt(transaction_address, timeout=3000)<br># get forwarder address from event logs!<br>data = <strong>txReceipt[&quot;logs&quot;][0][&quot;data&quot;]</strong><br>fAddr = <strong>&quot;0x&quot; + data[26:66]</strong><br>forwarderAddress = <strong>to_checksum_address(fAddr)</strong></pre><p>Additionally added an <strong>event</strong> for <strong>flushing</strong> <strong>tokens</strong> for future work so that we can follow flushing through events!</p><p>In the end, the whole contract was <strong>rewritten</strong> using the <strong>latest</strong> <strong>recommendations</strong> like in the solidity documentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e257a621889d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/valus/forwarder-contract-for-ether-and-erc-20-tokens-e257a621889d">Forwarder contract for Ether and ERC-20 tokens</a> was originally published in <a href="https://medium.com/valus">VALUS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging Events on Ethereum]]></title>
            <link>https://medium.com/valus/logging-events-on-ethereum-755cd46bfe94?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/755cd46bfe94</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Mon, 12 Nov 2018 16:08:59 GMT</pubDate>
            <atom:updated>2019-06-06T21:57:08.955Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick insight into dealing with Ethereum events for logging purposes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*eYLJm31X4RVxljLp7q1tyg.png" /></figure><h4>OVERVIEW</h4><p>When trying to look up some <strong>Ethereum</strong> <strong>Events</strong> using <strong>Web3.py</strong> for forwarding reasons I had some problems.</p><p>Why use <strong>events</strong> and how:</p><p><a href="https://media.consensys.net/technical-introduction-to-events-and-logs-in-ethereum-a074d65dd61e">Technical Introduction to Events and Logs in Ethereum</a></p><p>How to use Ethereum events with <strong>Python:</strong></p><p><a href="https://hackernoon.com/ethereum-smart-contracts-in-python-a-comprehensive-ish-guide-771b03990988">Ethereum Smart Contracts in Python: a comprehensive(ish) guide</a></p><p>For our use-case, this is kind of useless as it requires a TX receipt which we do not have in our case (or in any case when you <strong>don&#39;t save a TX receipt, </strong>which is in most cases).</p><h3><strong>USING INFURA AND WSS</strong></h3><p>As it turns out you can not use an Infura <strong>HTTP</strong> api if you would like to listen to events but you must use <strong>Websocket </strong>as a<strong> Web3 provider!!!</strong> A <strong>big help</strong> if you want to do it using <strong>INFURA</strong>:</p><p><a href="https://github.com/INFURA/infura/issues/73#issuecomment-365097830">Watching contract events with Infura · Issue #73 · INFURA/infura</a></p><p>Also Infura documentation for <strong>EVENTS</strong>, <strong>HELPFUL</strong>:</p><p><a href="https://infura.io/docs/wss/introduction">Infura - Scalable Blockchain Infrastructure</a></p><h3><strong>FILTERING EVENTS</strong></h3><p>Filtering events proved to be more difficult than expected as the provided documentation is quite clumsy and there are a few helpful must-know tricks.</p><p>The official documentation here was bit unhelpful as it suggested to use <em>fromBlock=’latest’</em> and using <em>filter.get_new_enteries() :</em></p><p><a href="https://web3py.readthedocs.io/en/latest/filters.html?highlight=filters">Filtering - Web3.py 4.6.0 documentation</a></p><p>This did not return any useful events as we should have used <strong>get_all_enteries(). </strong>As helpfully suggested here:</p><p><a href="https://ethereum.stackexchange.com/questions/49687/python-3-how-to-make-event-filter-via-createfilter-web3-py-v4-2-1?rq=1">Python 3 How to make Event Filter via createFilter web3.py v4.2.1</a></p><p><strong>On Event Filters and how to use them:</strong></p><p><a href="https://ethereum.stackexchange.com/questions/36009/web3-py-eventfilter-get-new-entries-always-empty?noredirect=1&amp;lq=1">Web3.py EventFilter.get_new_entries() always empty</a></p><p>In this present time 4.9.2018 it is unreliable to depend on the <strong>get_new_entries()</strong> function as filters have a problem with deleting:</p><p><a href="https://github.com/ethereum/web3.py/issues/923">&quot;filter not found&quot; in Web3.py 4.2.0 · Issue #923 · ethereum/web3.py</a></p><p><strong>Thus it is best to not rely on it and lookup if deposits are new by yourself locally! (looking up block numbers, or maybe id’s …)</strong></p><p><strong>PROBLEM</strong> with <strong>web3.py</strong> and <strong>websockets</strong> providers for INFURA is described here:</p><p><a href="https://github.com/ethereum/web3.py/issues/1009">websocket provider not working · Issue #1009 · ethereum/web3.py</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755cd46bfe94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/valus/logging-events-on-ethereum-755cd46bfe94">Logging Events on Ethereum</a> was originally published in <a href="https://medium.com/valus">VALUS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invisible ReCaptcha Django]]></title>
            <link>https://medium.com/valus/invisible-recaptcha-django-ed06201161d5?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed06201161d5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 11:39:34 GMT</pubDate>
            <atom:updated>2018-11-23T21:39:05.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>Integrating a most user-friendly reCAPTCHA into your Django web platform.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*w1ORuN3k9TDQR07FBWPhfw.png" /></figure><p>There are some libraries for Django which you can use for this however, I prefer to do it by myself as it is more transparent and customizable (and in my case easier). To implement an invisible <strong>ReCaptcha </strong>by <strong>yourself </strong>using Django you start by using an official <strong>Google documentation</strong>:</p><p><a href="https://developers.google.com/recaptcha/docs/invisible">Invisible reCAPTCHA | Google for Developers</a></p><p>Here you have plenty of information on how to implement it on the <strong>front end</strong>. This means you only have to add a button with some crucial parameters like:</p><pre>&lt;button type=&quot;button&quot; <strong>data-sitekey</strong>=&quot;6LfKMG0UAAAAACdYaD7UE9dHIEsmmlmkL1SjE-AS&quot; <strong>data-callback</strong>=&quot;onClickResetPassValid&quot; class=&quot;<strong>g-recaptcha</strong> buttonColor anim&quot;&gt;Reset&lt;/button&gt;</pre><p>Then in the js function <em>onClickResetPassValid</em>() you can do the validation of the input data as this is called if the recaptcha is successful.</p><p>Next, we need to verify this request in the back-end before continuing using the usual code which uses a return field in the POST request named <strong>g-recaptcha-response</strong>:</p><pre>&#39;&#39;&#39; Begin reCAPTCHA validation &#39;&#39;&#39;<br>recaptcha_response = request.POST.get(&#39;g-recaptcha-response&#39;)<br>url = &#39;https://www.google.com/recaptcha/api/siteverify&#39;<br>values = {<br>    &#39;secret&#39;: settings.GOOGLE_RECAPTCHA_SECRET_KEY,<br>    &#39;response&#39;: recaptcha_response<br>}<br>data = urllib.parse.urlencode(values).encode()<br>req = urllib.request.Request(url, data=data)<br><br>response = urllib.request.urlopen(req)<br>result = json.loads(response.read().decode())<br>&#39;&#39;&#39; End reCAPTCHA validation &#39;&#39;&#39;<br>if result[&#39;success&#39;] == False:<br>    context = {&#39;recaptchaSuccess&#39;: False}<br>    return render(request, &#39;login/login.html&#39;, context)</pre><h4>PROBLEMS?</h4><p>Important to mention here is that if using validation in the front-end, there are some troubles and an approach mentioned in the first link (google documentation) should be used which is optimal. This approach would first validate the input data and after that use ReCaptcha validation.</p><p>However, we solved this problem differently as it suited our approach more. First, the reason for problems is that we need to <strong>reset </strong>the recaptcha after first calling the validation js function (e.g. onClickResetPassValid()) as the data-callback function can only be called once in the session if not reset. Therefore when we first call the validation function and possibly find a problem with data so that we do not submit the form, the button will not work for the second time (when we correct the data) as the recaptcha needs to be reset for the data-callback fuction to work again! This is done by using <strong><em>grecaptcha.reset() </em></strong>as mentioned here:</p><p><a href="https://groups.google.com/forum/#!topic/recaptcha/Y7xcoKhZ5OU">data-callback function not working in Invisible reCAPTCHA.</a></p><p>Calling <strong><em>grecaptcha.reset() </em></strong>should be implemented everytime the problem is detected in the js so that the ReCaptcha is reset and can work when the data is corrected. Example of this:</p><pre><strong>if </strong>(emailCond){<br>    $(&quot;#divCheckEmailLogin&quot;).slideUp(&quot;fast&quot;);<br>    $(&quot;#email&quot;).removeClass(&quot;inputWrongBorderRed&quot;);<br>}<br><strong>else </strong>{<br>    // reset recaptcha to try again!<br>    <strong>grecaptcha.reset();</strong><br>    $(&quot;#divCheckEmailLogin&quot;).slideDown(&quot;fast&quot;);<br>    $(&quot;#email&quot;).addClass(&quot;inputWrongBorderRed&quot;);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed06201161d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/valus/invisible-recaptcha-django-ed06201161d5">Invisible ReCaptcha Django</a> was originally published in <a href="https://medium.com/valus">VALUS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Ethereum Node]]></title>
            <link>https://medium.com/valus/aws-ethereum-node-c05266945b7e?source=rss-874682c0be50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c05266945b7e</guid>
            <category><![CDATA[distributed-ledgers]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Primoz Kocevar]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 11:32:03 GMT</pubDate>
            <atom:updated>2018-11-23T21:27:23.966Z</atom:updated>
            <content:encoded><![CDATA[<h4>My experiences and hacks dealing with setting up an Ethereum Blockchain on AWS instance.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*Alx4_-Pn0804yiuOUp7Tew.png" /></figure><h4>FIRST ATTEMPT</h4><p>One of my first attempts to achieve a full Ethereum node was using this code from AWS marketplace: <a href="https://aws.amazon.com/marketplace/pp/B073VZM29M">https://aws.amazon.com/marketplace/pp/B073VZM29M</a></p><p>However, after some time, I figured that this setup was set to create private nets and I wanted a full public node. I made the interface available to external communication by changing the setting in Ethereum.sh from <strong>-rpcaddr 127.0.0.1</strong> to <strong>0.0.0.0 </strong>and also changing the security settings in AWS console to let in ingoing traffic on port 8545. However, as this was not very useful to me at the moment I accepted another approach to have as efficient as possible public node available.</p><h4>PARITY ATTEMPT</h4><p>As a first real attempt at manually setting up an Ethereum node on an AWS, I set up a micro EC2 instance. Then I installed Parity node on that instance as recommended here:</p><p><a href="https://medium.com/coinmonks/run-an-ethereum-node-on-aws-for-free-afca27f253ed">Run an Ethereum Node on AWS for Free</a></p><p>The instance also had quite a small amount of RAM and storage (30 GB) and probably because of these reasons the synchronization with the Ethereum main net was failing. After many attempts, the sync node was stuck at a random number and after a weekend of retries I gave up on the idea and looked for another approach.</p><h4>GETH FINAL SOLUTION</h4><p>The next logical step was trying a <strong>Geth</strong> node as is a standard for the Ethereum network. This was not a recommended way according to some developers that had better experiences with <strong>Parity </strong>as it is supposedly more <strong>storage efficient </strong>and <strong>faster</strong>. This time I did not want to make the same mistake and reserved a much stronger EC2 instance in AWS. The instance I choose was a <strong>large</strong> type and it has<strong> 200 GB</strong> of SSD storage. Here it must be considered that the same size of node could perform even better if Parity was used. This was done as recommended here:</p><p><a href="https://ethereum.stackexchange.com/questions/37120/best-possible-way-to-launch-the-ethereum-mainnet-node-on-aws">Best possible way to launch the ethereum mainnet node on AWS</a></p><p>Installation of <strong>Geth</strong> on the <strong>AWS</strong> <strong>EC2</strong> <strong>Ubuntu</strong> image instance:</p><p><a href="https://github.com/ethereum/go-ethereum/wiki/Installation-Instructions-for-Ubuntu">ethereum/go-ethereum</a></p><p>After some syncing attempts, It is important to go with the option when <strong>syncing to geth </strong>like:</p><pre>geth --syncmode=fast --cache=1024 --rpc --rpcaddr 0.0.0.0 --rpcport 3000</pre><p>This command is very important to get correct!</p><ul><li><em>SYNCMODE</em>: you can also use light or full options, but mostly fast is optimal</li><li><em>CACHE</em>: 1024 for faster synchronization! (if lots of RAM also 2048 is possible)</li><li><em>RPC </em>option must be enabled to have an RPC port open</li><li><em>RPCADDR </em>must be set to 0.0.0.0 so that it is accessible from outside!(or an IP on which the node lives)</li><li><em>RPCPORT </em>is usually 8545 as this is a default for geth nodes used for RPC calls. I use port 3000 for security from bots that try the 8545 port systematically!</li></ul><p>The syncing of the Ethereum network can be stuck at the end like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*TfWc5v06Vm1eUAQOtAgbFA.png" /></figure><p>However, this is explained:</p><p><a href="https://github.com/ethereum/go-ethereum/issues/16796">Geth node sync always behind · Issue #16796 · ethereum/go-ethereum</a></p><p>Some other options to run geth described here:</p><p><a href="https://github.com/ethereum/go-ethereum/issues/14536">Unable to attach to the local running geth node · Issue #14536 · ethereum/go-ethereum</a></p><p><strong>Testing the node:</strong></p><ul><li><a href="https://ethereum.stackexchange.com/questions/46841/what-is-context-deadline-exceeded">what is context deadline exceeded?</a></li><li><a href="https://ethereum.stackexchange.com/questions/809/which-tcp-and-udp-ports-are-required-to-run-an-ethereum-client">Which TCP and UDP ports are required to run an Ethereum client?</a></li></ul><p><strong>Attaching to Ropsten node:</strong></p><p>Attaching to ropsten via IPC connection is not as simple as main net (as it uses a different folder) so use the next instructions or just connect to an HTTP <strong>RPC</strong> which is the same for ropsten as is for mainnet:</p><p><a href="https://ethereum.stackexchange.com/questions/11248/how-to-call-geth-attach-on-testnet-better-than-writing-full-path">How to call &quot;geth attach&quot; on --testnet better than writing full path?</a></p><p><strong>Useful stuff:</strong></p><p><a href="https://github.com/ethereum/go-ethereum/issues/16353">connection refused to Geth websocket / RPC ports · Issue #16353 · ethereum/go-ethereum</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c05266945b7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/valus/aws-ethereum-node-c05266945b7e">AWS Ethereum Node</a> was originally published in <a href="https://medium.com/valus">VALUS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>