<?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 Jakub Dziworski on Medium]]></title>
        <description><![CDATA[Stories by Jakub Dziworski on Medium]]></description>
        <link>https://medium.com/@jakub.dziworski?source=rss-77dc29f98d4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1OY2LU0lPM-FURqZ.</url>
            <title>Stories by Jakub Dziworski on Medium</title>
            <link>https://medium.com/@jakub.dziworski?source=rss-77dc29f98d4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:45:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jakub.dziworski/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[Detecting hand-marked video clips with TensorFlow]]></title>
            <link>https://blog.softwaremill.com/detecting-hand-marked-video-clips-with-tensorflow-d244b5fbd3a9?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d244b5fbd3a9</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 08:12:28 GMT</pubDate>
            <atom:updated>2019-11-06T08:12:28.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*InRYqAuQYO8Axm1oYxSsHQ.png" /></figure><h3>The clip marking problem</h3><p>Have you ever shot a video of someone doing hard and repetitive task? Think action sports (skateboarding, snowboarding, inline skating) or random things like bottle flipping or making your cat do something funny. Usually it takes a lot of tries until the trick is eventually performed — only one or few shots are used. To capture the footage it takes a lot of time to actually browse through all the tries just to find these few that were successful.</p><h4>Old analog solutions</h4><p>Back in the days of tapes there was one popular solution to this. After successful shot people would usually put a hand right in front of the lens. Afterwards when rewinding the tape with preview they had known which parts needed to be captured.</p><h4>Modern ways</h4><p>We don’t capture footage from tapes anymore. After session of filming we end up with multiple files. Some cameras have option to annotate or lock video clips. This is however slow process and definitely not handy if you are right there in action, filming multiple people. You need to mark your clips as fast as possible. There is simply no time for browsing through camera menus. Other way is to mark clips with hand and then look at the thumbnails. This is neither perfect solution. Different file explorers generate thumbnails for different timestamps so your hand might not be picked up. On top of that if you have lots of footage it is easy to accidentally skip marked clip if you don’t notice the thumbnail.</p><h3>Implementation</h3><p>Luckily it is 2019 and image object detection has never been easier, thanks to neural networks. From user perspective the application is simple:</p><ol><li>Choose a source directory with video clips</li><li>Analyse last few seconds of every clip and detect hand in front of the lens</li><li>If there is a hand in a clip, copy it to destination directory for marked clips</li></ol><p>To implement such solution I decided to go with good old OpenCV for loading videos and frames grabbing. For object detection I chose Tensorflow Object Detection API. I was also lucky enough to find great hands <a href="https://github.com/EvilPort2/Hand-Tracking/blob/master/hand_inference_graph/frozen_inference_graph.pb">model</a> made by <a href="https://github.com/EvilPort2">EvilPort2</a></p><p>The main program flow is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba743075a14ec460b65fd5d3aa5ba5fd/href">https://medium.com/media/ba743075a14ec460b65fd5d3aa5ba5fd/href</a></iframe><p>First we find all MP4 files in source directory. For each file the call to find_hand_in_video is performed to run detection. Finally if the find_hand_in_video returns True the file is copied to destination directory. The find_hand_in_video function begins with following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe85dec227c0772de92b0ea16a5c992e/href">https://medium.com/media/fe85dec227c0772de92b0ea16a5c992e/href</a></iframe><p>We don’t want to process whole video — just last 3 seconds are enough. This is where hand marks are expected. First frame is calculated by subtracting 3 seconds worth of FPS from total frames amount in video. This can be achieved by getting CAP_PROP_FRAME_COUNT property and setting CAP_PROP_POS_FRAMES. Once the video is loaded into cap variable can start grabbing frames:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0db4606771a5f7ba2b1160d4e4ba2ba4/href">https://medium.com/media/0db4606771a5f7ba2b1160d4e4ba2ba4/href</a></iframe><p>We don’t want to process every frame. That would be too heavy. There are 2 main ways to skip frames using OpenCV’s VideoCapture:<br>1. Set CAP_PROP_POS_FRAMES to desired frame number<br>2. Use lightweight cap.grab() to move to next frame. Skip frames with if frame_id % SKIPFRAMES != 0. Afterwards Obtain non-skipped frames’ data using cap.retrieve()</p><p>While method 1 is easier, in our case it is simply slower. Jumping to discrete frame is very time consuming. If frames are relatively close to each other, it makes more sense to just iterate one by one and filter unwanted frames. Since we process every 40 frame the second method is more suitable. Once the frame is obtained we can perform detection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ef428517e166df432c035b23da90da/href">https://medium.com/media/02ef428517e166df432c035b23da90da/href</a></iframe><p>In TensorFlow all data is represented with tensor structure (which is basically multi dimensional array). Graphs are composed from tensors. The model that we used was created using object detection api. Such models contain tensors from which we can pick information about scores and detection boxes. np.expand_dims and np.squeeze are used to convert between OpenCV/TensorFlow array shapes. Moving back to find_hand_in_video:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a15fab552112b776ea1e4d83115a7470/href">https://medium.com/media/a15fab552112b776ea1e4d83115a7470/href</a></iframe><p>We are only interested in one hand detection. That is why we grab first item from scores and boxes arrays. We compare score to SCORE_THRESHOLD, but we also need to check how big the hand actually was. If we skip this part we might end up with lots of false positives. After all we do not want to detect hands of people in the shot — we actually only want big hand right in front of lens. Luckily our model provides data with points of box that encapsulate detected item. If the threshold value and box width are high enough the video is considered as hand marked.</p><h3>Conclusion</h3><p>Nowadays object detection in images is much easier thanks to tools with neural network capabilities like TensorFlow. In past we usually had to dive deep into computer vision theory to accomplish similar tasks. Not having to worry about it and just creating/finding good models is a pleasant and refreshing approach. There are more things to improve in solution presented above. I plan to add gestures detection to categorize clips. Also voice detection feature would be great for automatically naming clips. There are so many use cases for neural networks in image/audio detection — I highly encourage you too try it out — it is definitely worth investing some time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d244b5fbd3a9" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/detecting-hand-marked-video-clips-with-tensorflow-d244b5fbd3a9">Detecting hand-marked video clips with TensorFlow</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating offline EOS transaction without cleos]]></title>
            <link>https://blog.softwaremill.com/creating-offline-eos-transaction-without-cleos-5c48d429101d?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c48d429101d</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[eosjs]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[eos]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Thu, 22 Aug 2019 08:25:15 GMT</pubDate>
            <atom:updated>2019-08-22T08:25:15.181Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why going offline might be important for you.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7cnL3MLZSWEn5PvDX0TYQ.jpeg" /></figure><p>There are few reasons why you would want to create transactions offline without cleos:</p><ul><li>Your system communicates with nodeos using rpc api only (not cleos)</li><li>Security reasons — your system does not store keys in keosd but manages them itself</li><li>Performance or networking limitations. If you spy (using wireshark or print-request flag) on cleos when it creates a transaction it performs 5 calls to nodeos. Maybe you want your transaction creation service to be decoupled from network interactions as much as possible.</li></ul><h3>Eosjs can help you</h3><p>There are few libraries that can help us with this task, but many of them are poorly maintained or simply not mature enough to be fully trusted. Fortunately eosjs with a little bit of tweaking is also capable of solving our problem. Since it is the most popular library for interacting with eos we minimize unexpected fails. The eosjs Api class has a nice transact function:<br>transact(transaction: any, { broadcast, sign /*other params*/ })<br>If we pass { broadcast: false, sign: true }, it returns transaction in format ready (almost) for broadcasting, saving us all the daunting steps required to sign and serialiaze it. It also returns signatures for transaction that need to be used when broadcasting.<br> <br>Perfect! Well, not entirely. By default transact function calls nodeos to retrieve required information. We, however, want our service to be decoupled from nodeos or any other network interactions.<br> There are 3 items that are fetched from rpc api:</p><ul><li>chain_id from /chain/get_info</li><li>public keys required for tx from /chain/get_required_keys</li><li>abi from /chain/get_raw_code_and_abi</li></ul><p>Luckily Api class provides a way to replace all rpc calls with our own provided values via constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbe20aa812b8f6e5d61774a3750e960a/href">https://medium.com/media/bbe20aa812b8f6e5d61774a3750e960a/href</a></iframe><p>Our custom implementation of authorityProvided replaces /chain/get_required_keys call. Same thing with abiProvider and /chain/get_raw_code_and_abi call. /chain/get_infocall is replaced with explicit chainId.</p><p>The last step is converting serializedTransaction returned by transact from Uint8Array to hex string (broadcasting transaction requires this format).</p><h3>Prequesties</h3><p>In previous section the data that would normally be fetched from nodeos need to be provided manually. We can get it before running our offline service in the following way:</p><ul><li>chain_id — /chain/get_info</li><li>block_num and ref_block_prefix — these fields are required in transaction JSON. <a href="https://github.com/EOSIO/Documentation/blob/master/TechnicalWhitePaper.md#transaction-as-proof-of-stake-tapos">They are used by EOS tapos mechanism</a>. We can get them from/chain/get_block using last_irreversible_block_num from /chain/get_info</li><li>abi — It needs to be base64 encoded abi. You can get such format by calling curl — request POST — data ‘{“account_name”:”eosio”}’ — url <a href="http://your_nodeos/v1/chain/get_raw_abi%60">http://your_nodeos/v1/chain/get_raw_abi</a></li></ul><p>Once we obtained these items our offline service can be called.</p><h3>Broadcasting</h3><p>After calling transact and obtaining transaction (in format ready for broadcasting), as well as signatures for it, we can push it. To do that we just need to call /chain/push_transaction and send following body:</p><pre>{ <br> “signatures”: signatures,<br> “compression”: 0,<br> “packed_context_free_data”: “”,<br> “packed_trx”: serializedTransaction<br>}</pre><h3>Wrap up</h3><p>Generating transactions offline in Eos is not exactly the most straightforward process but it can surely be done. It just requires fetching some data beforehand, stubbing rpc calls and a little bit of formatting. <br>If you want to see full working example check out the github repo I prepared — <a href="https://github.com/JakubDziworski/Eos-Offline-Transaction-Example/blob/master/src/tx-builder.ts">Eos Offline Transaction Example</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c48d429101d" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/creating-offline-eos-transaction-without-cleos-5c48d429101d">Creating offline EOS transaction without cleos</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting helm private repository from Github]]></title>
            <link>https://blog.softwaremill.com/hosting-helm-private-repository-from-github-ff3fa940d0b7?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff3fa940d0b7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Wed, 17 Apr 2019 08:56:15 GMT</pubDate>
            <atom:updated>2019-04-17T08:56:15.365Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to setup private Github repository, instead of maintaining one yourself and spending time on making sure it is properly secured.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xs2xzuOnrycV_gWwU0uKA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/nI8YlkExQoI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jon Tyson</a> on <a href="https://unsplash.com/search/photos/love?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Why private helm repositories</h3><p>Helm is a very useful package manager for <a href="https://kubernetes.io/">Kubernetes</a>. There are a lot of out of the box charts. If you are deploying serious k8s infrastructure chances are you will find yourself in need of creating your own charts. One way to manage custom charts is keeping the sources in some directory. You can then use such chart by referencing the directory. It is simple solution but not without flaws. For me the biggest issues were versioning and tooling requirements. Some tools for automation (like <a href="https://www.terraform.io/docs/providers/helm/release.html">terraform helm_release</a>) simply require chart to be available in repository.</p><h3>Solutions</h3><p>Helm repository is just a server hosting packaged chart files and index.yaml file pointing to them. index.yaml also stores some metadata about the repository. We could create simple server hosting such files. Unfortunately we’d have to maintain such server and make sure it properly secured. The easier approach is to actually use Github to host such files.</p><h3>Github setup</h3><p>Ok first things first — create private github repository within your organization and then push some files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4db50223ec2ff4fc90a644dc922d8fca/href">https://medium.com/media/4db50223ec2ff4fc90a644dc922d8fca/href</a></iframe><p>We have just created fully functional helm repository. The tricky part is to access it as if it was simple HTTP server hosting raw files. Luckily Github provides such feature via <a href="http://raw.githubusercontent.com/">raw.githubusercontent.com</a>. In order for helm to be able to pull files from such repository we need to provide it with Github username and token (<a href="https://github.com/settings/tokens">Personal Access Token</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/481b209e91507f2498f77dfe9d9e5e3b/href">https://medium.com/media/481b209e91507f2498f77dfe9d9e5e3b/href</a></iframe><h3>Adding new packages to existing repository</h3><p>If you want to add new package to existing repository simply:</p><ol><li>Place new package in repository root</li><li>helm repo index .. This will detect new file and update index.yaml.</li><li>Commit and push your new package and updated index.yaml</li><li>helm repo update</li></ol><h3>Additional security note</h3><p>It is important to realize where does helm actually store your Github token. It is stored as plain text in ~/.helm/repository/repositories.yaml. Therefore I advise you to generate token with as few permissions as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff3fa940d0b7" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/hosting-helm-private-repository-from-github-ff3fa940d0b7">Hosting helm private repository from Github</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Bitcoin Script failures]]></title>
            <link>https://blog.softwaremill.com/debugging-bitcoin-script-failures-f7f27b2a0ec4?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f27b2a0ec4</guid>
            <category><![CDATA[p2sh]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[p2pkh]]></category>
            <category><![CDATA[btc]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 09:30:04 GMT</pubDate>
            <atom:updated>2019-06-05T11:32:18.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeeB4DCLPzsjvFz-CbGEgQ.jpeg" /></figure><p>Developing apps using Bitcoin (or bitcoin related) blockchain is fun. Until you get your first infamous mandatory-script-verify-flag-failed.<br>These come in different flavors, some of them giving reasonable hints, while others being more or less useless:</p><ul><li>Script evaluated without error but finished with a false/empty top stack element</li><li>Script failed on OP_EQUALVERIFY OP</li><li>Non-canonical DER signature</li></ul><p><a href="https://github.com/bitcoin/bitcoin/blob/master/src/script/script_error.cpp">Here you can find all types of errors</a>.</p><h3>Bitcoin Script</h3><p>Script is just a regular stack based programming language, like ASM or JVM bytecode. There are number of opcodes you can push to the stack as well as regular values. Script pops opcodes and executes them. If any operation triggers an error, or final result is false (0) then the whole execution is considered a failure:</p><ul><li>2 2 OP_ADD — Success — Nothing triggers error, final result is 4</li><li>2 1 OP_SUB — Success — result is 1</li><li>2 2 OP_SUB — Failure — result is 0</li><li>2 1 OP_SUB — Success: result is 1</li><li>2 1 OP_EQUALVERIFY —Failure — OP_EQUALVERIFY triggers an error</li><li>&lt;signature&gt; &lt;public_key&gt; OP_CHECKSIG — SUCCESS — first item (signature) matches second item (public key)</li></ul><h3>How Script is used</h3><p>In reality Script is used to create transactions for different address types.<br>The most popular addresses types are P2PKH (Pay to Public Key Hash — the ones starting with “1”) and P2SH (Pay to Script Hash — these start with “3”).<br>P2PKH address is a hash of public key while P2SH address is a hash of a redeem script. The sender is responsible for creating a locking script and attaching it to the output. The receiver on the other hand must attach an unlocking script to input when spending funds. Locking script is appended to unlocking script and such combined script is executed. If and only if the execution succeeds the output can be considered spent. It is important to note that the way locking and unlocking scripts are constructed is determined by received address type</p><h4>P2PKH</h4><p>Let’s look at at the output for this <a href="https://www.blockchain.com/btc/tx/a224cd40124ff3cafc76fd3f9d0138e9d0915b9b3ca13c8ad3e11af5e72c1bc5">transaction</a> which is consumed by the input from this <a href="https://www.blockchain.com/btc/tx/2df9c70bc74aa9e3f6c0c1e3e968707f541a6b4ac091fabf888c00b095c23aa1">transaction</a>. As we can see it is aP2PKH transaction since receiver’s address starts with “1”. The way a P2PKH transaction is constructed is as follows:</p><ol><li>For simplicity let’s call sender A and receiver B</li><li>A detects that B’s address starts with “1” — it isP2PKH a address. It therefore needs to construct an output with locking script compatible with a P2PKH standard</li><li>A adds following script to the output:<br>DUP HASH160 0x4a0f1e2f2b0d7daeec5265f10bbbbe08ed725e89 EQUALVERIFY CHECKSIG. 0x4a0f1e2f2b0d7daeec5265f10bbbbe08ed725e89 is B’s public key hash. How does A know public key hash of B? Well, in P2PKH address is the same as public key hash base58 encoded. All A had to do was decode58 address.<br>As you can see there is also EQUALVERIFY opcode. This means public key hash will be compared to something. There is also HASH160 opcode. So 0x4a0f1e2f2b0d7daeec5265f10bbbbe08ed725e89 (public key hash) will be compared to hash of “someting” that B must provide.</li><li>B decides to spend output. B creates input and adds following script to it:<br>3045022100de3d4ee588bee5c298d998c251a133213925e45f517c95097f603ae1a19a74c302204cd84d713510e010fd1cb0b367cc78f46c98a2c5a15aed728e06d882c365cc3301 0363e1776495149c5a4e92acf453a3caa19000fc804e4ba2024b600ba25e09c943. The first value is B’s signature and the second one is B’s public key.</li><li>Scripts are concatenated: 3045022100de3d4ee588bee5c298d998c251a133213925e45f517c95097f603ae1a19a74c302204cd84d713510e010fd1cb0b367cc78f46c98a2c5a15aed728e06d882c365cc3301 0363e1776495149c5a4e92acf453a3caa19000fc804e4ba2024b600ba25e09c943 DUP HASH160 4a0f1e2f2b0d7daeec5265f10bbbbe08ed725e89 EQUALVERIFY CHECKSIG</li><li>Execution step by step is as follows (I used <a href="https://github.com/kallewoof/btcdeb">btcdeb</a> script debugging tool to visualize current stack and opcodes left to be executed):</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8d1725ab9a59be790ec8a4cbc77ddbe/href">https://medium.com/media/e8d1725ab9a59be790ec8a4cbc77ddbe/href</a></iframe><h4>P2SH</h4><p>In case of <strong>P2SH</strong> address is generated from “redeem script”. Redeem script in simplest form is described as m &lt;pubkey_1&gt; &lt;pubkey_n&gt; n OP_CHECKMULTISIG where n is amount of public keys that can be used for signing input and m is the minimum required number of public keys. For example for a multisig address requiring 2 of 3 public keys to be used for spending outputs, redeem script would look like this — 2 &lt;pubkey1&gt; &lt;pubkey2&gt; &lt;pubkey3&gt; 3 OP_CHECKMULTISIG. The redeem script is created by receiver. Once receiver constructs redeem script it hashes, which finally becomes an address. The P2SH output script (locking script) is pretty simple:<br>OP_HASH160 &lt;redeem script hash&gt; OP_EQUAL<br>The corresponding P2SH input script (unlocking script) looks like this:<br>0 &lt;signature_1&gt; &lt;signature_n&gt; &lt;redeem script as hex value&gt;</p><h3>Extracting scripts from transactions</h3><p>Now that we know how Script is executed, let us take a look at failing example. Suppose our program has just created new shiny transaction and it is trying to broadcast it to the network, but receives back mandatory-script-verify-flag-failed (Script failed an OP_EQUALVERIFY operation. When the transaction broadcasting fails with such a broad error the first thing we should do is grab boradcasted tx and decode it. There are many online tools for this task, however I do not recommend using them. The most reliable and simplest way is to just use the API provided by the bitcoin node you are using. This way you can be sure transaction is decoded correctly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df5b3942aa40cf5bd518a076af6e2471/href">https://medium.com/media/df5b3942aa40cf5bd518a076af6e2471/href</a></iframe><p>Take a look at vin.scriptSig value — this is the unlocking script — first part of the puzzle. As described above unlocking script in P2PKH are just 2 values — signature and public key of receiver:<br>30450221009f61f453f44e807fdc538ca21710393d34005dd5709dabd8b6b9ccf09ea0b36a0220420d91a33f43d7b979471220e12cd1025975bd2e6c0bf2a14eb65ad89d578104 02de8f92034b9b3c956c1896d23a628537561e29faa772438aac2265c91ede6519<br>We need the second part which is locking script created by sender.<br>As we know input is connected to output from some <strong>other</strong> transaction. <strong>Beware </strong>—don’t pick locking script from output within same transaction. I know it seems obvious but there are so many similar steps it’s really easy to make such a silly mistake. In order to find output corresponding to the input we need to grab txid from vin object and get transaction:</p><pre>&gt; bitcoin-cli getrawtransaction bd6645c8c24618e43053cdc5fe8ccc9418c1307a55cd7409f9681df2fd8c2e1e</pre><pre>02000000000103989d0d3ed579749dfb8493521e908fca126e945d4f7c9a6ab32b66f98fb697d1000000001716001469f8008d203190237e2a4dffab0a3196a1b3f673feffffff6fa67f745a9e1d3cfa51d6fd4ba2ed5344cff6131464242609269456d10952520000000048473044022020c9d9c5c978cd4c0ee1ef70ba94ee96d27cc4ee45843587edfc9abf5c3b8ed602201f54b7fad1e68ebbeebc25c278efe80e88924604ca076df5f68374288028cad701feffffff07308461f2aa761d87b3ef4218aae5d600a7e17cf0e2ccb33fa76bd7e55e13aa0000000048473044022046c07b361173d647ca7c65f16e7e5a275c4a88058388588532e7cdde9d332a8a022061c0ffed32e580b19e834e9a34a78d0ee92dca7ab612f66e7fb2a0b3b70dc1b301feffffff02005a6202000000001976a914393164d26cc8a065cb4915f46f6346d63ae2607588ac55be11000000000017a9149660a010c552090f7793826329e918548b24475f8702473044022063f1c620b6712a410651a7c256b1dcf70103eb7d3ac4b2aaeb3ca2ce3685ed1902200d80aaab0a10fd994312f2402adc79e6510275b1ad3f87d053f920768865da35012102a3a8980559174a47e6c36e4dde336ac05184a602aca79515ee2c56d3dff3a4cd000034080000</pre><p>Now that we have origin transaction we need to decode it and investigate output script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18bd05512af6965aeebae01e4793f2ca/href">https://medium.com/media/18bd05512af6965aeebae01e4793f2ca/href</a></iframe><p>Pay attention which output you select — n must match vin.vout in transaction that failed. Again it’s one of the silly mistakes that can lead to wrong debugging conclusions. Since vin.vout in spending transaction is 0 we must select script for output with n=0:<br>OP_DUP OP_HASH160 393164d26cc8a065cb4915f46f6346d63ae26075 OP_EQUALVERIFY OP_CHECKSIG</p><h3>Debug it just like any code</h3><p>Now that we have both locking and unlocking script we are ready to append them (pay attention to order):</p><pre>30450221009f61f453f44e807fdc538ca21710393d34005dd5709dabd8b6b9ccf09ea0b36a0220420d91a33f43d7b979471220e12cd1025975bd2e6c0bf2a14eb65ad89d578104 <br>02de8f92034b9b3c956c1896d23a628537561e29faa772438aac2265c91ede6519<br>OP_DUP<br>OP_HASH160<br>393164d26cc8a065cb4915f46f6346d63ae26075<br>OP_EQUALVERIFY OP_CHECKSIG</pre><p>Once we have complete script we can execute it step by step manually or using debugging tool like <a href="https://github.com/kallewoof/btcdeb">btcdeb</a>. Since it is a simple operations we can just execute it manually:</p><ol><li>Signature is pushed onto the stack (30450221009f61f453f44e807fdc538ca21710393d34005dd5709dabd8b6b9ccf09ea0b36a0220420d91a33f43d7b979471220e12cd1025975bd2e6c0bf2a14eb65ad89d578104)</li><li>Public Key is pushed onto the stack (02de8f92034b9b3c956c1896d23a628537561e29faa772438aac2265c91ede6519)</li><li>Public Key is pushed onto the stack again (OP_DUP duplicated top element)</li><li>Public Key is popped from stack hashed and pushed back (b27f04e510293c3e530e7b7bdf71f59118030e1e)</li><li>Public Key Hash is pushed onto the stack (393164d26cc8a065cb4915f46f6346d63ae26075)</li><li>OP_EQUALVERIFY is executed — it compares two top values from stack and fails script if they are different. This part fails!</li></ol><p>Let’s actually make a hash of 02de8f92034b9b3c956c1896d23a628537561e29faa772438aac2265c91ede6519. For that we can use online tools but beware of them. To be honest bitcoin tooling available online are a little messy. When using any tool for the first time validate it against correct outputs. If the tool provides matching results it is safe to use for debugging invalid scripts. The hash is b27f04e510293c3e530e7b7bdf71f59118030e1e which is definitely not 393164d26cc8a065cb4915f46f6346d63ae26075. <br>We were able to find the issue —<strong> the public key provided by receiver does not match the public key hash provided by sender!</strong><br>Moving back to the code that created transaction we found out it was signing inputs with wrong key —quick patch was applied and problem solved.</p><h3>Some other errors</h3><p>Sometimes there are problems you might be able to spot right away by looking at the script. These might be missing opcode or some particular value (for example any P2SH locking script must start with 0). There are however more difficult cases where error gives you almost no insight into what is going on. Some of them are:</p><ul><li>Providing bad signature for public key in unlocking script for P2PKH will result in very broad Script evaluated without error but finished with a false/empty top stack element. Why? Let’s look how the P2PKH script looks:<br>&lt;receiver_signature&gt; &lt;receiver_public_key&gt; OP_DUP OP_HASH160 &lt;receiver_public_key_hash&gt; OP_EQUALVERIFY OP_CHECKSIG<br>As you can see, after verifying public key and public key hash matches, signature is checked against public key. OP_CHECKSIG however doesn’t trigger error (unlike OP_EQUALVERIFY). It it just returns 0 or 1. In case of invalid signature the stack is left with 0 element which is false thus causing script to fail.</li><li>Different order of public keys in redeem script for P2SH will also result in very general Script evaluated without error but finished with a false/empty top stack element. As you can see comparing redeem script hashes is done using OP_EQUAL which doesn’t trigger error. It can happen if you used the same public keys for creating redeem script during address generation and during input script creation<strong> but with different order</strong>. When checking signatures order of public keys shouldn’t matter, but unfortunately the redeem script hash is different.</li></ul><h3>Summary</h3><p>If you are developing application which creates and broadcasts bitcoin transactions, it is very likely sooner or later you will need to deal with Script errors. Libraries which we use to construct transactions can prevent most of them. Unfortunately still many failures can only be detected when scripts are combined and executed together. We must be aware of it and take extra care when constructing transactions. If, after all, something goes wrong, now you know some tips how to handle it.</p><p><em>Thinking of blockchain adoption? Grab insights from 8 blockchain experts in a free copy of </em><a href="https://blockchainebook.softwaremill.com/"><em>“Blockchain Adoption Kit” ebook</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f27b2a0ec4" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/debugging-bitcoin-script-failures-f7f27b2a0ec4">Debugging Bitcoin Script failures</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical monitoring with Prometheus]]></title>
            <link>https://blog.softwaremill.com/practical-monitoring-with-prometheus-ee09a1dd5527?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee09a1dd5527</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Tue, 04 Dec 2018 11:41:17 GMT</pubDate>
            <atom:updated>2021-07-16T11:08:23.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V35x8bMdcKVFAiJeROJDOw.jpeg" /><figcaption>Photo by Shane Aldendorff from Pexels</figcaption></figure><p>When I first started using Prometheus, I found the documentation very useful when it comes to describing features of the library. I was, however, a little bit lost when it comes to bigger picture. What to monitor? What is the best method to monitor specific cases? Back then, I would really appreciate a common set of metrics for typical systems that most of us develop on a daily.<br>In this post I would like to present how to create such a monitoring solution.</p><h3>What to monitor?</h3><p>The very first thing to do, when building a monitoring system is deciding what should actually be monitored.<br>Over the time and a few projects I learned that items worth monitoring are:</p><ul><li>Inputs to the system</li><li>Outputs from the system</li><li>Important/time-consuming operations within the system</li><li>Resources</li></ul><p>The most common inputs to system are:</p><ul><li>HTTP endpoints</li><li>Message broker consumers (e.g. Kafka Consumer)</li><li>Reading from databases/files/services</li></ul><p>The most common outputs from the system are:</p><ul><li>Saving to databases/files</li><li>Calling external services</li><li>Producing to a message broker</li></ul><p>Examples of important/time-consuming operations within system are:</p><ul><li>One cycle of the batch processing (e.g. once a day you check all users transactions and make a report)</li><li>Creating and signing a bitcoin transaction</li></ul><p>So what I usually do is to find all inputs and outputs to my system as well as all long running operations within it.</p><h3>Subject of monitoring</h3><p>With this brief introduction, let’s actually take a look how to create monitoring system for a social media app. This app has the following components:</p><ul><li>HTTP endpoints POST /users and GET /users/{id}. Used for registering new user and getting their summary.</li><li>PostgreSQL users table. Used for saving and reading user data.</li><li>Auth service. Called when any endpoint is triggered to validate permissions.</li><li>Kafka topic posts. Used for displaying posts created by friends a user is connected with.</li><li>Time-consuming process of generating video for friends who have known each other for a couple years. Triggered every night.</li></ul><h4>Incoming HTTP requests</h4><p>There are many libraries for integrating HTTP server-side frameworks with prometheus. At SoftwareMill we mainly use Akka HTTP so we go with <a href="https://github.com/lonelyplanet/prometheus-akka-http">Prometheus Akka HTTP</a>.<br>Such libraries usually expose a Prometheus histogram and allow you to add labels with the names of the endpoints.</p><pre>pathPrefix(&quot;users&quot;) {<br>  recordResponseTime(&quot;post_user_endpoint_label&quot;) {<br>    (post &amp; pathEndOrSingleSlash) { /*….*/ }<br>  } ~<br>  recordResponseTime(&quot;get_user_endpoint_label&quot;) {<br>    (get &amp; path(JavaUUID) ) { /* …. */ }<br>  }<br>}</pre><p>A Prometheus histogram exposes two metrics: count and sum of duration.<br>Having such data we can plot requests per second and average request duration time.</p><ul><li>Requests duration (all endpoints combined — all labels are aggregated with sum):<br>sum(rate(http_request_duration_count[1m]))</li><li>Average requests duration (all endpoints combined — all labels are aggregated with avg):<br>avg(rate(http_request_duration_sum[1m])/rate(http_request_duration_count[1m]))</li><li>Requests per second (different graph for each endpoint — label):<br>rate(http_request_duration_count[1m])</li><li>Requests per second (different graph for each endpoint — label):<br>rate(http_request_duration_sum[1m])/rate(http_request_duration_count[1m])</li></ul><h4>Database</h4><p>There are Prometheus metrics exporters for databases. Often, however, things can get stuck on a client side so I find measuring queries from client very handy.<br>There are many different databases and libraries used to interact with them. Most of them provide you with some kind of generic callback that gives you information about queries and their duration. You can start a timer there and observe the duration. I also recommend adding a label for this metric with query statement itself. This will allow to find which kind of queries tend to be the most time-consuming. If you use this approach remember to remove the query parameters in order to have label per query type, instead of millions of useless labels.<br>In our case we use PostgreSQL and interact with it using <a href="http://scalikejdbc.org/">ScalikeJDBC</a>. This is how you can hook it up using such library:</p><pre>Histogram<br> .build()<br> .name(“sql_duration”)<br> .help(“Sql statement duration in seconds.”)<br> .labelNames(“statement”)<br> .register()</pre><pre>GlobalSettings.queryCompletionListener = (sql: String, params:  Seq[Any], millis: Long) =&gt; {<br> val sqlWithoutParamList = sql<br> .replaceAll(“, \\?”, “”)<br> .replaceAll(“JOIN \\(VALUES .* vals”, “JOIN VALUES (?) vals”)<br> sqlHistogram<br> .labels(sqlWithoutParamList)<br> .observe(millis / 1000.0)<br>}</pre><p>Exactly the same method can be used to monitor HTTP requests to measure queries count and average duration. Just instead of http_request_duration use sql_duration.</p><h4>Kafka</h4><p>When it comes to measuring Kafka consumer, it’s simply a matter of starting a timer before handling message and closing it afterwards. Prometheus will measure time automatically and expose the metrics. It’s a good idea to add a label for a topic. Currently we only have just one topic but there might be more introduced in the future.</p><pre>val kafkaHistogram = Histogram<br> .build(“kafka_message_duration”, “Kafka message handling duration”)<br> .labelNames(“topic”)<br> .register()</pre><pre>def handleMessage(message: Message) = {<br> val topic = message.record.topic<br> val timer = kafkaHistogram.labels(topic).startTimer()<br> handle(message)<br> timer.close()<br>}</pre><p>Querying kafka messages received per second and average handling duration is the same as shown previously — just with different metrics names.</p><h4>Calls to an external service</h4><p>There are libraries for integrating an HTTP client but it can be also achieved manually using a timer. We use <a href="https://github.com/softwaremill/sttp">STTP</a>, which indeed has a Prometheus plugin, which exposes histogram. Having histogram data we can perform the same monitoring techniques for measuring average request time and requests amount.</p><h4>Generating video</h4><p>For daily videos generation we can use a similar strategy. For such task we need to manually start and stop timer similarly to Kafka scenario:</p><pre>val videoHistogram = Histogram<br> .build(“friends_video”, “Friends video generation duration”)<br> .register()</pre><pre>def createVideos = {<br> val friends = db.fetchUsersBeingFriendsOverFiveYears()<br> friends.foreach { friendsPair =&gt;<br> val timer = videoHistogram.startTimer()<br> videoGenerator.generae(friendsPair)<br> timer.close()<br> }<br>}</pre><p>Since video generation will take some time it’s pointless to measure “videos per second”. Instead, I would suggest plotting just the amount of videos generated over time. This way we can see how many videos were generated in one batch and see how long the batch took. It’s as simple as querying <br>friends_videos_count metrics.</p><h4>Resources</h4><p>Resources is the easiest part. By using <a href="https://github.com/prometheus/node_exporter">Node Exporter</a> we get all the resource-related metrics. There are also <a href="https://grafana.com/dashboards?dataSource=prometheus">predefined Grafana dashboards</a> which I highly recommend for finding out which metrics to use and what queries to perform.</p><h3>Visualizing</h3><p>For visualizing I recommend using <a href="https://grafana.com/">Grafana</a>. It’s especially useful when you have complicated metrics with lots of labels. You can then create drop-down menus and choose which labels values you want to select. The best way to learn it is just find a good dashboard and see how it’s done under the hood. Go to <a href="https://grafana.com/dashboards">https://grafana.com/dashboards</a>, choose Prometheus as data source, browse available dashboards and you will learn how to use to its’ full potential in just a few minutes.</p><h3>Summary</h3><p>In this post I presented how to build a Prometheus monitoring solution for components used in an ordinary system. There are, however, lots of different ways to approach such task. If you know any of them, we would love to hear it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee09a1dd5527" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/practical-monitoring-with-prometheus-ee09a1dd5527">Practical monitoring with Prometheus</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating legacy data to Akka Persistence Event Store]]></title>
            <link>https://blog.softwaremill.com/migrating-legacy-data-to-akka-persistence-event-store-69cd59402677?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/69cd59402677</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 11:47:43 GMT</pubDate>
            <atom:updated>2018-12-03T15:27:05.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4Jv1AHFpyiQ8k-NILrt2g.jpeg" /></figure><p>Suppose you were working on a project that used to be simple CRUD using relational database. The popularity kept growing and growing and scalability became an issue. You therefore decided to rewrite service to CQRS+ES using Akka Persistence. The project is ready to launch — you just need to migrate existing data… but how?</p><p>I found a few ways to do that each having different pros and cons. All of them require to write a custom script that scans legacy database and converts it to events or commands. The way you convert entities from legacy database to events/commands depends on how the entities were stored. Most legacy systems store current state of the entity and mutate it. In such case you have no other way and just create commands/events from last state (e.g. create UserCreated events from rows in table users).</p><h3>Convert legacy data to raw events and save them in event store directly</h3><p>It may seem that the simplest way is to convert rows from legacy database to events and save them directly to the event store. This method however, has many tricky parts. The biggest problem is that there is lots of technical data stored in Akka Persistence’s event stores. It’s not a case of simply populating events table. Let’s take a Cassandra journal plugin, being the most popular one, as an example. There are many tables (messages, metadata, tag_scanning, tag_views, tag_write_progress). The columns in messages table are persistence_id, partition_nr, sequence_nr, timestamp, timebucket, event, event_manifest, message, meta, meta_ser_id, meta_ser_manifest, ser_id, ser_manifest, tags, used, writer_uuid. As you can see the event is just one of 16 columns you have to populate. It is therefore mandatory to understand the journal plugin internals really well to know what should be stored in which column. This method is relatively dangerous. If you make any mistake (and it’s very easy) when populating any of the tables, some of your events might not be recovered, be recovered out of order, or persistence query stop working. Debugging such issues is really troublesome.</p><h4>PROS</h4><ul><li>Highest level of decoupling — no need to use actors. It’s just “simple” READ-CONVERT-WRITE flow. All required dependencies are legacy database driver and event store database driver.</li></ul><h4>CONS</h4><ul><li>Lots of repetition (in case of Cassandra)</li><li>Lots of technical data</li><li>Mistakes can easily lead to fatal consequences</li><li>Impossible to easily switch between different journal implementations</li><li>Necessity to understand journal internals really well</li><li>Breaking changes to journal plugin may require migration modifications</li><li>Manually serializing and maintaining compatibility with production deserializer</li></ul><h3>Convert legacy data to Commands and send them to persistence actors</h3><p>As you can see the first method has many flaws. They, however, all can be overcome by using persistence actors directly. Add your project as dependency to migration script and instantiate actor system. Convert legacy data to commands and simply send them to actors. Let your actors do the magic of handling commands, creating events and persisting them to event store. You avoid a headache of digging into journal guts and save yourself from making mistakes. In many projects however, command handlers perform side effects, which are not desirable when migrating. A good example are withdrawals triggered by thePerformWithdrawCommand — actor performs call to an external service which does the actual change of the user account balance. You don’t want to withdraw your users money twice, do you? To solve this problem you would have to introduce some kind of isMigration flag to the project which is a little bit nasty and also dangerous (what if you forget to do that in some places?).</p><h4>PROS</h4><ul><li>All of the problems from 1st method are not relevant anymore</li></ul><h4>CONS</h4><ul><li>Having to handle some commands differently in case of migration — code changes to production code.</li></ul><h3>Convert legacy data to Events and send them to custom persistent actor with the same persistenceId</h3><p>Another way is converting rows to events and sending them to custom migration actors that simply persist the events:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3f4cd905f115f8adf859bcc8d649a4b/href">https://medium.com/media/a3f4cd905f115f8adf859bcc8d649a4b/href</a></iframe><p>It’s very important to have persistenceId and clusterSharding implementations correspond to your normal production actors. Only then events are recovered by correct actors when you run the production system.</p><h4>PROS</h4><ul><li>Problems from first and second method are gone</li></ul><h4>CONS</h4><ul><li>Having to write custom actor and clusterSharding implementation</li></ul><h3>Summary</h3><p>As you can see, migrating data to Akka Persistence is not a trivial process. Each method has different trade offs, but I think in most cases the safest and easiest is third option. Do you know other way of migrating? Share it — we would love to hear about it.</p><figure><a href="http://bit.ly/2li6uLV"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39zCgcLzqd6lM7t7oQqSCw.png" /></a></figure><p><strong>Looking for Scala and Java Experts?</strong></p><p><a href="http://bit.ly/2li6uLV"><strong>Contact us!</strong></a></p><p>We will make technology work for your business. <a href="http://bit.ly/2I0zctj">See the projects we have successfully delivered</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69cd59402677" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/migrating-legacy-data-to-akka-persistence-event-store-69cd59402677">Migrating legacy data to Akka Persistence Event Store</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript data validation with Joi]]></title>
            <link>https://blog.softwaremill.com/javascript-data-validation-with-joi-99cdffb5dd57?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/99cdffb5dd57</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[joi]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 10:41:24 GMT</pubDate>
            <atom:updated>2018-04-16T10:41:24.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPAwTWTT9yHQo1cQ956qNQ.jpeg" /></figure><h3>Y u no validate?</h3><p>Validating input to the system is one of the most trivial but at the same time the most neglected part of our job.<br>It is still however extremely important. With adequate input validation we can prevent:</p><ul><li>Exposing security vulnerabilities like sql injection</li><li>Receiving incorrect type or format</li><li>Receiving too much data</li></ul><p>It’s not too bad if the program implicitly throws error after receiving incorrect data. Most of the time we can track what went wrong in such cases.<br>However it becomes really scary when app treats malicious data as correct and proceeds it. Weird things can and will happen then.</p><p>Why then developers often neglect validation? In my opinion, because it’s easy, but at the same time relatively time-consuming and can lead to lots of boilerplate code filled with lots of conditional code.<br>This is especially true when using language such as JavaScript where checking type or existence of a value is often confusing.<br>I’ve seen and written such code many times — it’s definitely not a pleasant experience.</p><h3>Schema validation with Joi to the rescue</h3><p>However it doesn’t have to be that way. There are ways to validate data easily and enforce updating rules when the data format changes.</p><p>Ideally it would be great if we were able to define schema together with constraints for an object and validate it.<br>JavaScript wouldn’t be JavaScript if there weren’t multiple libraries offering such functionality:</p><ul><li>Joi</li><li>Tcomb-validation</li><li>Validatorjs</li><li>Validate.js</li></ul><p>They all are similar but in my opinion Joi is the best and most popular so we’ll focus on it.</p><p>Suppose we have an express app allowing to create, edit and view users.<br>There is a name and surname which shouldn’t be too short or too long.<br>There is also a year of birth which should be within some reasonable bounds.<br>Lastly, there is an email which should be valid email string. All of the fields except email are required. Here’s how we can validate such input using Joi:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a073ba9b8cc9945870e7d9e1992460/href">https://medium.com/media/e1a073ba9b8cc9945870e7d9e1992460/href</a></iframe><p>Let’s test it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b767f3641a03e1b064cdee574001921d/href">https://medium.com/media/b767f3641a03e1b064cdee574001921d/href</a></iframe><p>Apart from validating, Joi gives us additional feature for free — it converts values to expected types. In the request body birthYear was sent as string, but according to schema it’s a integer. Joi was luckily able to validate it and convert it to number. As a result birthYear is a number in response body — that’s neat! Imagine how many if checks we’d have to write to accomplish the same task.</p><p>Another great feature about validating input using schema is that it forces developer to change it each time data format changes.<br>It is not true for manual conditional checks — they are often forgotten to be removed, while new ones are not created, leading to crippled validation.</p><h3>Reusing schemas</h3><p>Now let’s create endpoint for editing user. We’d like to allow to edit any attribute of user so all of the fields are optional:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f9b5f685223d2d625c6bfe5a273fd6/href">https://medium.com/media/52f9b5f685223d2d625c6bfe5a273fd6/href</a></iframe><p>It looks a lot like createUserSchema, but without required().<br>We all know code duplication is bad, but thanks to Joi schemas being immutable we can easily reuse them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7f7c19db3b3b061cdd777220c932e38/href">https://medium.com/media/e7f7c19db3b3b061cdd777220c932e38/href</a></iframe><p>Edit user route might then look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c48db3a0e9a0eadd1f890ec767e38d2/href">https://medium.com/media/9c48db3a0e9a0eadd1f890ec767e38d2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0c065c06a656b0780d45bdb797f3626/href">https://medium.com/media/a0c065c06a656b0780d45bdb797f3626/href</a></iframe><h3>Validating requests with express middleware</h3><p>So far we’ve been validating only request body. How about parameters, headers and query parameters?<br>It could get a little verbose using the same method we’ve seen so far — how about writing generic middleware, that can validate any request?<br>Let’s take a look at example of getting users, filtering optionally by surname.<br>To spice things up, our API will also require 20 character long token in a header for authorization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f5649a13e9ae0fcfc9db44e423c1f9d/href">https://medium.com/media/9f5649a13e9ae0fcfc9db44e423c1f9d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c66de8600403a6b51fc303170bb25c1c/href">https://medium.com/media/c66de8600403a6b51fc303170bb25c1c/href</a></iframe><h3>Know your shortcuts</h3><p>Joi also includes many shortcut functions shirking code significantly.</p><p>Default values — We could add role attribute to createUserSchema. If it is not provided it could be “customer” by default:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a805431b88a56fee6769228c4315fa7/href">https://medium.com/media/6a805431b88a56fee6769228c4315fa7/href</a></iframe><p>Referencing other fields in validated object — Suppose when creating admin, additional secret has to be included. Otherwise it’s forbidden to include it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e38ba19402e78936c613fdc84313d423/href">https://medium.com/media/e38ba19402e78936c613fdc84313d423/href</a></iframe><p>Arrays — Let’s include array of unique nicknames for user to our api, but allow up to maximum of 2:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86a5c51257a7242699acded7ac7c182/href">https://medium.com/media/c86a5c51257a7242699acded7ac7c182/href</a></iframe><p>Binary — Including base64 encoded optional user avatar image but not bigger than 2mb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5be4afbeb30ab0752705943910366f2/href">https://medium.com/media/a5be4afbeb30ab0752705943910366f2/href</a></iframe><p>Dates — How about changing date of birth to exact day, but keeping min and max requirements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6c25bf58a8d977cd16d5519095fdab0/href">https://medium.com/media/a6c25bf58a8d977cd16d5519095fdab0/href</a></iframe><p>Predefined string patterns (no more googling regexes) — Let’s add ip, credit card and homepage to our createUserSchema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36041354bf36f7cc047a4316cea2db13/href">https://medium.com/media/36041354bf36f7cc047a4316cea2db13/href</a></iframe><p>Custom error messages — In one of examples above we defined token schema (Joi.string().token().length(20).required()). If token is too short or too long, by default, Joi will create an error message token length must be 20 characters long. Sometimes we don’t want to expose such details for security reasons. To override this behavior use error function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08b53691597dde2c5c027d2aa25deace/href">https://medium.com/media/08b53691597dde2c5c027d2aa25deace/href</a></iframe><p>There are many, many more — I encourage you to take look at the <a href="https://github.com/hapijs/joi/blob/master/API.md">api reference</a>.</p><h3>Summary</h3><p>Validation in javascript is easy, quick and maintainable — there is simply no excuse to neglect it.<br>Just ditch your army of conditional checks and start using right tools designed exactly for this purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99cdffb5dd57" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/javascript-data-validation-with-joi-99cdffb5dd57">JavaScript data validation with Joi</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Akka Streams pitfalls to avoid — part 1]]></title>
            <link>https://blog.softwaremill.com/akka-streams-pitfalls-to-avoid-part-1-75ef6403c6e6?source=rss-77dc29f98d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ef6403c6e6</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka-streams]]></category>
            <dc:creator><![CDATA[Jakub Dziworski]]></dc:creator>
            <pubDate>Tue, 21 Nov 2017 11:04:56 GMT</pubDate>
            <atom:updated>2018-06-06T15:06:08.386Z</atom:updated>
            <content:encoded><![CDATA[<h3>Akka Streams pitfalls to avoid — part 1</h3><p><em>Written by </em><a href="https://medium.com/u/77dc29f98d4a"><em>Jakub Dziworski</em></a><em> and </em><a href="https://medium.com/u/5db5c579e5f8"><em>Andrzej Ludwikowski</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KSzEIGQwfJBU86OQ." /></figure><p>The Akka Streams library is proven to be very useful in implementing systems focused on data processing. However, if you use it without prior knowledge or insufficient care you may encounter some really weird behavior.</p><p>At SoftwareMill we’ve been using Akka Streams in many projects. During this time we’ve come across multiple quirks related to this library. After you gain more experience, most of them make sense, but are not intuitive at first glance. Especially if you are trying to solve the problem with a procedural mindset.</p><p>This post is a collection of common Akka Streams pitfalls with explanations how to avoid them. We found ourselves caught in these traps many times while learning the library. We hope you can learn from our mistakes.</p><h3>1. Swallowed exceptions</h3><p>The default behavior for most stages when the exception is thrown is to… swallow it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b377eb4166ddbb9e2ddda7c571f983a/href">https://medium.com/media/3b377eb4166ddbb9e2ddda7c571f983a/href</a></iframe><p>In such case the stream will just be completed without any logs. To actually log exceptions there are 2 options:</p><ul><li>log or rethrow exception in the recover stage. This way all exceptions from upstream will be caught and logged:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91df6ae0e12b33bd72293bcf335f1c1a/href">https://medium.com/media/91df6ae0e12b33bd72293bcf335f1c1a/href</a></iframe><ul><li>define custom supervision strategy and use it in stream attributes or in materializer settings:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe37267a0acaafffed7e802fd3dc38d/href">https://medium.com/media/7fe37267a0acaafffed7e802fd3dc38d/href</a></iframe><h3>2. Value, by-name and function parameters</h3><p>Generally speaking, most methods in Akka Streams API require a function to transform emitted elements. After some time you may find yourself accustomed to transforming elements with lambdas. For this reason there is a high possibility you are going to misinterpret methods that take value parameters. Let’s imagine you need to consume elements from an infinite queue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/742ba3b70a25e3140d5b90de5f4c6cab/href">https://medium.com/media/742ba3b70a25e3140d5b90de5f4c6cab/href</a></iframe><p>The code above seems to be fine, but the actual output is:</p><pre>msg1<br>msg1<br>msg1<br>msg1</pre><p>It turns out that repeat takes parameter which is a <strong>value</strong> (def repeat[T](element: T)), so it repeats the same element over and over again. It gets even more confusing if you are used to the Scala collection API. Stream.continually — equivalent of Source.repeat has a method which takes by-name parameter(def continually[A](elem: =&gt; A)). To solve the issue you can just repeat irrelevant value like Unit and map it to something else in the next stage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0df703a177718e3332bb3b8dfd415999/href">https://medium.com/media/0df703a177718e3332bb3b8dfd415999/href</a></iframe><p>Pay extra attention to what kind of parameter is required by a method you use.</p><h3>3. Exceptions thrown outside stages</h3><p>A similar case applies to exceptions. Suppose you want to consume messages from JMS queue. Communication with an external services should always be considered unstable. To make such cases more resilient, Akka provides RestartSource, which will restart the inner source each time it fails in a backoff manner… at least it should.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2852460c7adaf68a20e24e67faa5718d/href">https://medium.com/media/2852460c7adaf68a20e24e67faa5718d/href</a></iframe><p>Calling connectToUnstableService() could throw an exception. Theoretically, RestartSource should automatically retry an inner source if the exception is thrown. However, if you run this example the exception is going to be thrown and the stream will just complete:</p><pre>Error during preStart in [akka.stream.scaladsl.RestartWithBackoffSource@7174a4f4]: Failed to connect service<br>java.lang.RuntimeException: Failed to connect unstable jms service</pre><p>Why? If you look closely, connectToUnstableService() is called when creating an inner source. Source.single takes value as a parameter. The exception is therefore not thrown while the stream is processing, but before it was even created. This is something out of RestartSource’s jurisdiction. The solution is similar to the previous pitfall — just create a source with a single unit element and map this element to a connection or whatever dangerous operation you want to perform:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/885d8936c78e44c4656a3db9388fb6cb/href">https://medium.com/media/885d8936c78e44c4656a3db9388fb6cb/href</a></iframe><h3>4. mapAsync — keep everything in the Future</h3><p>If you want to process something in parallel, there is a good chance that you would usemapAsync. Good choice, just remember to put everything in the Future. Otherwise you will end up with blocking code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f26ad20891899e9a8217d9dc12876867/href">https://medium.com/media/f26ad20891899e9a8217d9dc12876867/href</a></iframe><p>Such source will finish not after about 5 seconds, as you might assume, but after 25 seconds:</p><pre>2017–11–16 14:09:<strong>33</strong>,581 — very slow action 1 … <br>2017–11–16 14:09:38,585 — very slow action 2 … <br>2017–11–16 14:09:43,585 — very slow action 3 … <br>2017–11–16 14:09:48,585 — very slow action 4 … <br>2017–11–16 14:09:53,587 — very slow action 5 … <br>2017–11–16 14:09:<strong>58</strong>,588 — done …</pre><p>Because the Future is not enclosing the blocking code, it will actually block the actor responsible for this stage. Remember that all stages not marked asynchronous will run in one single actor. With a corrected example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c5518bb9b14f8d1d9d71f3113953c08/href">https://medium.com/media/4c5518bb9b14f8d1d9d71f3113953c08/href</a></iframe><p>everything works as expected:</p><pre>2017–11–16 14:10:<strong>41</strong>,041 — very slow action 1 … <br>2017–11–16 14:10:41,041 — very slow action 2 … <br>2017–11–16 14:10:41,042 — very slow action 4 … <br>2017–11–16 14:10:41,042 — very slow action 3 … <br>2017–11–16 14:10:41,042 — very slow action 5 … <br>2017–11–16 14:10:<strong>46</strong>,043 — done …</pre><h3>5. tick as a scheduler</h3><p>Let’s say you want to schedule some processing with 60 minute intervals. Usually the processing takes about 40 minutes to finish. Sometimes it needs more than the scheduled interval, e.g. 90 minutes. In such case you would like to start the next processing, right after the previous one. Unfortunately, if you use the tick method, your scheduler will need to wait for the next tick.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb53b4c764171266390b83870b4ad55/href">https://medium.com/media/7cb53b4c764171266390b83870b4ad55/href</a></iframe><pre>2017–11–15 08:46:<strong>34</strong>,584 — Processing started<br>2017–11–15 08:46:41,586 — done!<br>2017–11–15 08:46:<strong>44</strong>,494 — Processing started<br>2017–11–15 08:46:51,495 — done!<br>2017–11–15 08:46:<strong>54</strong>,494 — Processing started<br>2017–11–15 08:47:01,495 — done!</pre><p>As you can see, the interval between Processing started lines is 10 seconds, instead of 5 seconds. Since the actual processing needs more than 5 seconds, <br>every second tick is skipped. This can be fixed by adding buffer(1, OverflowStrategy.<em>backpressure</em>) after tick.</p><p>If you know some more pitfalls please leave a comment. Don’t forget to check out <a href="https://blog.softwaremill.com/akka-streams-pitfalls-to-avoid-part-2-f93e60746c58">Part 2</a> too.</p><figure><a href="http://bit.ly/2kTnW94"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQUlm-o3I57GE0TxaxWIMg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ef6403c6e6" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/akka-streams-pitfalls-to-avoid-part-1-75ef6403c6e6">Akka Streams pitfalls to avoid — part 1</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>