<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-34374221</atom:id><lastBuildDate>Fri, 27 Mar 2026 11:48:20 +0000</lastBuildDate><category>TypeScript</category><category>java</category><category>javascript</category><category>rust</category><category>Scala</category><category>Beginning Java</category><category>Spring</category><category>Spring Framework</category><category>learning rust</category><category>CQRS</category><category>ip-num</category><category>Axon</category><category>Software Architecture</category><category>Typeclass</category><category>Cryptography</category><category>Cryptography101</category><category>cidr</category><category>Learning TypeScript</category><category>SpringMVC</category><category>networking</category><category>Es6</category><category>Notes</category><category>Personal</category><category>JPA</category><category>Software Development</category><category>Functional Programming</category><category>IPv4</category><category>IPv6</category><category>geekabyte</category><category>#TooLongForTwitter</category><category>Crypto</category><category>Hibernate</category><category>JProwork</category><category>Maven</category><category>Monads</category><category>NFTs</category><category>Prowork</category><category>Solana</category><category>closure</category><category>AMD</category><category>ASN</category><category>AngularJs</category><category>Blockchain</category><category>Blogging</category><category>CSS</category><category>Cats</category><category>CommonJS</category><category>Deno</category><category>ElasticSearch</category><category>Jackson</category><category>Meta</category><category>Modules</category><category>Random</category><category>SLF4J</category><category>SSH</category><category>Snippets</category><category>atto</category><category>git</category><category>linux</category><category>ne</category><category>nodejs</category><category>reddit</category><category>ristex</category><category>sysadmin</category><category>unix</category><title>geekAbyte</title><description></description><link>http://www.geekabyte.io/</link><managingEditor>noreply@blogger.com (dade)</managingEditor><generator>Blogger</generator><openSearch:totalResults>242</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-6388603237987598188</guid><pubDate>Sun, 14 Apr 2024 17:56:00 +0000</pubDate><atom:updated>2024-04-15T18:14:20.902+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><title>FuturesOrdered: Keeping Concurrency in Order In Rust</title><description>&lt;p&gt;The use case is as follows: You have some tasks you want to execute concurrently, but you want the results to be returned in the same order the tasks were defined to be executed.&lt;/p&gt;

&lt;p&gt;As an example, let&#39;s say you have some records returned from the database, as specified by some query. But before returning the records, some transformation needs to be done, and these transformations can be done concurrently. Due to the nature of concurrency, the order in which the transformations will be done is nondeterministic, meaning the order of the transformed records can and will end up being different from the original order of the records as retrieved from the database. This is something you do not want; you want the transformed records to be in the same order as specified in the original query that retrieved them from the database.&lt;/p&gt;

&lt;p&gt;This sounds like the perfect task for Rust&#39;s FuturesOrdered type from the &lt;a href=&quot;https://crates.io/crates/futures&quot;&gt;futures&lt;/a&gt; crate.&lt;/p&gt;

&lt;p&gt;Reading the &lt;a href=&quot;https://docs.rs/futures/latest/futures/stream/struct.FuturesOrdered.html&quot;&gt;documentation&lt;/a&gt;, it states:&lt;/p&gt;

&lt;blockquote&gt;&quot;...it imposes a FIFO order on top of the set of futures. While futures in the set will race to completion in parallel, results will only be returned in the order their originating futures were added to the queue.&quot;&lt;/blockquote&gt;

&lt;p&gt;Just what we want.&lt;/p&gt;
&lt;p&gt;Let us illustrate with some code.&lt;/p&gt;

The dependencies:

&lt;pre&gt;&lt;code class=&quot;language-toml&quot;&gt;[dependencies]
futures = &quot;0.3.30&quot;
tokio = { version = &quot;1.37.0&quot;, features = [&quot;full&quot;]}
rand = &quot;0.8.5&quot;&lt;/code&gt;&lt;/pre&gt;

The code:

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;async fn transform(number: i32) -&amp;gt; i32 {
    let mut rng = rand::thread_rng();
    let random_number = rng.gen_range(1..=5);
    tokio::time::sleep(Duration::from_secs(random_number)).await;
    println!(&quot;Done from {number}&quot;);
    return number;
}

#[tokio::main]
async fn main() -&amp;gt; std::io::Result&amp;lt;()&amp;gt; {
    let mut tasks = FuturesOrdered::new();
    for n in 0..9 {
        tasks.push_back(async move { transform(n).await })
    }
    let mut results = vec![];
    while let Some(result) = tasks.next().await {
        results.push(result)
    }
    println!(&quot;{results:?}&quot;);
    Ok(())
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;transform&lt;/code&gt; function represents the concurrent task. It sleeps for a random amount of seconds between 1 and 5, prints it is done, and then returns the transformed value, which in this case is just the original value passed to the function.&lt;/p&gt;

&lt;p&gt;Running the code above should give something like:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-toml&quot;&gt;Done from 1
Done from 3
Done from 6
Done from 9
Done from 5
Done from 7
Done from 0
Done from 2
Done from 4
Done from 8
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;Done from n&lt;/em&gt; shows that the tasks are finished in different ordering, but the final printing of the results is still in order, showing that even though the tasks get executed concurrently and finishes out of order, when the result is retrieved via calling `tasks.next().await` it is returned in other.&lt;/p&gt;

Another way is to collect the results into a vec. That is:

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[tokio::main]
async fn main() -&amp;gt; std::io::Result&amp;lt;()&amp;gt; {
    let mut tasks = FuturesOrdered::new();
    for n in 0..=9 {
        tasks.push_back(transform(n))
    }
    let results = tasks.collect::&amp;lt;Vec&amp;lt;i32&amp;gt;&amp;gt;().await;
    println!(&quot;{results:?}&quot;);
    Ok(())
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this, the tasks would also execute, concurrently, finish in nondeterministic order, but the results will be collected in order as the tasks were started.&lt;/p&gt;



</description><link>http://www.geekabyte.io/2024/04/futuresordered-keeping-concurrency-in.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-7172415640732343142</guid><pubDate>Fri, 05 May 2023 08:39:00 +0000</pubDate><atom:updated>2023-05-05T10:51:57.999+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Solana</category><title>Fixing &quot;Failed to get Recent Blockhash&quot; Error in Solana Development with Anchor Framework</title><description>&lt;p&gt;I took a break from exploring development in Solana, and the first thing I hit when I recently resumed again was failing tests when using the Anchor framework.&lt;/p&gt;
&lt;p&gt;Running &lt;code&gt;anchor run test&lt;/code&gt; leads to this error:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;  1) calculator
  Is initialized!:
  Error: failed to get recent blockhash: FetchError:
  request to http://localhost:8899/ failed, reason:
  connect ECONNREFUSED ::1:8899
  at Connection.getLatestBlockhash
  (node_modules/@solana/web3.js/src/connection.ts:4555:13)
  at processTicksAndRejections
  (node:internal/process/task_queues:95:5)
  at AnchorProvider.sendAndConfirm
  (node_modules/@coral-xyz/anchor/src/provider.ts:147:9)
  at MethodsBuilder.rpc [as _rpcFn]
  (node_modules/@coral-xyz/anchor/src/program/namespace/rpc.ts:29:16)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The important part of the error message is:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;Error: failed to get recent blockhash: FetchError:
request to http://localhost:8899/ failed, reason:
connect ECONNREFUSED ::1:8899
      at Connection.getLatestBlockhash
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Googling the error, I found this suggestion &lt;a href=&quot;https://github.com/solana-labs/example-helloworld/issues/392#issuecomment-1014965594&quot;&gt;here&lt;/a&gt; which says to &quot;Try using node 16 instead of 17 if you&#39;re on 17&quot;.&lt;/p&gt;
&lt;p&gt;I tried this and sure this works. But it does not feel right. &lt;code&gt;node&lt;/code&gt;&#39;s current version is 20.x, dropping down to version 16 does not feel like the most appropriate way to solve this problem.&lt;/p&gt;
&lt;p&gt;So why is the issue happening in the first place? Maybe if we understand that, we can come up with a better solution.&lt;/p&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;p&gt;Well, the reason why dropping down to version 16 works, is because, starting from version 17, node now by default resolves &quot;localhost&quot; to IPv6&#39;s ::1, not IPv4&#39;s&amp;nbsp;&lt;span style=&quot;font-family: monospace;&quot;&gt;127.0.0.1&lt;/span&gt;. Version 16 was the last version were node resolves localhost to&amp;nbsp;&lt;span style=&quot;font-family: monospace;&quot;&gt;127.0.0.1&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;And you guessed it, when you run the local Solana test validator, via &lt;code&gt;solana-test-validator&lt;/code&gt; it is automatically listening on &lt;code&gt;127.0.0.1&lt;/code&gt;. So Anchor test is trying to connect to the validator using &quot;localhost&quot;, but this resolves to an IPv6 address, but our Solana validator is listening for connections on an IPv4 address, which is&amp;nbsp;&lt;span style=&quot;font-family: monospace;&quot;&gt;127.0.0.1&lt;/span&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Now that we know the problem, a better solution then is to configure the Solana test validator to listen on the IPv6 address, or better still configure it to listen on &lt;code&gt;0.0.0.0&lt;/code&gt; which means it will be able to serve request that comes in both as IPv4 or IPv6.&lt;/p&gt;
&lt;p&gt;To do this, stop your Solana test validator if it was running and then run the following command:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;solana config set --url http://0.0.0.0:8899
// or to set to IPv6
solana config set --url http://\[::1\]:8899
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Start your test validator and run the tests, everything should work fine.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2023/05/fixing-failed-to-get-recent-blockhash.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-5830812231273580728</guid><pubDate>Mon, 23 Jan 2023 07:41:00 +0000</pubDate><atom:updated>2023-01-24T14:09:51.310+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><title>A Short Note on Types in Rust</title><description>&lt;p&gt;Types, loosely defined, are about capabilities. What are the capabilities available on a value of a certain type? Programmers experienced with strong and statically typed languages will probably have a more visceral appreciation of this, but even programmers of weakly and dynamically typed languages like JavaScript, encounter the reality of types and their capabilities; only that they do so at runtime.&lt;/p&gt;
&lt;p&gt;For example, a JavaScript developer might type out the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;3&quot;&lt;/span&gt;.&lt;span class=&quot;hljs-keyword&quot;&gt;to&lt;/span&gt;Exponential()
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But this will fail at runtime because the &quot;3&quot; is of the &lt;code&gt;String&lt;/code&gt; type and it does not have the capability to be shown as exponential. The following, on the other hand, will work seamlessly:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; (&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;).toExponential()
&#39;&lt;span class=&quot;hljs-number&quot;&gt;3e+0&lt;/span&gt;&#39;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Because 3 is of the &lt;code&gt;number&lt;/code&gt; type and the &lt;code&gt;number&lt;/code&gt; type has the capability to be formatted in exponential form.&lt;/p&gt;
&lt;p&gt;Rust extends the idea of types to now include capabilities that relate to memory management. These capabilities ensure memory safety in Rust.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
&lt;h3 id=&quot;a-short-note-on-memory&quot;&gt;A short note on memory&lt;/h3&gt;
&lt;p&gt;Dealing with memory while programming is an area that is mostly hidden from developers who have mostly worked with languages with garbage collectors. This section quickly provides a brief overview of some of the key aspects of memory management, as moving to Rust will require a deeper understanding of what is happening behind the scenes.&lt;/p&gt;
&lt;h3 id=&quot;stack-and-heap&quot;&gt;Stack and Heap&lt;/h3&gt;
&lt;p&gt;Values within a program take up memory. There are various memory regions in a computer, where values can be placed, but two of the most common regions are the &lt;em&gt;stack&lt;/em&gt; and &lt;em&gt;heap&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;You can think of the stack as a temporary memory location for values needed by an executing function. This includes function parameters and locally defined variables. Since this is more of a scratch area, access to it is fast, and once a function is done executing, the values can be discarded/overridden. Hence, the typical lifespan of a value on the stack is tied to the function that needs it for execution.&lt;/p&gt;
&lt;p&gt;The heap, on the other hand, is a memory location that is more durable, where values that are not tied to the lifetime of an executing function can be placed. Dealing with the heap is more involved for obvious reasons. The heap is not as simple as the stack, and finding space to put new values might require additional low level memory management operation needed to make such space available. The stack does not have this complexity.&lt;/p&gt;
&lt;p&gt;The idea is to limit the use of the heap region as much as possible, as it is not as fast as the stack memory region.&lt;/p&gt;
&lt;h3 id=&quot;sized-types-and-dynamically-sized-types&quot;&gt;Sized Types and Dynamically Sized Types&lt;/h3&gt;
&lt;p&gt;The type of a variable determines the type of values such a variable can contain. A consequence of this is that types also dictate how big or small the memory required by such a value is. &lt;/p&gt;
&lt;p&gt;A variable of type &lt;code&gt;u32&lt;/code&gt; can contain numeric values in the range of 0 up to 4,294,967,295, while a variable of type &lt;code&gt;u8&lt;/code&gt;, on the other hand, has a smaller size and can contain numeric values between the range of 0 and 255. This means a variable of &lt;code&gt;u32&lt;/code&gt;, will require a memory that is 32-bit long, while &lt;code&gt;u8&lt;/code&gt;, requires memory that is 8-bit in length.  &lt;/p&gt;
&lt;p&gt;Most types have a particular size, hence required memory length, that is knowable at compile time. &lt;code&gt;u8&lt;/code&gt; and &lt;code&gt;u32&lt;/code&gt; fall into this category of types. These types are called &lt;em&gt;Sized Types&lt;/em&gt;. They are guaranteed to remain uniquely the same. A type of &lt;code&gt;u32&lt;/code&gt; will always need a 32-bit length of memory regardless if it contains 0 or 4,294,967,295. The same applies to all other sized types.&lt;/p&gt;
&lt;p&gt;On the other hand, there are other types whose sizes cannot be uniquely known at compile time. &lt;/p&gt;
&lt;p&gt;One example is an array represented by &lt;code&gt;[T]&lt;/code&gt;. This type represents a certain number of &lt;code&gt;T&lt;/code&gt; in sequence, but we don’t know how many there are; it could be 0, 1, 132, or 1 million &lt;code&gt;T&#39;s&lt;/code&gt;. Hence, it is not possible to ascribe a unique size to these types at compile time. These types are known as Dynamically sized types (DST).&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;str&lt;/code&gt; type is another example of DSTs. It represents a slice of strings. But for the same reason why we cannot uniquely determine the size of &lt;code&gt;[T]&lt;/code&gt; at compile time, we also cannot determine the size of all slices of strings. Because a slice of string, represented by the type &lt;code&gt;str&lt;/code&gt; could be 0, 1, 131, or 1 million long.&lt;/p&gt;
&lt;p&gt;The idea with DSTs is not that the size is not known at compile times; they are, but they can vary, hence no unique size can be ascribed to them at compile time.&lt;/p&gt;
&lt;p&gt;The Rust compiler generally prefers to know the size of types at compile time, for various reasons such as better management and optimization. So, we have a problem here with dynamically sized types, since creating a value and annotating it with a DST won&#39;t compile.&lt;/p&gt;
&lt;p&gt;This:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn main() {
   let dst_value: str = &quot;hello world&quot;;
}&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;Will fail compilation with the following error&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;error&lt;/span&gt;[E0277]: the size &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;values&lt;/span&gt; of type `str` cannot be known &lt;span class=&quot;hljs-built_in&quot;&gt;at&lt;/span&gt; compilation &lt;span class=&quot;hljs-built_in&quot;&gt;time&lt;/span&gt;
  --&amp;gt; src/main.rs:&lt;span class=&quot;hljs-number&quot;&gt;70&lt;/span&gt;:&lt;span class=&quot;hljs-number&quot;&gt;9&lt;/span&gt;
   |
&lt;span class=&quot;hljs-number&quot;&gt;70&lt;/span&gt; |     &lt;span class=&quot;hljs-built_in&quot;&gt;let&lt;/span&gt; dst_value: str = &lt;span class=&quot;hljs-string&quot;&gt;&quot;hello world&quot;&lt;/span&gt;;
   |         ^^^^^^^^^ doesn&#39;t have a size known &lt;span class=&quot;hljs-built_in&quot;&gt;at&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;compile&lt;/span&gt;-&lt;span class=&quot;hljs-built_in&quot;&gt;time&lt;/span&gt;
   |
   = help: the trait `Sized` &lt;span class=&quot;hljs-built_in&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;not&lt;/span&gt; implemented &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; `str`
   = note: all &lt;span class=&quot;hljs-built_in&quot;&gt;local&lt;/span&gt; variables must have a statically known size
   = help: unsized locals are gated as an unstable &lt;span class=&quot;hljs-built_in&quot;&gt;feature&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The Rust compiler is kind enough to tell us why it is refusing to compile the code. A very instructive reason it gave is that &quot;all local variables must have a statically known size.&quot; &lt;/p&gt;
&lt;p&gt;So, how do we deal with this? &lt;/p&gt;
&lt;p&gt;To fully understand how we first take a look at the concepts of ownership and the borrow checker in Rust.&lt;/p&gt;
&lt;h3 id=&quot;ownership-and-copying-and-referencing-and-moving-and-borrowing&quot;&gt;Ownership, Copying, Referencing, Moving and Borrowing&lt;/h3&gt;
&lt;p&gt;Let&#39;s first look at copying and referencing. We can illustrate using Javascript.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Copying&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is one of the atomic operations performed in any programming language. You have value in one variable, you copy it into another. In Javascript:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; let &lt;span class=&quot;hljs-selector-tag&quot;&gt;a&lt;/span&gt; = &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
undefined
&amp;gt; let &lt;span class=&quot;hljs-selector-tag&quot;&gt;b&lt;/span&gt; = &lt;span class=&quot;hljs-selector-tag&quot;&gt;a&lt;/span&gt;
undefined
&amp;gt; &lt;span class=&quot;hljs-selector-tag&quot;&gt;b&lt;/span&gt;
&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
&amp;gt; &lt;span class=&quot;hljs-selector-tag&quot;&gt;b&lt;/span&gt; = &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
&amp;gt; &lt;span class=&quot;hljs-selector-tag&quot;&gt;b&lt;/span&gt;
&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
&amp;gt; &lt;span class=&quot;hljs-selector-tag&quot;&gt;a&lt;/span&gt;
&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Basically, once you have &lt;code&gt;b = a&lt;/code&gt; the value of &lt;code&gt;a&lt;/code&gt; is copied to &lt;code&gt;b&lt;/code&gt;, hence when &lt;code&gt;b&lt;/code&gt;  is modified, it does not affect the value still contained in &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Referencing&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Referencing is when multiple variables do not have their unique copy of a value, but instead point to the same value. This means that if one of the variables changes the value, the other variable will also be changed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; let a = [&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;]
undefined
&amp;gt; let b = a
undefined
&amp;gt; a.push(&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;)
&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;
&amp;gt; a
[ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt; ]
&amp;gt; b
[ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt; ]
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;To prevent creating a reference, a clone will have to be created.&lt;/p&gt;
&lt;p&gt;The concepts of copying and referencing also exist in Rust, but Rust handles them differently. Before discussing copying in Rust, let&#39;s take a look at the concepts of ownership and moving of values, which on the other hand, are unique to Rust.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Ownership and moving of values&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Rust introduces the concept of ownership and the moving of values. Simply put, it means values are not assigned to variables, rather values are owned by variables. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-meta&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; let a = &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Should now be seen as the variable &lt;code&gt;a&lt;/code&gt; was granted ownership of the value 1.&lt;/p&gt;
&lt;p&gt;It is also possible to copy a value owned by a variable, which creates another value that is owned by the other variable.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-meta&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; let a = &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;;
&amp;gt;&amp;gt; let b = a;
&amp;gt;&amp;gt; a
&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;hljs-meta&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; b
&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This should be interpreted as variable &lt;code&gt;a&lt;/code&gt; owning the value 1, then with &lt;code&gt;let b = a&lt;/code&gt;, a new copy of the value owned by the variable &lt;code&gt;a&lt;/code&gt; is created and handed over to be owned by variable &lt;code&gt;b&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The above is more or less the same behavior as the copying we saw with JavaScript.&lt;/p&gt;
&lt;p&gt;The additional feature in Rust is the concept of moving values. &lt;/p&gt;
&lt;p&gt;This means, instead of copying, a variable yields ownership of a value to another variable. As a result, once the value is moved and ownership is transferred, the old variable can no longer be used.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn main() {
   let a = String::from(&quot;Hello world&quot;);
   let b = a; // value has moved from a to b
   println!(&quot;{b}&quot;);
   println!(&quot;{a}&quot;); // this line won&#39;t make it compile
}&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;The above code won&#39;t compile. This is because with the values of type &lt;code&gt;String&lt;/code&gt;, the &lt;code&gt;let b = a line&lt;/code&gt; means the value from variable &lt;code&gt;a&lt;/code&gt; is moved to variable &lt;code&gt;b&lt;/code&gt;. That is, variable &lt;code&gt;a&lt;/code&gt; has transferred ownership to variable &lt;code&gt;b&lt;/code&gt;. Hence, trying to use the variable &lt;code&gt;a&lt;/code&gt; later on in the code by attempting to print it out won&#39;t compile.&lt;/p&gt;
&lt;p&gt;What could be confusing is the fact that in the previous example where we worked with values of type &lt;code&gt;u8&lt;/code&gt;, the behavior was copying, which is similar to what we had with JavaScript. But, when the value is of type &lt;code&gt;String&lt;/code&gt;, the value was moved! &lt;/p&gt;
&lt;p&gt;What gives?&lt;/p&gt;
&lt;p&gt;Well, it comes down to the idea of types again and their capabilities. The general idea is, types allocated on the heap generally default to moving values, while most primitive types that are placed on the stack copy instead. &lt;code&gt;String&lt;/code&gt; is a type that manages memory on the heap hence why its default capability is not to copy. To create a distinct copy of &lt;code&gt;String&lt;/code&gt; it will have to be cloned instead.&lt;/p&gt;
&lt;p&gt;It is illustrative to point out that Rust further distinguishes between &lt;em&gt;copying&lt;/em&gt; and &lt;em&gt;cloning&lt;/em&gt;. Where &lt;em&gt;copy&lt;/em&gt; can be interpreted as a simple bit-wise transfer of bits from one memory location to another while &lt;em&gt;clone&lt;/em&gt;, apart from moving bits, also require additional logic to be executed.&lt;/p&gt;
&lt;p&gt;This whole concept of moving values is something unique to Rust and new programmers coming to Rust need to be aware of this.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Borrowing and referencing of values&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Now to recreate the scenario we had in Javascript where mutating an array in one variable led to the mutation on another variable, we have the following Rust code:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn main() {
   let mut a = vec![1,2,3,4];
   let b = &amp;amp;mut a;
   b.push(5);
   println!(&quot;{a:?}&quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Variable &lt;code&gt;a&lt;/code&gt; holds a vector, but it was mutated via variable &lt;code&gt;b&lt;/code&gt; and 5 was added, and this got reflected in variable &lt;code&gt;a&lt;/code&gt;. Essentially, the same reference scenario we had with JavaScript arrays. &lt;/p&gt;
&lt;p&gt;The only difference, however, is that Rust makes referencing explicit.&lt;/p&gt;
&lt;p&gt;Let&#39;s go through the syntax. &lt;code&gt;let mut a = vec![1,2,3,4];&lt;/code&gt; grants ownership of the vector to variable &lt;code&gt;a&lt;/code&gt;. Most data structures are immutable by default in Rust, so we use the &lt;em&gt;mut&lt;/em&gt; keyword to indicate that the value owned by &lt;code&gt;a&lt;/code&gt; can be modified.&lt;/p&gt;
&lt;p&gt;Then &lt;code&gt;let b =&amp;amp;mut a;&lt;/code&gt; is where the magic happens. &lt;/p&gt;
&lt;p&gt;This, instead of moving the value from &lt;code&gt;a&lt;/code&gt; to &lt;code&gt;b,&lt;/code&gt; allows &lt;code&gt;b&lt;/code&gt; to &lt;em&gt;borrow&lt;/em&gt; the value instead. &lt;/p&gt;
&lt;p&gt;This form of borrowing is achieved by creating a reference and handing that over to &lt;code&gt;b.&lt;/code&gt; &lt;/p&gt;
&lt;p&gt;The syntax &lt;code&gt;&amp;amp;mut&lt;/code&gt; is used to achieve this, and the &lt;code&gt;mut&lt;/code&gt; keyword indicates that it is possible to mutate the value through this reference.&lt;/p&gt;
&lt;p&gt;It is possible to borrow a value, i.e. create a reference to a value but not be able to mutate the value. Sort of a read-only. In such a scenario, you only use &lt;code&gt;&amp;amp;&lt;/code&gt; for example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn main() {
   let mut a = vec![1,2,3,4];
   let b = &amp;amp;a;
   println!(&quot;{b:?}&quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But there are certain things you can and cannot do depending on if a value is owned, moved, borrowed, mutable, or immutable. These whole classes of restrictions are there to ensure memory safety, and this is what the borrow checker enforces.&lt;/p&gt;
&lt;p&gt;In summary, the borrow checker ensures: 
you can have multiple read-only references to the same memory location as long as there are no mutable references. 
If a mutable reference is created to a memory location, it is only this mutable reference that can read from and write to the memory location.&lt;/p&gt;
&lt;p&gt;To get a more elaborate exploration of the rules the borrow checker enforces, see
 &lt;a href=&quot;https://www.geekabyte.io/2020/02/rust-ownership-rules.html&quot;&gt;Rust Ownership Rules&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;introduction-to-pointers-and-using-references-to-work-with-dst&quot;&gt;Introduction to Pointers and using References to work with DST&lt;/h3&gt;
&lt;p&gt;DSTs were already introduced as types that do not have a unique size at compile time, and as mentioned above, Rust prefers to deal with types it can know their size at compile time. So, how does Rust work with DSTs? To understand this, we need to talk about pointers.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pointers and References in Rust&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pointers are variables, just like any other type of variable, but their values hold the memory address of other variables. They are an indirection that points to the memory location where another value can be found.&lt;/p&gt;
&lt;p&gt;In Rust, pointers also have types, which makes sense since one can imagine, specific capabilities are only available to pointers. Pointers can also be found in languages like C and C++, but they can be difficult, and unsafe to work with due to the potential for misusing the unhindered access to memory locations. &lt;/p&gt;
&lt;p&gt;This is the reason in Rust, you hardly deal with pointers directly. Instead, you have references, which are pointers with safety or liveness guarantees. &lt;/p&gt;
&lt;p&gt;You can think of them as a protective layer that makes working with pointers safer. Pointers that are not references, i.e. that don&#39;t have this protective guarantee in Rust are usually called &lt;em&gt;raw pointers&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The thing with references is that they also have types, and the good thing about them, is that they have a known size. This is because references hold memory addresses, hence it is possible to have a constant bit length that will always be assigned to references, big enough to enable it to store whatever memory address it needs to store. &lt;/p&gt;
&lt;p&gt;Sometimes extra meta-information about the value in the memory address they point to is also stored, when this is the case, the reference is usually called a &lt;em&gt;fat pointer&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The syntax for creating references is &lt;code&gt;&amp;amp;T&lt;/code&gt;. To create a reference to a type &lt;code&gt;T&lt;/code&gt;, use &lt;code&gt;&amp;amp;T&lt;/code&gt;. For example, in the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
fn main() {
   let phone_code: HashMap&amp;lt;String, u8&amp;gt; = HashMap::from([(&quot;NL&quot;.to_string(), 31), (&quot;USA&quot;.to_string(), 1)]);
   let ref_to_phone_code: &amp;amp;HashMap&amp;lt;String, u8&amp;gt; = &amp;amp;phone_code;
   dbg!(ref_to_phone_code);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;phone_code&lt;/code&gt; is of the type &lt;code&gt;HashMap&amp;lt;String, u8&amp;gt;&lt;/code&gt;, but &lt;code&gt;ref_to_phone_code&lt;/code&gt;, a reference, is of the type &lt;code&gt;&amp;amp;HashMap&amp;lt;String, u8&amp;gt;&lt;/code&gt; - notice the ampersand now in the type.&lt;/p&gt;
&lt;p&gt;Also, the value of the type &lt;code&gt;&amp;amp;HashMap&amp;lt;String, u8&amp;gt;&lt;/code&gt; was created by appending &lt;code&gt;&amp;amp;&lt;/code&gt; to the variable it will reference, that is &lt;code&gt;&amp;amp;phone_code&lt;/code&gt; in the code above.&lt;/p&gt;
&lt;p&gt;Rust uses references to work with DSTs. Since references are types with known size at compile time, the trick is to only allow interaction with DSTs via references to them. This is why annotating a type with &lt;code&gt;str&lt;/code&gt;, a DST, will cause a compilation failure, but &lt;code&gt;&amp;amp;str&lt;/code&gt;, a reference to a DST, compiles fine.&lt;/p&gt;
&lt;h3 id=&quot;in-summary-t-sized-and-dst-t-and-mut-t&quot;&gt;In Summary: T (Sized and DST), &amp;amp;T and &amp;amp;mut T&lt;/h3&gt;
&lt;p&gt;As mentioned at the beginning of this post, types are about encoding capabilities allowed with a value. Rust extends this to encompass capabilities related to memory management and layout.&lt;/p&gt;
&lt;p&gt;So a type &lt;code&gt;T&lt;/code&gt; can exist in one of two flavors: One where its memory size is always known to be of a particular bit length; these are called &lt;em&gt;Sized Types&lt;/em&gt;, and the ones whose size/bit length is not unique and can vary; these are called Dynamically Sized Types.&lt;/p&gt;
&lt;p&gt;Then you have references, which are pointers (variables that hold memory location) with guarantees that ensure safe memory access. &lt;/p&gt;
&lt;p&gt;These guarantees are enforced by the borrow checker. &lt;/p&gt;
&lt;p&gt;These references could be of type &lt;code&gt;&amp;amp;T&lt;/code&gt; or &lt;code&gt;&amp;amp;mut T&lt;/code&gt;, depending on whether the reference is mutable or not. If type &lt;code&gt;T&lt;/code&gt; is a DST, then a variable of type &lt;code&gt;&amp;amp;T&lt;/code&gt; (or &lt;code&gt;&amp;amp;mut T&lt;/code&gt;) can be used to reference the DST.&lt;/p&gt;
&lt;h3 id=&quot;resources&quot;&gt;Additional Resources&lt;/h3&gt;
&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;&lt;a href=&quot;https://denniskubes.com/2017/01/24/the-5-minute-guide-to-c-pointers/&quot;&gt;The 5-Minute Guide to C Pointers&lt;/a&gt;&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://doc.rust-lang.org/reference/types/pointer.html&quot;&gt;Pointer Types&lt;/a&gt;&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://www.geekabyte.io/2020/02/rust-ownership-rules.html&quot;&gt;Rust Ownership Rules&lt;/a&gt;&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rDoqT-a6UFg&quot;&gt;Visualizing memory layout of Rust&#39;s data types&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;/p&gt;
</description><link>http://www.geekabyte.io/2023/01/a-short-note-on-types-in-rust.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-4086175434880942798</guid><pubDate>Tue, 11 Oct 2022 17:11:00 +0000</pubDate><atom:updated>2022-10-11T19:14:10.723+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><title>Introduction to Declarative Macros in Rust</title><description>&lt;p&gt;This post will give a quick overview of declarative macros in Rust. If you are not familiar with the concepts of macros in Rust, then read &lt;a href=&quot;https://www.geekabyte.io/2022/10/introduction-to-macros-in-rust.html&quot;&gt;Introduction to Macros in Rust&lt;/a&gt; first.&lt;/p&gt;
&lt;p&gt;Declarative macros work similar to how pattern matching works. It involves taking inputs, then pattern matching to determine what logic to execute. &lt;/p&gt;
&lt;p&gt;The macros definition for creating declarative macros, then contains rules which determine the Rust code that gets generated/executed based on the pattern. &lt;/p&gt;
&lt;p&gt;This is why declarative macros are also sometimes referred to as &lt;em&gt;Macros By Example&lt;/em&gt;, as the code that is generated depends on the example of patterns that matches.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Rust provides the &lt;code&gt;macro_rules!&lt;/code&gt; macro for defining declarative macros. You use the &lt;code&gt;macro_rules!&lt;/code&gt; to specify the input string pattern and also to specify the code that gets generated/executed.&lt;/p&gt;
&lt;p&gt;The syntax for &lt;code&gt;macro_rules&lt;/code&gt; takes the following form:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;macro_rules! $name {
    ($matcher) =&amp;gt; {$expansion} ;
    ($matcher) =&amp;gt; {$expansion} ;
    &lt;span class=&quot;hljs-comment&quot;&gt;// …&lt;/span&gt;
   ($matcher) =&amp;gt; {$expansion} ;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That is, the &lt;code&gt;macro_rules&lt;/code&gt; definition contains a list of rules, the particular rule, represented by &lt;code&gt;{$expression}&lt;/code&gt; that will be executed depends on which of the &lt;code&gt;($matcher)&lt;/code&gt; matches the input.
To see this syntax in action, create a new cargo project by running&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cargo &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; declarative_macros
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Open the &lt;code&gt;main.rs&lt;/code&gt; and edit it.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;$matcher&lt;/code&gt; can be a simple literal match. For example to create a macro that prints different message based on whether the input passed to it is &quot;morning&quot; or &quot;evening&quot; , add the code below to &lt;code&gt;main.rs&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn main() {

    #[macro_export]
    macro_rules! greet {
        (&quot;morning&quot;) =&amp;gt; {
            println!(&quot;Good morning! Have a nice day!&quot;);
        };
        (&quot;evening&quot;) =&amp;gt; {
            println!(&quot;Good evening! Sleep tight!&quot;);
        }
    }
}
// using it
#[test]
fn run_greet() {
    // prints &quot;Good morning! Have a nice day!&quot;
    greet!(&quot;morning&quot;); 
    // prints &quot;Good evening! Sleep tight!&quot;
    greet!(&quot;evening&quot;);
}&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;The &lt;code&gt;$match&lt;/code&gt; can be more versatile than just matching a literal. For example the match can be used to define that the input should be an expression, a block of code etc. It can also be used to capture values passed in, that are then used within the macro logic.&lt;/p&gt;
&lt;p&gt;To demonstrate how using a more versatile match pattern looks like when defining declarative macros, we write one that retrieves the balances for specified Solana accounts.&lt;/p&gt;
&lt;p&gt;For this to work, update the dependencies section in &lt;code&gt;Cargo.toml&lt;/code&gt; as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-section&quot;&gt;[dependencies]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;solana-client&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1.8.1, &amp;lt; 1.11&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;solana-program&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1.8.1, &amp;lt; 1.11&quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then update the &lt;code&gt;main.rs&lt;/code&gt; file as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use solana_client::rpc_client::RpcClient;
use solana_program::pubkey::Pubkey;
use std::str::FromStr;

fn main() {
 #[macro_export]
 macro_rules! sol_balance {
  ($item:expr) =&amp;gt; {
    {
     let mut result: Vec&amp;lt;u64&amp;gt; = Vec::new();
     let rpc = RpcClient::new(&quot;https://api.devnet.solana.com&quot;
               .to_string());
     let item_str = format!(&quot;{}&quot;, $item);
     for i in item_str.split(&quot;,&quot;) {
         result.push(rpc.get_account(
         &amp;amp;Pubkey::from_str(i.trim()).unwrap()
         ).unwrap().lamports);
       }
       result
     }
  }}

}

#[test]
fn run_macros() {
    let result = sol_balance!(
        &quot;4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU,
        HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny&quot;
    );
    dbg!(result);
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Running the test would print out the sol balance at the specified account.
Let&#39;s go over the code above. The core structure of the macro is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    &lt;span class=&quot;hljs-comment&quot;&gt;#[macro_export]&lt;/span&gt;
    macro_rules! sol_balance {
        (&lt;span class=&quot;hljs-variable&quot;&gt;$item&lt;/span&gt;&lt;span class=&quot;hljs-symbol&quot;&gt;:expr&lt;/span&gt;) =&amp;gt; {
        &lt;span class=&quot;hljs-regexp&quot;&gt;//&lt;/span&gt; body of macro
    }}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;($item:expr)&lt;/code&gt; is an example of a more versatile match. It still corresponds to the &lt;code&gt;($matcher)&lt;/code&gt; in &lt;code&gt;($matcher) =&amp;gt; {$expansion}&lt;/code&gt;. The &lt;code&gt;$item&lt;/code&gt; is the input that is being matched, but this time around it is not just a literal. This syntax also captures the input making its value available for use in the macro code. This is called Metavariables. It also contains a qualification part using &lt;code&gt;:expr&lt;/code&gt;. This is used to categorize the input. The &lt;code&gt;:expr&lt;/code&gt; is an example of a fragment specifier. &lt;code&gt;:expr&lt;/code&gt; specifies that the input is an expression. Other fragment specifiers exist. See &lt;a href=&quot;https://veykril.github.io/tlborm/decl-macros/minutiae/fragment-specifiers.html&quot;&gt;Fragment Specifiers&lt;/a&gt; for more information.&lt;/p&gt;
&lt;p&gt;The body of the macro is then defined as:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
  let mut result: Vec&amp;amp;lt;u64&amp;amp;gt; = Vec::new();
  let rpc = RpcClient::new(&quot;https://api.devnet.solana.com&quot;
            .to_string());
  let item_str = format!(&quot;{}&quot;, $item);
  for i in item_str.split(&quot;,&quot;) {
      result.push(rpc.get_account(
      &amp;amp;amp;Pubkey::from_str(i.trim()).unwrap()
      ).unwrap().lamports);
     }
  result
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that we wrap this within &lt;code&gt;{}&lt;/code&gt; to allow using multiple statements.&lt;/p&gt;
&lt;p&gt;It is also possible to support repetition when defining the matcher. This take the form of:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-variable&quot;&gt;$ &lt;/span&gt;( &lt;span class=&quot;hljs-variable&quot;&gt;$(&lt;/span&gt;matcher) ) separator repmode
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You can read this as &lt;code&gt;$(matcher)&lt;/code&gt; as the pattern to be repeated, the &lt;code&gt;separator&lt;/code&gt; that delineates the repetition, and &lt;code&gt;repmode&lt;/code&gt; determines the number of repetition that is expected.&lt;/p&gt;
&lt;p&gt;The currently supported &lt;code&gt;repmode&lt;/code&gt; are:&lt;/p&gt;
&lt;p&gt;?: at most one repetition
*: zero or more repetitions
+: one or more repetitions&lt;/p&gt;
&lt;p&gt;The same syntax is used to process each item that is repeated. To see this repetition in practice, we can update the &lt;code&gt;sol_balance&lt;/code&gt; macro to take a list of accounts separated by &quot;;&quot; instead of taking a single string separated by &quot;,&quot;. This will look like:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use solana_client::rpc_client::RpcClient;
use solana_program::pubkey::Pubkey;
use std::str::FromStr;

fn main() {

 #[macro_export]
 macro_rules! sol_balance {
   ($($item:expr);*) =&amp;gt; {
     {
       let mut result: Vec&amp;lt;u64&amp;gt; = Vec::new();

       let rpc = RpcClient::new(&quot;https://api.devnet.solana.com&quot;
                 .to_string());
         $(
           let item_str = format!(&quot;{}&quot;, $item);
           result.push(rpc.get_account(
           &amp;amp;Pubkey::from_str(item_str.trim()).unwrap()
           ).unwrap().lamports);
          )*
          result
       }
    }}
}

// usage

#[test]
fn run_macros() {
  let result = sol_balance!(
    &quot;4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU&quot;
     ;
     &quot;HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny&quot;
   );
  dbg!(result);
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Running the test with the code modified as above should also print the sol balance at the given accounts.&lt;/p&gt;
&lt;p&gt;There is more to writing a declarative macros that is not touched upon in this overview. For example we did not talk about the &lt;code&gt;#[macro_export]&lt;/code&gt; attribute, neither did we talk about things like Metavariable Expressions. Even at this, this introduction should be enough to understand the essence of declarative Macros in Rust.&lt;/p&gt;
&lt;p&gt;The next post in this series will then be an introduction to the function-like procedural macros. &lt;/p&gt;
</description><link>http://www.geekabyte.io/2022/10/introduction-to-declarative-macros-in.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-1545281428742517635</guid><pubDate>Mon, 10 Oct 2022 12:38:00 +0000</pubDate><atom:updated>2023-08-27T14:52:02.698+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><title>Introduction to Macros In Rust</title><description>&lt;p&gt;This guide will present an overview of the fundamentals a new developer approaching macros in Rust needs to know. If you have read other materials online and you still find the concept of macros in Rust vague, then this post is for you.&lt;/p&gt;
&lt;p&gt;The guide will be broken into 4 series of posts. The first post, which is this post, will be a quick overview of macros in Rust. The following 3 posts will then look more deeply into the different types of macros in Rust and how to create them.&lt;/p&gt;
&lt;p&gt;The posts in this series are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Introduction to macros in Rust (this post)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.geekabyte.io/2022/10/introduction-to-declarative-macros-in.html&quot;&gt;Introduction to declarative macros in Rust&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Introduction to attribute-like procedural macros in Rust (yet to be published)&lt;/li&gt;
&lt;li&gt;Introduction to function-like procedural macros in Rust (yet to be published)&lt;/li&gt;
&lt;li&gt;Introduction to custom-derive procedural macros in Rust (yet to be published)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;what-are-macros&quot;&gt;What are macros&lt;/h3&gt;
&lt;p&gt;Macros are mechanisms for generating or manipulating code programmatically at compile time. In essence, it allows us to treat source code as values. Meaning that, at compile time, we can take inputs: where the input could be another source code or some defined string pattern, and from these inputs, manipulate and generate source codes that form the final compiled code that will be executed.&lt;/p&gt;
&lt;p&gt;Macros as a concept are not specific to Rust, as they can be found in languages like Lisp, C/C++, Scala, and a host of others. Although one clear distinction of macros in Rust is that it provides type safety. Meaning that it provides mechanisms to prevent generating programs or source code that are not type-safe.&lt;/p&gt;
&lt;p&gt;That is what macros are in a nutshell, a mechanism for taking inputs (other source codes, or just string patterns) and using these to generate source code/program at compile time.&lt;/p&gt;
&lt;p&gt;So now that we know what macros are, we talk about how macro usage looks like.&lt;/p&gt;
&lt;h3 id=&quot;what-does-macros-usage-look-like-in-rust-&quot;&gt;What does macros usage look like in Rust?&lt;/h3&gt;
&lt;p&gt;Before looking at how to create macros in Rust, it is instructive to see how already created macros are used.&lt;/p&gt;
&lt;p&gt;There are two distinct ways of making use of macros in Rust. macros are either used via 
A syntax I call bang function syntax 
or via attribute syntax. &lt;/p&gt;
&lt;p&gt;The bang function syntax is the syntax that looks like a function call but with an exclamation mark at the end of the function name. For example things like: &lt;code&gt;println!()&lt;/code&gt;, &lt;code&gt;dbg!()&lt;/code&gt;, &lt;code&gt;format!()&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;These are used to invoke macros and are not normal function calls. &lt;/p&gt;
&lt;p&gt;Attributes syntax, on the other hand, is the syntax used for annotation. It takes the form of &lt;code&gt;#[..]&lt;/code&gt; or &lt;code&gt;#![..]&lt;/code&gt; and they can be placed on various language elements like functions, structs, enums, etc. This is another syntax that can be used to invoke macros. &lt;/p&gt;
&lt;p&gt;A real-world example of attribute syntax being used to invoke macros can be found in the web framework called &lt;a href=&quot;https://rocket.rs/&quot;&gt;rocket&lt;/a&gt;. For example in the code below, gotten from the documentation &lt;a href=&quot;https://api.rocket.rs/v0.5-rc/rocket/attr.get.html&quot;&gt;here&lt;/a&gt; where we see the definition of a handler for  the &lt;code&gt;/&lt;/code&gt; HTTP path:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[get(&lt;span class=&quot;hljs-meta-string&quot;&gt;&quot;/&quot;&lt;/span&gt;)]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;index&lt;/span&gt;&lt;/span&gt;() -&amp;gt; &amp;amp;&lt;span class=&quot;hljs-symbol&quot;&gt;&#39;static&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;str&lt;/span&gt; {
    &lt;span class=&quot;hljs-string&quot;&gt;&quot;Hello, world!&quot;&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;#[get(&quot;/&quot;)]&lt;/code&gt; syntax is invoking a macro defined by the rocket framework. This invocation means that at compile time, the custom &lt;code&gt;get&lt;/code&gt; macro will take the function &lt;code&gt;index()&lt;/code&gt; as input, process it, and generate the exact source code, the framework needs to be able to call this function in response to an HTTP GET request to the path &lt;code&gt;/&lt;/code&gt;. Essentially fulfilling what a macro is: a mechanism to generate source code at compile time.&lt;/p&gt;
&lt;p&gt;The exact syntax used to call a macro depends on the type of macro and how it has been created. Some macro types are called via the bang function syntax, while other kinds are called via the attribute syntax.&lt;/p&gt;
&lt;h3 id=&quot;types-of-rust-macros-&quot;&gt;Types of Rust macros.&lt;/h3&gt;
&lt;p&gt;In Rust, there are two types of macros: Declarative macros and Procedural macros. There are then 3 subcategories of procedural macros: Custom-derive macros, Attribute-like macros, and Function-like macros.&lt;/p&gt;
&lt;p&gt;Basically types of Rust macros:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Declarative macros (also referred to as macro by example or mbe for short)&lt;/li&gt;
&lt;li&gt;Procedural macros&lt;ul&gt;
&lt;li&gt;Function-like&lt;/li&gt;
&lt;li&gt;Attribute-like macros&lt;/li&gt;
&lt;li&gt;Custom derive macros&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The first thing to note in this categorisation is what makes declarative macros different from procedural Macros. &lt;/p&gt;
&lt;p&gt;The difference lies in their inputs and outputs, and also how they are created and used. &lt;/p&gt;
&lt;p&gt;Declarative macros take what can be described as token fragments while procedural macros take &lt;code&gt;TokenStream&lt;/code&gt; as inputs. Token fragments are like string patterns that can further be qualified by a fragment specifier that tells what kind they are. Fragment specifiers can be used to specify the inputs are block, expression, statement, etc. See &lt;a href=&quot;https://veykril.github.io/tlborm/decl-macros/minutiae/fragment-specifiers.html&quot;&gt;Fragment Specifiers&lt;/a&gt; for an overview of the supported fragment specifiers.&lt;/p&gt;
&lt;p&gt;Procedural macros, on the other hand, take in &lt;code&gt;TokenStream&lt;/code&gt; which is a more low-level representation of the source code. &lt;/p&gt;
&lt;p&gt;The other difference between declarative macros and procedural macros (also the difference between the 3 kinds of procedural macros) is how they are created and used.&lt;/p&gt;
&lt;p&gt;Declarative macros and function-like procedural macros are used by a syntax that looks like function invocation but ends with !. for example &lt;code&gt;do_work!()&lt;/code&gt;. Meaning when looking at usage it is not possible to tell if a declarative macro is being used or a function-like procedural macro is.&lt;/p&gt;
&lt;p&gt;Attribute-like procedural macros on the other hand are used to create a custom annotation, so they are used with the syntax of applying attributes. That is: &lt;code&gt;#[my_macro]&lt;/code&gt;. They can also be defined to take helper attributes. That is &lt;code&gt;#[my_macro(attr)]&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;While custom derives macros are used to define new values that can be passed into the &lt;code&gt;#[derive(...)]&lt;/code&gt; macro. For example, if &lt;code&gt;MyMacro&lt;/code&gt; is defined to be a custom derive macro, it can then be used as &lt;code&gt;#[derive(MyMacro)]&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;This completes the quick overview of macros in Rust. The following posts in the series will then go into the details of how these different types of macros are created and used and their different peculiarities.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2022/10/introduction-to-macros-in-rust.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-208720466664995450</guid><pubDate>Wed, 28 Sep 2022 03:22:00 +0000</pubDate><atom:updated>2022-09-29T19:04:26.136+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><category domain="http://www.blogger.com/atom/ns#">Solana</category><title>How to query account balance on Solana using Rust.</title><description>&lt;p&gt;This post shows how to query Solana&#39;s cluster rpc endpoint using Rust. Most of the examples of how to perform this task that I ran to uses Javascript/Typescript via the &lt;a href=&quot;https://github.com/solana-labs/solana-web3.js&quot;&gt;Solana Web3js library&lt;/a&gt;, so I decided to do a quick post showing how to do same but in Rust. It uses querying for the sol balance of a Solana account as the main example of interaction with the rpc endpoint.&lt;/p&gt;
&lt;p&gt;The task is simple: given a Solana address, we retrieve the sol balance for that address. &lt;/p&gt;
&lt;p&gt;To get started we will need the following dependencies:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[dependencies]
solana-client = &quot;1.14.3&quot; // &lt;span class=&quot;hljs-keyword&quot;&gt;update&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;to&lt;/span&gt; the &lt;span class=&quot;hljs-keyword&quot;&gt;current&lt;/span&gt; latest &lt;span class=&quot;hljs-keyword&quot;&gt;version&lt;/span&gt;
solana-sdk = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1.14.3&quot;&lt;/span&gt; // &lt;span class=&quot;hljs-keyword&quot;&gt;update&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;to&lt;/span&gt; the &lt;span class=&quot;hljs-keyword&quot;&gt;current&lt;/span&gt; latest &lt;span class=&quot;hljs-keyword&quot;&gt;version&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The code snippet below then shows how to call the rpc endpoint and retrieve the Sol balance for an account&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use solana_client::rpc_client::RpcClient;
use solana_program::pubkey::Pubkey;
use std::str::FromStr;

fn main() {
 let rpc = RpcClient::new(&quot;https://api.devnet.solana.com&quot;);
 let pubkey_str = &quot;4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU&quot;;

 let balance = rpc
      .get_account(&amp;Pubkey::from_str(pubkey_str).unwrap())
      .unwrap().lamports;

 println!(&quot;Sol balance of {pubkey_str} is {balance}&quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Solana addresses are &lt;a href=&quot;https://learnmeabitcoin.com/technical/base58&quot;&gt;base58&lt;/a&gt; encoded strings, hence they need to be first converted into an instance of &lt;code&gt;Pubkey&lt;/code&gt; before they can be used in the &lt;code&gt;rpc.get_account&lt;/code&gt; call, which expects a &lt;code&gt;&amp;amp;[u8]&lt;/code&gt; byte array. To help with this conversion, &lt;code&gt;Pubkey&lt;/code&gt; implements the &lt;code&gt;std::str::FromStr&lt;/code&gt; trait. This wmeans, if the trait &lt;code&gt;std::str::FromStr&lt;/code&gt; is in scope, then it is possible to convert a string to &lt;code&gt;Pubkey&lt;/code&gt;, which is what was done in the code snippet above.&lt;/p&gt;
&lt;p&gt;This post was inspired by a recent question I answered on Solana stack exchange &lt;a href=&quot;https://solana.stackexchange.com/questions/3414/how-to-use-solana-rust-client-to-request-sol-balance/&quot;&gt;here&lt;/a&gt;. The answer also mentions another verbose alternative that involves manually converting from base58 to bytes array.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2022/09/how-to-query-account-balance-on-solana.html</link><author>noreply@blogger.com (dade)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-4820375311101189030</guid><pubDate>Sat, 13 Aug 2022 17:41:00 +0000</pubDate><atom:updated>2022-08-23T15:15:01.256+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><title>IntoIterator and the for ... in Syntax in Rust</title><description>&lt;p&gt;In &lt;a href=&quot;https://www.geekabyte.io/2022/08/rust-iterator-pattern-with-iter.html&quot;&gt;Rust Iterator pattern with iter(), into_iter() and iter_mut() methods&lt;/a&gt; I explained why attempting to use a variable holding a &lt;code&gt;Vec&lt;/code&gt; after iterating through it using the &lt;code&gt;for … in&lt;/code&gt; syntax leads to a compilation error. &lt;/p&gt;
&lt;p&gt;The post explains why the following code won&#39;t compile:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
  &lt;span class=&quot;hljs-comment&quot;&gt;// iterating through a vec&lt;/span&gt;
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints {
       dbg!(i);
   }
&lt;span class=&quot;hljs-comment&quot;&gt;// attempting to use the vec will &lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// lead to compile error after the iteration&lt;/span&gt;
   dbg!(some_ints);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I then showed 3 methods that can be called before iterating using the &lt;code&gt;for … in&lt;/code&gt; and how 2 of these methods allow the &lt;code&gt;Vec&lt;/code&gt; to still be used even after iteration. &lt;/p&gt;
&lt;p&gt;These 3 methods are &lt;code&gt;into_iter()&lt;/code&gt;, &lt;code&gt;iter()&lt;/code&gt;, and &lt;code&gt;iter_mut()&lt;/code&gt;.  That is:&lt;/p&gt;
&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[test]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;into_iter_demo&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-comment&quot;&gt;// the .into_iter() method creates an iterator, v1_iter 
    // which takes ownership &lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;of the values being iterated.&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; v1_iter = v1.into_iter();

    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;);

    &lt;span class=&quot;hljs-comment&quot;&gt;// If the line below is uncommented, the code won&#39;t compile anymore&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// this is because, after the iteration, v1 can no longer be used &lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// since the iteration moved ownership&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;//dbg!(v1);&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The two other methods that allow the &lt;code&gt;Vec&lt;/code&gt; to still be used after iteration via &lt;code&gt;for … in&lt;/code&gt; are:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[test]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;iter_demo&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v1 = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
    &lt;span class=&quot;hljs-comment&quot;&gt;// the .iter() method creates an iterator, 
    // v1_iter which borrows value immutably &lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; v1_iter = v1.iter();

    &lt;span class=&quot;hljs-comment&quot;&gt;// iter() returns an iterator of slices.&lt;/span&gt;
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;);
   &lt;span class=&quot;hljs-comment&quot;&gt;// because values were borrowed immutably, 
   // it is still possible to use 
   // the vec after iteration is done&lt;/span&gt;
    dbg!(v1);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[test]
&lt;span class=&quot;hljs-symbol&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;iter_mut_demo() &lt;/span&gt;{
    let mut &lt;span class=&quot;hljs-built_in&quot;&gt;v1&lt;/span&gt; = vec![&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;]&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // the .&lt;span class=&quot;hljs-keyword&quot;&gt;iter_mut() &lt;/span&gt;method creates an &lt;span class=&quot;hljs-keyword&quot;&gt;iterator, 
&lt;/span&gt;    // v1_iter which &lt;span class=&quot;hljs-keyword&quot;&gt;borrows &lt;/span&gt;value &lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;can mutate &lt;span class=&quot;hljs-keyword&quot;&gt;it. &lt;/span&gt;
    let mut v1_iter = &lt;span class=&quot;hljs-built_in&quot;&gt;v1&lt;/span&gt;.&lt;span class=&quot;hljs-keyword&quot;&gt;iter_mut();
&lt;/span&gt;
    // access the first &lt;span class=&quot;hljs-keyword&quot;&gt;item &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;multiple &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;it &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;by &lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
    let &lt;span class=&quot;hljs-keyword&quot;&gt;item1 &lt;/span&gt;= v1_iter.next().unwrap()&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    *&lt;span class=&quot;hljs-keyword&quot;&gt;item1 &lt;/span&gt;= *&lt;span class=&quot;hljs-keyword&quot;&gt;item1 &lt;/span&gt;* &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // access the second &lt;span class=&quot;hljs-keyword&quot;&gt;item &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;multiple &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;it &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;by &lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
    let &lt;span class=&quot;hljs-keyword&quot;&gt;item2 &lt;/span&gt;= v1_iter.next().unwrap()&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    *&lt;span class=&quot;hljs-keyword&quot;&gt;item2 &lt;/span&gt;= *&lt;span class=&quot;hljs-keyword&quot;&gt;item2 &lt;/span&gt;* &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // access the third &lt;span class=&quot;hljs-keyword&quot;&gt;item &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;multiple &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;it &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;by &lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
    let &lt;span class=&quot;hljs-keyword&quot;&gt;item3 &lt;/span&gt;= v1_iter.next().unwrap()&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    *&lt;span class=&quot;hljs-keyword&quot;&gt;item3 &lt;/span&gt;= *&lt;span class=&quot;hljs-keyword&quot;&gt;item3 &lt;/span&gt;* &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // &lt;span class=&quot;hljs-meta&quot;&gt;end&lt;/span&gt; of the &lt;span class=&quot;hljs-keyword&quot;&gt;iteration
&lt;/span&gt;    assert_eq!(v1_iter.next(), None)&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // this will print out [&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;6&lt;/span&gt;]
    &lt;span class=&quot;hljs-keyword&quot;&gt;dbg!(v1);
&lt;/span&gt;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In this post, we are going to dive a little bit deeper into understanding some of the machinery that makes the above work. &lt;/p&gt;
&lt;p&gt;We start again by talking about the &lt;code&gt;Iterator&lt;/code&gt; trait.&lt;br /&gt;&lt;/p&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;
&lt;h3 id=&quot;iterator-pattern-and-iterator-trait-&quot;&gt;Iterator pattern and Iterator trait.&lt;/h3&gt;
&lt;p&gt;An &lt;code&gt;Iterator&lt;/code&gt; represents the ability to retrieve elements from another data structure in sequence. In rust, it is any data structure that implements the &lt;code&gt;Iterator&lt;/code&gt; trait.&lt;/p&gt;
&lt;p&gt;It is important to note that the &lt;code&gt;Vec&lt;/code&gt; data structure by itself is not an &lt;code&gt;Iterator&lt;/code&gt; and hence cannot be iterated. &lt;/p&gt;
&lt;p&gt;To make this more obvious, let us forget about the &lt;code&gt;for … in&lt;/code&gt; syntax for a second, and try to perform an operation that should be possible on a data structure that supports being iterated. &lt;/p&gt;
&lt;p&gt;An example of such an operation is the &lt;code&gt;for_each&lt;/code&gt; method. &lt;/p&gt;
&lt;p&gt;In the code example below, we attempt to loop directly over a &lt;code&gt;Vec&lt;/code&gt; of numbers using &lt;code&gt;for_each&lt;/code&gt; and print each item. The code won&#39;t compile:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   &lt;span class=&quot;hljs-comment&quot;&gt;// calling for_each directly on a Vec won&#39;t compile&lt;/span&gt;
   some_ints.for_each(|item| {
       dbg!(item);
   });
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The compile error below gives us a clue as to why the code does not compile:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;error&lt;/span&gt;[E0599]: `Vec&amp;lt;{&lt;span class=&quot;hljs-built_in&quot;&gt;integer&lt;/span&gt;}&amp;gt;` &lt;span class=&quot;hljs-keyword&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;not&lt;/span&gt; an iterator
  &lt;span class=&quot;hljs-comment&quot;&gt;--&amp;gt; src/main.rs:60:14&lt;/span&gt;
   |
&lt;span class=&quot;hljs-number&quot;&gt;60&lt;/span&gt; |      some_ints.for_each(|&lt;span class=&quot;hljs-built_in&quot;&gt;item&lt;/span&gt;| {
   |                ^^^^^^^^ `Vec&amp;lt;{&lt;span class=&quot;hljs-built_in&quot;&gt;integer&lt;/span&gt;}&amp;gt;` &lt;span class=&quot;hljs-keyword&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;not&lt;/span&gt; an iterator; &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; calling `.into_iter()` &lt;span class=&quot;hljs-keyword&quot;&gt;or&lt;/span&gt; `.iter()`
   |
   = note: &lt;span class=&quot;hljs-keyword&quot;&gt;the&lt;/span&gt; following trait bounds were &lt;span class=&quot;hljs-keyword&quot;&gt;not&lt;/span&gt; satisfied:
           `Vec&amp;lt;{&lt;span class=&quot;hljs-built_in&quot;&gt;integer&lt;/span&gt;}&amp;gt;: Iterator`
           which &lt;span class=&quot;hljs-keyword&quot;&gt;is&lt;/span&gt; required &lt;span class=&quot;hljs-keyword&quot;&gt;by&lt;/span&gt; `&amp;amp;mut Vec&amp;lt;{&lt;span class=&quot;hljs-built_in&quot;&gt;integer&lt;/span&gt;}&amp;gt;: Iterator`
           `[{&lt;span class=&quot;hljs-built_in&quot;&gt;integer&lt;/span&gt;}]: Iterator`
           which &lt;span class=&quot;hljs-keyword&quot;&gt;is&lt;/span&gt; required &lt;span class=&quot;hljs-keyword&quot;&gt;by&lt;/span&gt; `&amp;amp;mut [{&lt;span class=&quot;hljs-built_in&quot;&gt;integer&lt;/span&gt;}]: Iterator`

For more information &lt;span class=&quot;hljs-keyword&quot;&gt;about&lt;/span&gt; this &lt;span class=&quot;hljs-keyword&quot;&gt;error&lt;/span&gt;, &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; `rustc &lt;span class=&quot;hljs-comment&quot;&gt;--explain E0599`.&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;error&lt;/span&gt;: could &lt;span class=&quot;hljs-keyword&quot;&gt;not&lt;/span&gt; compile `playground` due &lt;span class=&quot;hljs-keyword&quot;&gt;to&lt;/span&gt; a previous &lt;span class=&quot;hljs-keyword&quot;&gt;error&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The compile error contains the line: &lt;/p&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Vec&amp;lt;{integer}&amp;gt;&lt;/code&gt; is not an iterator; try calling &lt;code&gt;.into_iter()&lt;/code&gt; or &lt;code&gt;.iter()&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/blockquote&gt;
&lt;p&gt;Proving the point that a data structure like &lt;code&gt;Vec&lt;/code&gt; by itself is not an iterator. &lt;/p&gt;
&lt;p&gt;But instead of using the &lt;code&gt;for_each&lt;/code&gt; method, we can actually perform an iteration directly on the &lt;code&gt;Vec&lt;/code&gt; using the &lt;code&gt;for … in&lt;/code&gt; syntax. &lt;/p&gt;
&lt;p&gt;For example, the following code compile and runs as expected:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; item &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints {
       dbg!(item);
   }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What gives?! &lt;/p&gt;
&lt;p&gt;Did we not just prove that a &lt;code&gt;Vec&lt;/code&gt; is not an Iterator on itself? &lt;/p&gt;
&lt;p&gt;We even showed this by trying to call a method that should work on an iterator and confirm it fails. But here we are still being able to &lt;em&gt;iterate&lt;/em&gt; over something that should not be an Iterator using the &lt;code&gt;for … in&lt;/code&gt; syntax. &lt;/p&gt;
&lt;p&gt;How is that possible? &lt;/p&gt;
&lt;p&gt;To understand why this works, we need to look into another trait called &lt;code&gt;IntoIterator&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;what-is-the-intoiterator-trait-&quot;&gt;What is the IntoIterator trait?&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;IntoIterator&amp;nbsp;&lt;/code&gt;is a trait that specifies how a data structure can be converted into an Iterator.  The basic structure of the trait looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;pub&lt;/span&gt; &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;IntoIterator&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Item&lt;/span&gt;&lt;/span&gt;;
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;IntoIter&lt;/span&gt;&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;Iterator&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
        &amp;lt;Self::IntoIter &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Iterator&lt;/span&gt;&amp;gt;::Item == Self::Item;

    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;into_iter&lt;/span&gt;&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&amp;gt; Self::IntoIter;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As can be seen, the main method specified by the trait is &lt;code&gt;into_iter()&lt;/code&gt;. The result of calling it with is an &lt;code&gt;Iterator&lt;/code&gt;. That is, &lt;code&gt;Self::IntoIter&lt;/code&gt; the return type, is of type &lt;code&gt;Iterator&lt;/code&gt;, given it is an associated type defined to be an iterator in the body of the trait. This is what the line &lt;code&gt;type IntoIter: Iterator&lt;/code&gt; above means.&lt;/p&gt;
&lt;p&gt;So any data structure, that by itself is not an iterator, can define how it can be transformed into an iterator by implementing the &lt;code&gt;IntoIterator&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;Vec&lt;/code&gt; data structure defined in the Rust standard library implements the &lt;code&gt;IntoIterator&lt;/code&gt;, which means it has the method &lt;code&gt;into_iter()&lt;/code&gt; which when called returns an &lt;code&gt;Iterator&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;To see this in action, let&#39;s go back to the code that did not compile, where we directly called &lt;code&gt;for_each&lt;/code&gt; on a &lt;code&gt;Vec&lt;/code&gt;, but instead of calling &lt;code&gt;for_each&lt;/code&gt; directly, we first call &lt;code&gt;into_iter()&lt;/code&gt;, before calling &lt;code&gt;for_each&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   &lt;span class=&quot;hljs-comment&quot;&gt;// first calling into_iter() works&lt;/span&gt;
   some_ints.into_iter().for_each(|item| {
       dbg!(item);
   });
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This works, because the first call to &lt;code&gt;into_iter()&lt;/code&gt; returns an &lt;code&gt;Iterator&lt;/code&gt;, which allows iterating over the underlying &lt;code&gt;Vec&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;So how does this help answer why it is possible to use &lt;code&gt;for … in&lt;/code&gt; directly on a &lt;code&gt;Vec&lt;/code&gt; without first turning it into an &lt;code&gt;Iterator&lt;/code&gt; by calling &lt;code&gt;into_iter&lt;/code&gt;?&lt;/p&gt;
&lt;p&gt;Well, the answer is that when the &lt;code&gt;for … in&lt;/code&gt; syntax is used, the compiler automagically first calls &lt;code&gt;into_iter()&lt;/code&gt;, getting an &lt;code&gt;Iterator&lt;/code&gt; back and using that to do the iteration.&lt;/p&gt;
&lt;p&gt;According to the &lt;a href=&quot;https://doc.rust-lang.org/std/iter/index.html#for-loops-and-intoiterator&quot;&gt;documentation&lt;/a&gt;, the &lt;code&gt;for … in&lt;/code&gt; syntax actually desugars to something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; values = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
{
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; result = &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;IntoIterator&lt;/span&gt;::into_iter(values) {
        &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; iter =&amp;gt; &lt;span class=&quot;hljs-keyword&quot;&gt;loop&lt;/span&gt; {
            &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; next;
            &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; iter.next() {
                &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(val) =&amp;gt; next = val,
                &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt; =&amp;gt; &lt;span class=&quot;hljs-keyword&quot;&gt;break&lt;/span&gt;,
            };
            &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; x = next;
            &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; () = { &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;{x}&quot;&lt;/span&gt;); };
        },
    };
    result
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Where the &lt;code&gt;into_iter&lt;/code&gt; is first called on the &lt;code&gt;Vec&lt;/code&gt; value, and then the iteration is continuously done, calling &lt;code&gt;next()&lt;/code&gt;, until &lt;code&gt;None&lt;/code&gt; is reached, signifying the end of the iteration.&lt;/p&gt;
&lt;p&gt;So the &lt;code&gt;into_iter&lt;/code&gt; method, which is part of the &lt;code&gt;IntoInterator&lt;/code&gt; traits explains how the &lt;code&gt;for … in&lt;/code&gt; syntax can be used for iterating over a &lt;code&gt;Vec&lt;/code&gt;. And this is because the compiler by default calls the &lt;code&gt;into_iter&lt;/code&gt; when &lt;code&gt;for … in&lt;/code&gt; syntax is used.&lt;/p&gt;
&lt;p&gt;But what about the other two similar methods that we saw at the beginning of this post? That is &lt;code&gt;iter()&lt;/code&gt; and &lt;code&gt;iter_mut()&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;It is also possible to use these two methods to turn a &lt;code&gt;Vec&lt;/code&gt; into an &lt;code&gt;iterator&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;That is:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {

   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   &lt;span class=&quot;hljs-comment&quot;&gt;// first calling into_iter() works&lt;/span&gt;
   some_ints.iter().for_each(|item| {
       dbg!(item);
   });
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   some_ints.iter_mut().for_each(|item| {
       dbg!(item);
   });
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What is going on when &lt;code&gt;iter_mut()&lt;/code&gt; and &lt;code&gt;iter()&lt;/code&gt; are used? And how is this different from the &lt;code&gt;into_iter()&lt;/code&gt; that comes from the &lt;code&gt;IntoIterator&lt;/code&gt; trait?&lt;/p&gt;
&lt;h3 id=&quot;3-different-kinds-of-iteration&quot;&gt;3 different kinds of iteration&lt;/h3&gt;
&lt;p&gt;Iterators can come in different forms. Nothing is stopping a developer from implementing an Iterator that has other custom behavior that defines how it iterates. &lt;/p&gt;
&lt;p&gt;In Rust&#39;s standard library, most collections have 3 different kinds of Iterators. We can have one which takes ownership of the value being iterated, one that borrows the value immutably, and another that borrows the value and can mutate it. &lt;/p&gt;
&lt;p&gt;An iterator that takes ownership can be created by calling &lt;code&gt;into_iter()&lt;/code&gt;, one that borrows immutable can be created by calling &lt;code&gt;iter()&lt;/code&gt; and the one that borrows value with the ability to mutate can be created by calling &lt;code&gt;iter_mut()&lt;/code&gt;. This is the crux of the &lt;a href=&quot;https://www.geekabyte.io/2022/08/rust-iterator-pattern-with-iter.html&quot;&gt;Rust Iterator pattern with iter(), into_iter() and iter_mut() methods&lt;/a&gt; post.&lt;/p&gt;
&lt;p&gt;It turns out that the Rust compiler by default goes for the &lt;code&gt;into_iter()&lt;/code&gt; version when it de-sugars the &lt;code&gt;for … in&lt;/code&gt; syntax.&lt;/p&gt;
&lt;p&gt;One important thing to point out here is the fact that it is possible to have a custom data structure, that is an iterator, i.e. has all the familiar iteration-related methods: &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;for_each&lt;/code&gt; etc but which is not usable with the &lt;code&gt;for … in&lt;/code&gt; syntax. This will be the case if such data structure implements &lt;code&gt;Iterator&lt;/code&gt; but does not implement the &lt;code&gt;IntoIterator&lt;/code&gt; trait. Because without implementing the &lt;code&gt;IntoIterator&lt;/code&gt; trait, there will be no &lt;code&gt;into_iter()&lt;/code&gt; method for the &lt;code&gt;for … in&lt;/code&gt; syntax to call.&lt;/p&gt;
&lt;p&gt;Another interesting point is what happens if we manually call any of &lt;code&gt;into_iter()&lt;/code&gt;, &lt;code&gt;iter()&lt;/code&gt;, or &lt;code&gt;iter_mut&lt;/code&gt; ourselves as part of usage in &lt;code&gt;for … in&lt;/code&gt; syntax. Basically what was shown in the &lt;a href=&quot;https://www.geekabyte.io/2022/08/rust-iterator-pattern-with-iter.html&quot;&gt;Rust Iterator pattern with iter(), into_iter() and iter_mut() methods&lt;/a&gt; post.&lt;/p&gt;
&lt;p&gt;How come these works:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn main() {
   let mut some_ints = vec![&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
&lt;span class=&quot;hljs-regexp&quot;&gt;//&lt;/span&gt; manually calling iter &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; … &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; 
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints.iter() { 
       dbg!(i);
   }

&lt;span class=&quot;hljs-regexp&quot;&gt;//&lt;/span&gt; manually calling iter_mut &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; … &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; 
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints.iter_mut() {
       dbg!(i);
   }

&lt;span class=&quot;hljs-regexp&quot;&gt;//&lt;/span&gt; manually calling into_iter &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; … &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt;    
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints.into_iter() {
       dbg!(i);
   }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We are manually converting the &lt;code&gt;Vec&lt;/code&gt; ourselves to an iterator by calling &lt;code&gt;iter()&lt;/code&gt;, &lt;code&gt;iter_mut()&lt;/code&gt;, and &lt;code&gt;into_iter()&lt;/code&gt; and yet it works. &lt;/p&gt;
&lt;p&gt;Why does this work? &lt;/p&gt;
&lt;p&gt;Was it not already stated that the &lt;code&gt;for … in&lt;/code&gt; syntax works with anything that implements &lt;code&gt;IntoIterator&lt;/code&gt; which allows it to call &lt;code&gt;into_iter()&lt;/code&gt;. And here we are, manually converting the &lt;code&gt;Vec&lt;/code&gt; into an &lt;code&gt;iterator&lt;/code&gt; ourselves, and yet the &lt;code&gt;for … in&lt;/code&gt; works. How come?&lt;/p&gt;
&lt;p&gt;The answer is in a little trick in the standard library. Which is the fact that the standard library contains this implementation for &lt;code&gt;IntoIterator&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;impl&lt;/span&gt;&amp;lt;I: &lt;span class=&quot;hljs-built_in&quot;&gt;Iterator&lt;/span&gt;&amp;gt; &lt;span class=&quot;hljs-built_in&quot;&gt;IntoIterator&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; I
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This basically means any &lt;code&gt;Iterator&lt;/code&gt; implements &lt;code&gt;IntoIterator&lt;/code&gt; and the implementation is such that the &lt;code&gt;Iterator&lt;/code&gt; returns itself when &lt;code&gt;into_iter()&lt;/code&gt; is called. Which makes sense if you think about it. If something is already an Iterator, what else can be done when you attempt to turn it again into an &lt;code&gt;Iterator&lt;/code&gt; other than it returning itself?&lt;/p&gt;
&lt;p&gt;And this is what happens. Even though the &lt;code&gt;iter()&lt;/code&gt;, &lt;code&gt;into_iter()&lt;/code&gt; and &lt;code&gt;iter_mut&lt;/code&gt; methods are called directly, &lt;code&gt;for … in&lt;/code&gt;, still work, because the &lt;code&gt;iterator&lt;/code&gt; created by calling this method automatically has an implementation of &lt;code&gt;IntoIterator&lt;/code&gt; which returns itself and which the &lt;code&gt;for … in&lt;/code&gt; syntax needs.&lt;/p&gt;
&lt;p&gt;The above shows how implementing the &lt;code&gt;IntoIterator&lt;/code&gt; trait can be done in such a way as to provide interesting functionalities. &lt;/p&gt;
&lt;p&gt;Another interesting utility that is achieved via providing different implementations for  &lt;code&gt;IntoIterator&lt;/code&gt; is how it is possible to use &lt;code&gt;for … in&lt;/code&gt; with a collection and yet be able to still use the collection after iteration, without having to call the &lt;code&gt;iter()&lt;/code&gt; or &lt;code&gt;iter_mut&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This is a more succinct syntax to the solution provided in the &lt;a href=&quot;https://www.geekabyte.io/2022/08/rust-iterator-pattern-with-iter.html&quot;&gt;Rust Iterator pattern with iter(), into_iter() and iter_mut() methods&lt;/a&gt; post&lt;/p&gt;
&lt;p&gt;We look at this, in the next section.&lt;/p&gt;
&lt;h3 id=&quot;the-3-implementation-of-intoiterator-for-vec&quot;&gt;The 3 Implementation of IntoIterator for Vec&lt;/h3&gt;
&lt;p&gt;There are three different implementations of &lt;code&gt;IntoIterator&lt;/code&gt; for the &lt;code&gt;Vec&lt;/code&gt; type. These 3 different implementations are for 3 different variants of the &lt;code&gt;Vec&lt;/code&gt; type depending on its memory access.  &lt;/p&gt;
&lt;p&gt;There are implementations of &lt;code&gt;IntoIterator&lt;/code&gt; for the bare &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; type, the immutable referenced &lt;code&gt;&amp;amp;Vec&amp;lt;T&amp;gt;&lt;/code&gt; type and mutable reference &lt;code&gt;&amp;amp;&#39;a mut Vec&amp;lt;T&amp;gt;&lt;/code&gt; type.&lt;/p&gt;
&lt;p&gt;The implementation of &lt;code&gt;IntoIterator&lt;/code&gt; for bare &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; returns an &lt;code&gt;Iterator&lt;/code&gt; that takes ownership of the values as they are iterated. The implementation of &lt;code&gt;IntoIterator&lt;/code&gt; for &lt;code&gt;&amp;amp;Vec&amp;lt;T&amp;gt;&lt;/code&gt; borrows the value being iterated immutable, while the implementation of  &lt;code&gt;IntoIterator&lt;/code&gt; for &lt;code&gt;&amp;amp;&#39;a mut Vec&amp;lt;T&amp;gt;&lt;/code&gt; makes it possible to mutate the value as part of the iteration.&lt;/p&gt;
&lt;p&gt;This means one can iterate over a &lt;code&gt;Vec&lt;/code&gt; type and still be able to use it afterward if the iteration is done over &lt;code&gt;&amp;amp;Vec&amp;lt;T&amp;gt;&lt;/code&gt; or &lt;code&gt;&amp;amp;&#39;a mut Vec&amp;lt;T&amp;gt;&lt;/code&gt;. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &amp;amp;some_ints { &lt;span class=&quot;hljs-comment&quot;&gt;// same as calling some_ints.iter()&lt;/span&gt;
       dbg!(i);
   }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &amp;amp;&lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; some_ints { &lt;span class=&quot;hljs-comment&quot;&gt;// same as calling some_ints.iter_mut()&lt;/span&gt;
       *i = *i * &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;;
   }
   dbg!(some_ints);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above syntax can be used as a more succinct way to iterate over a data structure like &lt;code&gt;Vec&lt;/code&gt; using the &lt;code&gt;for … in&lt;/code&gt; syntax without taking ownership of the &lt;code&gt;Vec&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;summary&quot;&gt;Summary&lt;/h3&gt;
&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;The &lt;code&gt;IntoIterator&lt;/code&gt; is a trait that defines how an &lt;code&gt;Iterator&lt;/code&gt; can be created for a data structure. It defines an &lt;code&gt;into_iter()&lt;/code&gt; method that when it is called, should return an &lt;code&gt;Iterator&lt;/code&gt;&amp;nbsp;&lt;/li&gt;&lt;li&gt;The &lt;code&gt;for .. in&lt;/code&gt; syntax requires there is an implementation of &lt;code&gt;IntoIterator&lt;/code&gt; because the compiler automagically first calls &lt;code&gt;into_iter()&lt;/code&gt; to retrieve an &lt;code&gt;Iterator&lt;/code&gt; it uses for its iteration.&amp;nbsp;&lt;/li&gt;&lt;li&gt;The Rust standard library also contains an implementation of &lt;code&gt;IntoIterator&lt;/code&gt; for an &lt;code&gt;Iterator&lt;/code&gt;. This implementation just returns the &lt;code&gt;Iterator&lt;/code&gt;. This makes sense, because if something is already an &lt;code&gt;iterator&lt;/code&gt;, then returning it, satisfies the contract defined by &lt;code&gt;IntoIterator&lt;/code&gt;&amp;nbsp;&lt;/li&gt;&lt;li&gt;The fact that there is an &lt;code&gt;IntoIterator&lt;/code&gt; for &lt;code&gt;Iterator&lt;/code&gt; that returns that &lt;code&gt;iterator&lt;/code&gt; means that methods like &lt;code&gt;iter()&lt;/code&gt; or &lt;code&gt;iter_mut()&lt;/code&gt; can still be used within the &lt;code&gt;for .. in&lt;/code&gt; syntax. The &lt;code&gt;for .. in&lt;/code&gt; syntax, can call the &lt;code&gt;into_iter()&lt;/code&gt; gets the &lt;code&gt;Iterator&lt;/code&gt; itself and uses that for its iteration.&amp;nbsp;&lt;/li&gt;&lt;li&gt;The standard library also contains 3 different implementations of &lt;code&gt;IntoIterator&lt;/code&gt; for &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;amp;Vec&amp;lt;T&amp;gt;&lt;/code&gt;, and &lt;code&gt;&amp;amp;&#39;a mut Vec&amp;lt;T&amp;gt;&lt;/code&gt;. The implementation for &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; takes ownership of the value being iterated, the implementation for &lt;code&gt;&amp;amp;Vec&amp;lt;T&amp;gt;&lt;/code&gt; borrows values being iterated immutably, and the implementation for &lt;code&gt;&amp;amp;&#39;a mut Vec&amp;lt;T&amp;gt;&lt;/code&gt; borrows values mutably.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Given a variable &lt;code&gt;some_var&lt;/code&gt; holding a &lt;code&gt;Vec&lt;/code&gt; one can iterate over it using &lt;code&gt;for … in&lt;/code&gt; and still be able to use it after the iteration if the iteration is done over  &lt;code&gt;&amp;amp;some_var&lt;/code&gt; and &lt;code&gt;&amp;amp;mut some_ints&lt;/code&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;/p&gt;
</description><link>http://www.geekabyte.io/2022/08/intoiterator-and-for-in-syntax-in-rust.html</link><author>noreply@blogger.com (dade)</author><thr:total>4</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-1433692153818584294</guid><pubDate>Wed, 10 Aug 2022 21:37:00 +0000</pubDate><atom:updated>2022-10-14T07:32:48.609+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">rust</category><title>Rust Iterator pattern with iter(), into_iter() and iter_mut() methods</title><description>&lt;p&gt;Let&#39;s create a &lt;em&gt;vec&lt;/em&gt; of integers, iterate through and print the individual values, and then afterward, print out the whole &lt;em&gt;vec&lt;/em&gt;. Here is the code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints {
       dbg!(i);
   }

   dbg!(some_ints);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Simple right? Well nope. Trying to compile the above code will fail with the following errors:&lt;/p&gt;

&lt;div style=&quot;width: fit-content;&quot;&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-symbol&quot;&gt;error[E0382]: use of moved value:&lt;/span&gt; `some_ints`
&lt;span class=&quot;hljs-symbol&quot;&gt;   --&amp;gt; src/main.rs:9:&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;9&lt;/span&gt;
    |
&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;   |    let some_ints = vec![&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;]&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    |        --------- move occurs because `some_ints` has type `Vec&amp;lt;i32&amp;gt;`, 
    which does &lt;span class=&quot;hljs-literal&quot;&gt;not&lt;/span&gt; implement the `Copy` trait
&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;   |    for i in some_ints {
    |             --------- `some_ints` moved due to this implicit call to `.into_iter()`
...
&lt;span class=&quot;hljs-number&quot;&gt;9&lt;/span&gt;   |    dbg!(some_ints)&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    |         ^^^^^^^^^ value used here after move
    |
&lt;span class=&quot;hljs-symbol&quot;&gt;note:&lt;/span&gt; this function takes ownership of the receiver `self`, which moves `some_ints`
&lt;span class=&quot;hljs-symbol&quot;&gt;help:&lt;/span&gt; consider iterating over &lt;span class=&quot;hljs-literal&quot;&gt;a&lt;/span&gt; slice of the `Vec&amp;lt;i32&amp;gt;`&#39;s 
content to avoid moving into the `f&lt;span class=&quot;hljs-literal&quot;&gt;or&lt;/span&gt;` &lt;span class=&quot;hljs-keyword&quot;&gt;loop&lt;/span&gt;
    |
&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;   |    for i in &amp;amp;some_ints {
    |             +

For more information about this error, try `rustc --explain E0382`
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
  
&lt;p&gt;Why is this the case? Why is the borrow checker preventing the use of a &lt;em&gt;vec&lt;/em&gt; after a simple iteration? &lt;/p&gt;
&lt;p&gt;Well, the answer to that question lies in Rust&#39;s implementation of the Iterator pattern - which by the way, is what makes it possible to use the &lt;code&gt;for…in&lt;/code&gt; syntax.&lt;/p&gt;
&lt;p&gt;Iterators are not special or unique to Rust. The concept can be found in a handful of languages. I wrote about the Iterator pattern as it exists in JavaScript in the post &lt;a href=&quot;https://www.geekabyte.io/2019/06/iterables-and-iterators-in-javascript.html&quot;&gt;Iterables and Iterators in JavaScript&lt;/a&gt;. &lt;/p&gt;
&lt;p&gt;The unique thing about the Iterator pattern in Rust is its interaction with the borrow checker. &lt;/p&gt;
&lt;p&gt;If this interaction with the borrow checker is not taken into consideration then it is possible to bump into certain confusing compile errors while attempting to use the iterator pattern.&lt;/p&gt;
&lt;p&gt;So to get started answering the question of why the borrow checker prevents what looks like a legit code above, let&#39;s take a look at the Iterator pattern and what is special about it in Rust.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
&lt;h3 id=&quot;rust-and-iterator-pattern-&quot;&gt;Rust and Iterator Pattern.&lt;/h3&gt;
&lt;p&gt;An Iterator is a data structure that allows retrieval of elements from another data structure in sequence. In rust, it is any data structure that implements the &lt;code&gt;Iterator&lt;/code&gt; trait.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#![allow(unused)]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
&lt;span class=&quot;hljs-keyword&quot;&gt;pub&lt;/span&gt; &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Iterator&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Item&lt;/span&gt;&lt;/span&gt;;

    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;next&lt;/span&gt;&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&amp;gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;lt;Self::Item&amp;gt;;

    &lt;span class=&quot;hljs-comment&quot;&gt;// methods with default implementations elided&lt;/span&gt;
 }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;Iterator&lt;/code&gt; trait defines a &lt;code&gt;next&lt;/code&gt; method that when called, returns an &lt;code&gt;Option&lt;/code&gt; of type &lt;code&gt;Self::Item&lt;/code&gt;, which ends up being whatever the type of elements in what is being iterated over. Once the iteration reaches the end, a &lt;code&gt;None&lt;/code&gt; is returned. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[test]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;iterator_demo&lt;/span&gt;&lt;/span&gt;() {
 &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v1 = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
 &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; v1_iter = v1.iter();

 &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;));
 &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;));
 &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;));
 &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;);

}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above is simple enough. The part that interacts with the borrow checker is how the &lt;code&gt;next&lt;/code&gt; method treats the value it is getting from the underlying structure it is iterating over.&lt;/p&gt;
&lt;p&gt;It is possible that the &lt;code&gt;next&lt;/code&gt; method of the &lt;code&gt;iterator&lt;/code&gt; trait be implemented in such a way that it borrows the value immutable, borrows the value mutable, or even takes ownership of the values being iterated. &lt;/p&gt;
&lt;p&gt;These three behaviors define 3 different distinct types of iterators. &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An iterator that borrows the value being iterated immutably&lt;/li&gt;
&lt;li&gt;An iterator that borrows the value being iterated mutably.&lt;/li&gt;
&lt;li&gt;An iterator that takes ownership of values being iterated&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To demonstrate these 3 iterator types, we can take a &lt;em&gt;vec&lt;/em&gt; as usual and create these three distinct iterators and observe their behavior.&lt;/p&gt;
&lt;strong id=&quot;an-iterator-that-borrows-the-value-being-iterated-immutably-&quot;&gt;An iterator that borrows the value being iterated immutably.&lt;/strong&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[test]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;iter_demo&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v1 = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;];
    &lt;span class=&quot;hljs-comment&quot;&gt;// the .iter() method creates an iterator, v1_iter 
    // which borrows value immutably &lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; v1_iter = v1.iter();

    &lt;span class=&quot;hljs-comment&quot;&gt;// iter() returns an iterator of slices.&lt;/span&gt;
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&amp;amp;&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;);
   &lt;span class=&quot;hljs-comment&quot;&gt;// because values were borrowed immutably, it is still 
   // possible to use the vec after iteration is done&lt;/span&gt;
    dbg!(v1);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the code above, the &lt;code&gt;.iter()&lt;/code&gt; method that is called on the &lt;em&gt;vec&lt;/em&gt;, &lt;code&gt;v1&lt;/code&gt; creates an iterator, &lt;code&gt;v1_iter&lt;/code&gt; which borrows value immutably. Because the values of &lt;code&gt;v1&lt;/code&gt; were borrowed immutable by the iterator &lt;code&gt;v1_iter&lt;/code&gt; it was still possible to use the &lt;em&gt;vec&lt;/em&gt; &lt;code&gt;v1&lt;/code&gt; after the iteration by &lt;code&gt;dbg!&lt;/code&gt; printing it.&lt;/p&gt;
&lt;strong id=&quot;an-iterator-that-borrows-the-value-being-iterated-mutably&quot;&gt;An iterator that borrows the value being iterated mutably&lt;/strong&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;#[test]
&lt;span class=&quot;hljs-symbol&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;iter_mut_demo() &lt;/span&gt;{
    let mut &lt;span class=&quot;hljs-built_in&quot;&gt;v1&lt;/span&gt; = vec![&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;]&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // the .&lt;span class=&quot;hljs-keyword&quot;&gt;iter_mut() &lt;/span&gt;method creates an &lt;span class=&quot;hljs-keyword&quot;&gt;iterator, 
&lt;/span&gt;    // v1_iter which &lt;span class=&quot;hljs-keyword&quot;&gt;borrows &lt;/span&gt;value &lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;can mutate &lt;span class=&quot;hljs-keyword&quot;&gt;it. &lt;/span&gt;
    let mut v1_iter = &lt;span class=&quot;hljs-built_in&quot;&gt;v1&lt;/span&gt;.&lt;span class=&quot;hljs-keyword&quot;&gt;iter_mut();
&lt;/span&gt;
    // access the first &lt;span class=&quot;hljs-keyword&quot;&gt;item &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;multiple &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;it &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;by &lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
    let &lt;span class=&quot;hljs-keyword&quot;&gt;item1 &lt;/span&gt;= v1_iter.next().unwrap()&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    *&lt;span class=&quot;hljs-keyword&quot;&gt;item1 &lt;/span&gt;= *&lt;span class=&quot;hljs-keyword&quot;&gt;item1 &lt;/span&gt;* &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // access the second &lt;span class=&quot;hljs-keyword&quot;&gt;item &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;multiple &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;it &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;by &lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
    let &lt;span class=&quot;hljs-keyword&quot;&gt;item2 &lt;/span&gt;= v1_iter.next().unwrap()&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    *&lt;span class=&quot;hljs-keyword&quot;&gt;item2 &lt;/span&gt;= *&lt;span class=&quot;hljs-keyword&quot;&gt;item2 &lt;/span&gt;* &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // access the third &lt;span class=&quot;hljs-keyword&quot;&gt;item &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;and &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;multiple &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;it &lt;/span&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;by &lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
    let &lt;span class=&quot;hljs-keyword&quot;&gt;item3 &lt;/span&gt;= v1_iter.next().unwrap()&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;
    *&lt;span class=&quot;hljs-keyword&quot;&gt;item3 &lt;/span&gt;= *&lt;span class=&quot;hljs-keyword&quot;&gt;item3 &lt;/span&gt;* &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // &lt;span class=&quot;hljs-meta&quot;&gt;end&lt;/span&gt; of the &lt;span class=&quot;hljs-keyword&quot;&gt;iteration
&lt;/span&gt;    assert_eq!(v1_iter.next(), None)&lt;span class=&quot;hljs-comment&quot;&gt;;&lt;/span&gt;

    // this will print out [&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;6&lt;/span&gt;]
    &lt;span class=&quot;hljs-keyword&quot;&gt;dbg!(v1);
&lt;/span&gt;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the code above, the &lt;code&gt;.iter_mut()&lt;/code&gt; method that is called on the &lt;em&gt;vec&lt;/em&gt;, &lt;code&gt;v1&lt;/code&gt; creates an iterator, &lt;code&gt;v1_iter&lt;/code&gt; which borrows value mutable. That is, the value borrowed can be updated. And the code does exactly that, mutating each value iterated by multiplying it by 2. Because the values of &lt;code&gt;v1&lt;/code&gt; were borrowed mutably and not owned by the iterator &lt;code&gt;v1_iter&lt;/code&gt; it was still possible to use the &lt;em&gt;vec&lt;/em&gt; &lt;code&gt;v1&lt;/code&gt; by printing it. Printing also confirms that the values in the &lt;em&gt;vec&lt;/em&gt; have been updated with each item multiplied by 2. &lt;/p&gt;
&lt;strong id=&quot;an-iterator-that-takes-ownership-of-values-being-iterated&quot;&gt;An iterator that takes ownership of values being iterated&lt;/strong&gt;
&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[test]&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;into_iter_demo&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-comment&quot;&gt;// the .into_iter() method creates an iterator, 
    // v1_iter which takes ownership &lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// of the values being iterated.&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; v1_iter = v1.into_iter();

    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;));
    &lt;span class=&quot;hljs-built_in&quot;&gt;assert_eq!&lt;/span&gt;(v1_iter.next(), &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;);

    &lt;span class=&quot;hljs-comment&quot;&gt;// If the line below is uncommented, the code won&#39;t compile anymore&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// this is because, after the iteration, v1 can no longer be used &lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// since the iteration moved ownership&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;//dbg!(v1);&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the code above, the &lt;code&gt;.into_iter()&lt;/code&gt; method creates an iterator, &lt;code&gt;v1_iter&lt;/code&gt; which takes ownership, because of this, &lt;code&gt;v1&lt;/code&gt; is no longer usable after the iteration has ownership has moved after the iteration. Uncommenting the dbg! line would lead to a compile error because of this.&lt;/p&gt;
&lt;h3 id=&quot;iterator-and-for-in-syntax&quot;&gt;Iterator and for…in syntax&lt;/h3&gt;
&lt;p&gt;So now we have seen that Iterators in Rust can come in 3 forms depending on how ownership is handled when the iterator accesses the values of the data structure being iterated. &lt;/p&gt;
&lt;p&gt;How does this then help us answer why the following code: &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints {
       dbg!(i);
   }

   dbg!(some_ints);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;which looks legit get flagged by the borrow checker?&lt;/p&gt;
&lt;p&gt;The answer lies in the fact that the &lt;code&gt;for…in&lt;/code&gt; syntax, by default, calls the &lt;code&gt;.into_iter()&lt;/code&gt; method, which returns an iterator that takes ownership of values being iterated. &lt;/p&gt;
&lt;p&gt;The code above is essentially the same as the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints.into_iter() {
       dbg!(i);
   }

   dbg!(some_ints);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Compiling both will lead to the same error.&lt;/p&gt;
&lt;p&gt;So to use the &lt;code&gt;for…in&lt;/code&gt; syntax and still be able to use the underlying &lt;em&gt;vec&lt;/em&gt;, after iteration, we will have to manually call either the &lt;code&gt;iter()&lt;/code&gt; or &lt;code&gt;iter_mut()&lt;/code&gt; method instead.&lt;/p&gt;
&lt;p&gt;For example, using the &lt;code&gt;iter()&lt;/code&gt; method with &lt;code&gt;for..in&lt;/code&gt; will look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {

   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints.iter() {
       dbg!(i);
   }

   dbg!(some_ints);
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This time around, the code compiles fine. And if the code is executed, the contents of &lt;code&gt;some_ints&lt;/code&gt; will get printed fine even after the iteration. Something that was not possible before.&lt;/p&gt;
&lt;p&gt;Using the &lt;code&gt;iter_mut()&lt;/code&gt; method on the other hand enables us to mutate the values as they are being iterated. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {

   &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; some_ints = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;,&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;];
   &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; some_ints.iter_mut() {
       *i = *i * &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;;
   }

   dbg!(some_ints);

}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above code compiles fine, and when run, will print &lt;code&gt;[2,3,6,8,10]&lt;/code&gt; confirming that it was possible to mutate the values while iterating.&lt;/p&gt;&lt;p&gt;To further explore how all the above works, check&amp;nbsp;&lt;a href=&quot;https://www.geekabyte.io/2022/08/intoiterator-and-for-in-syntax-in-rust.html&quot;&gt;IntoIterator and the for ... in Syntax in Rust&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;summary&quot;&gt;Summary&lt;/h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;An Iterator is a pattern that allows retrieval of elements from another data structure in sequence. In Rust, it is represented by the &lt;code&gt;Iterator&lt;/code&gt; trait.&lt;/li&gt;
&lt;li&gt;A data structure implementing the &lt;code&gt;Iterator&lt;/code&gt; trait interacts with the borrow checker based on how it handles access to the values in the data structure being iterated. &lt;/li&gt;
&lt;ul&gt;&lt;li&gt;It is possible for the iterator to borrow the value being iterated immutably. This type of iterator is created by calling &lt;code&gt;iter()&lt;/code&gt;.&lt;/li&gt;&lt;li&gt;It is possible for the iterator to borrow the value being iterated mutably. This type of iterator is created by calling &lt;code&gt;iter_mut()&lt;/code&gt;.&lt;/li&gt;&lt;li&gt;It is possible for the iterator to take ownership of the value values being iterated. This type of iterator is created by calling &lt;code&gt;into_iter()&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt;


&lt;li&gt;By default, the &lt;code&gt;for..in&lt;/code&gt; syntax calls the &lt;code&gt;into_iter()&lt;/code&gt; which takes ownership of the value being iterated. This is why after iteration, the underlying variable that holds the original &lt;em&gt;vec&lt;/em&gt; becomes unusable. This is because ownership has moved away from it.&lt;/li&gt;
&lt;li&gt;To use the &lt;code&gt;for..in&lt;/code&gt; syntax and still be able to use the variable that holds the original &lt;em&gt;vec&lt;/em&gt;, after iteration, then either call &lt;code&gt;iter()&lt;/code&gt; or &lt;code&gt;iter_mut()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
</description><link>http://www.geekabyte.io/2022/08/rust-iterator-pattern-with-iter.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-7714604311347173650</guid><pubDate>Sun, 12 Jun 2022 14:34:00 +0000</pubDate><atom:updated>2022-10-11T18:28:16.994+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Introduction to Digital Signature for the Working Developer</title><description>&lt;p&gt;In this post, we would be looking at digital signatures. It will be a quick, straight-to-the-point overview of some of the essential things a developer should know about digital signatures. How to think about them and what problems they solve. It is targeted at the working developer who needs to be familiar enough with digital signatures to use them, but who does not need to know the gory details of how they are implemented, or how they work internally.&lt;/p&gt;
&lt;p&gt;This post contains the following sections:&amp;nbsp;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;What is a digital signature&amp;nbsp;&lt;/li&gt;&lt;li&gt;Components of Digital Signature Schemes&amp;nbsp;&lt;/li&gt;&lt;li&gt;Digital Signature Algorithms&amp;nbsp;&lt;/li&gt;&lt;li&gt;Last note: Digital Signatures versus Message Authenticated Codes.&lt;/li&gt;&lt;/ol&gt;&lt;span&gt;&lt;/span&gt;&lt;p&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
&lt;h3 id=&quot;what-is-a-digital-signature&quot;&gt;What is a digital signature&lt;/h3&gt;
&lt;p&gt;Signatures in real life are used to ascertain that a piece of document originated and is authorized by the signer. &lt;/p&gt;
&lt;p&gt;Similarly, in the digital world, digital signatures are cryptographic primitives used for the same purpose. That is, to ascertain that some digital data came from, and has been authorized by an entity that claims to have originated it. &lt;/p&gt;
&lt;p&gt;The digital data could be in the form of an email, a PDF document, blockchain transactions, etc. the point of digital signature remains the same: ascertain that some digital data is legit by ascertaining it originated from the right origin. This function is called &lt;em&gt;origin authentication&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;Apart from origin authentication, digital signatures can also be used to ascertain that the data signed has not been tampered with. This is called &lt;em&gt;message authentication&lt;/em&gt; or &lt;em&gt;Integrity&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;It is also worth mentioning that digital signatures are cryptographic primitives that fall under the asymmetric cryptography category because they make use of two key pairs: private and public keys. &lt;/p&gt;
&lt;p&gt;Let&#39;s now take a look at the components of a digital signature scheme.&lt;/p&gt;
&lt;h3 id=&quot;components-of-digital-signature-schemes&quot;&gt;Components of Digital Signature Schemes&lt;/h3&gt;
&lt;p&gt;Digital signature schemes are usually made up of three distinct components or algorithms:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Key generation&lt;/strong&gt;: This component of the scheme consists of the algorithm that takes care of generating the key pair (private/public) that the signer needs to generate the digital signature.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Signing Algorithm&lt;/strong&gt;: This component is the actual algorithm that generates the digital signature. It takes the message to be signed and uses the private key generated by the key generation algorithm, to create a digital signature.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Verifying Algorithm&lt;/strong&gt;: This checks the authenticity of digital signatures. It takes the public key generated via a key generation algorithm, together with the signature, generated by the signing algorithm, and returns either success if the signature is valid or an error if invalid.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Having listed the three main broad components of digital signatures, let&#39;s now take a look at some of the popularly known digital signature schemes. For completeness&#39; sake, it would also mention schemes that were once used but are no longer recommended due to security reasons. &lt;/p&gt;
&lt;h3 id=&quot;digital-signature-algorithms-&quot;&gt;Digital Signature Algorithms.&lt;/h3&gt;
&lt;br /&gt;
&lt;strong id=&quot;rsa-rsa-pkcs1-v1_5-and-rsa-pss-&quot;&gt;RSA (RSA-PKCS1-v1_5 and RSA-PSS)&lt;/strong&gt;
&lt;p&gt;RSA (Ron &lt;strong&gt;Rivest&lt;/strong&gt;, Adi &lt;strong&gt;Shamir&lt;/strong&gt;, and Leonard &lt;strong&gt;Adleman&lt;/strong&gt; - last names of the cryptographers who proposed the scheme) was the first digital signatures scheme to be articulated in 1977. &lt;/p&gt;
&lt;p&gt;RSA was introduced as a scheme for encryption in &lt;a href=&quot;https://www.geekabyte.io/2022/06/introduction-to-asymmetric-encryption.html&quot;&gt;Introduction to Asymmetric Encryption for the Working Developer&lt;/a&gt;. It is asymmetric cryptography primitive, hence uses private/public key pair. When used for encryption, the public key is used to encrypt a message that is then sent to the owner of the corresponding private key. The private key can then be used to decrypt the message. &lt;/p&gt;
&lt;p&gt;When RSA is used for digital signature, the signing algorithm involves taking a hash of the message to be signed, and then encrypting the hash to create a ciphertext that serves as the signature. The message and the signature (ciphertext of the message) are then shared.&lt;/p&gt;
&lt;p&gt;The verifying part of the scheme involves two steps. The first step is to use the same hashing algorithm to hash the message received from the signer. The second step is to use the corresponding public key to the private key of the signer to decrypt the received signature (that is the ciphertext the signer published with the message). If the hash value generated by the verifier is the same as the one revealed after using the public key to decrypt the signature, then the signature is valid. If it is not equal, then the signature is invalid. &lt;/p&gt;
&lt;p&gt;As mentioned in &lt;a href=&quot;https://www.geekabyte.io/2022/06/introduction-to-asymmetric-encryption.html&quot;&gt;Introduction to Asymmetric Encryption for the Working Developer&lt;/a&gt; RSA is usually used with a padding scheme to make it more secure. The first padding scheme that can be used with RSA to create digital signatures is PKCS1-v1_5. This gives rise to the RSA-PKCS1-v1_5 digital signature scheme. This scheme is no longer recommended due to &lt;a href=&quot;https://crypto.stackexchange.com/questions/12688/can-you-explain-bleichenbachers-cca-attack-on-pkcs1-v1-5&quot;&gt;security vulnerability&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A newer standard RSA-PSS which makes use of &lt;a href=&quot;https://en.wikipedia.org/wiki/Probabilistic_signature_scheme&quot;&gt;PSS encoding algorithm&lt;/a&gt; is the preferred scheme to use when using RSA for digital signatures.&lt;/p&gt;
&lt;strong id=&quot;schnorr-signature&quot;&gt;Schnorr Signature&lt;/strong&gt;
&lt;p&gt;Schnorr Signature is another digital signature scheme that was proposed in 1990 by &lt;a href=&quot;https://en.wikipedia.org/wiki/Claus_P._Schnorr&quot;&gt;Claus P. Schnorr&lt;/a&gt;. It is efficient and secure, with no known vulnerability. Although historically, It is not widely used because it was covered by a patent. The patent has since expired in 2008 so adoption will probably see an uptick. This is observed already has Bitcoin recently added Schnorr signatures as part of the digital signature it supports.&lt;/p&gt;
&lt;strong id=&quot;dsa-and-ecdsa&quot;&gt;DSA and ECDSA&lt;/strong&gt;
&lt;p&gt;In 1991, the National Institute of Standard and Technology &lt;a href=&quot;https://www.nist.gov/&quot;&gt;NIST&lt;/a&gt; proposed the Digital Signature Algorithm (DSA). For all intent and purposes, DSA is a variant of the Schnoor signature. The sole reason why it was proposed, was to avoid Shnoor&#39;s patent restriction. It has no known vulnerability and enjoyed great adoption, although it has since been replaced with the elliptic curve implementation of the scheme, which is known as the Elliptic Curve Digital Signature Algorithm (ECDSA)&lt;/p&gt;
&lt;strong id=&quot;eddsa&quot;&gt;EdDSA&lt;/strong&gt;
&lt;p&gt;EdDSA, which stands for Edwards-curve Digital Signature Algorithm, was proposed in 2008 by &lt;a href=&quot;https://en.wikipedia.org/wiki/Daniel_J._Bernstein&quot;&gt;Daniel J. Bernstein&lt;/a&gt;. It takes inspiration from Schnoor&#39;s signature it is also an elliptic curve-based scheme since it makes use of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Edwards_curve&quot;&gt;Edward curve&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;It is worth mentioning that these schemes mentioned above are by far not the only digital signature schemes in existence. Although, arguably, they are the most common. There exist other schemes like &lt;a href=&quot;https://en.wikipedia.org/wiki/ElGamal_signature_scheme&quot;&gt;ElGamal signature scheme&lt;/a&gt;, the &lt;a href=&quot;https://en.wikipedia.org/wiki/Rabin_signature_algorithm&quot;&gt;Rabin signature algorithm&lt;/a&gt;, or  &lt;a href=&quot;https://en.wikipedia.org/wiki/NTRUSign&quot;&gt;NTRUsign&lt;/a&gt; just to mention a few.&lt;/p&gt;
&lt;h3 id=&quot;code-examples-using-rsa-pss&quot;&gt;Code Examples using RSA-PSS&lt;/h3&gt;
&lt;p&gt;The code snippets below show how to use RSA-PSS using Deno&#39;s implementation of Web Crypto API. Three methods will be used: &lt;em&gt;generateKey&lt;/em&gt;, &lt;em&gt;sign&lt;/em&gt;, and &lt;em&gt;verify&lt;/em&gt;. Which corresponds to the three components of digital signature schemes.&lt;/p&gt;

&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;// Key Generation
const keyParams = {
    name: &quot;RSA-PSS&quot;,
    // The length in bits of the RSA modulus
    modulusLength: 2048,
    // The public component e. Recommended value is 65537
    publicExponent: new Uint8Array([1, 0, 1]),
    // hash function required by PSS
    hash: &quot;SHA-256&quot;,
};

const keyPair = await crypto.subtle.generateKey(keyParams, true, [&quot;sign&quot;, &quot;verify&quot;])

// Signing

const message = new TextEncoder().encode(&quot;increase interest rate by 2%&quot;)

const signParams = {
    name: &quot;RSA-PSS&quot;,
    // A long integer representing the length of the random salt to use, in bytes
    // Value can be either 0 or the length of the output of the key&#39;s digest algorithm. 
    // For example, if you use SHA-256 as the digest algorithm, this could be 32
    saltLength: 32
}
const signature = await crypto.subtle.sign(signParams, keyPair.privateKey, message)


// Verification

const verifyParams = {
    name: &quot;RSA-PSS&quot;,
    // A long integer representing the length of the random salt to use, in bytes
    // Value can be either 0 or the length of the output of the key&#39;s digest algorithm. 
    // For example, if you use SHA-256 as the digest algorithm, this could be 32
    saltLength: 32
}

const verificationResult = await crypto.subtle.verify(verifyParams, keyPair.publicKey, signature, message)

console.log(`Signature verification is: ${verificationResult}`);


// Confirm if message is different verification fails

const differentMessage = new TextEncoder().encode(&quot;increase interest rate by 20%&quot;)

const failedVerification = await crypto.subtle.verify(verifyParams, keyPair.publicKey, signature, differentMessage)

console.log(`Signature verification for different message is: ${failedVerification}`);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Having the above code snippet in &lt;em&gt;index.js&lt;/em&gt; file and running via the following command &lt;em&gt;deno run index.js&lt;/em&gt; would print out the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Signature verification &lt;span class=&quot;hljs-keyword&quot;&gt;is&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
Signature verification &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; different message &lt;span class=&quot;hljs-keyword&quot;&gt;is&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;last-note-digital-signatures-versus-message-authenticated-codes&quot;&gt;Last note: Digital Signatures versus Message Authenticated Codes&lt;/h3&gt;
&lt;p&gt;In &lt;a href=&quot;https://www.geekabyte.io/2021/10/hash-function-in-action-message.html&quot;&gt;Hash Function in Action: Message Authentication Codes&lt;/a&gt; I introduced Message Authenticated Codes (MAC). Which involves two parties making use of a shared secret key to ascertain the integrity of messages.&lt;/p&gt;
&lt;p&gt;It is worth mentioning that digital signatures are the asymmetric version of message authentication code, with the extra convenience that it does not require parties to perform any key exchange.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2022/06/introduction-to-digital-signature-for.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-916655031706304703</guid><pubDate>Mon, 06 Jun 2022 11:10:00 +0000</pubDate><atom:updated>2022-06-08T17:27:46.689+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Introduction to Asymmetric Encryption for the Working Developer</title><description>&lt;p&gt;In this post, we are going to look at asymmetric encryption. As mentioned in the previous post on &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-symmetric-encryption.html&quot;&gt;symmetric encryption&lt;/a&gt;, encryption is the cryptographic primitive that guarantees confidentiality, by which we mean the ability for two or more authorized parties to communicate, without an unauthorized person being able to decipher the messages being communicated.&lt;/p&gt;
&lt;p&gt;In symmetric encryption, both parties need to use the same key for encryption and decryption. This leads to the problem of how to securely get the communicating parties to use the same key. A solution to this is the Key exchange protocol that was discussed in &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-key-exchange-for.html&quot;&gt;Introduction to Key Exchange for the Working Developer&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Asymmetric encryption is different. Unlike symmetric encryption, it does not have the requirement that the same key needs to be used for encryption and decryption. Hence why it is called asymmetric. It makes use of key pairs instead. One is called the private key, the other called the public key. &lt;/p&gt;
&lt;p&gt;In this post, we will be looking at how to use asymmetric encryption and what other general information to be aware of. As always it is targeted at the working developer who needs a grounded understanding of these cryptographic primitives without necessarily covering the internals of these primitives.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
&lt;h3 id=&quot;asymmetric-cryptography-and-asymmetric-encryption&quot;&gt;Asymmetric Cryptography and Asymmetric Encryption&lt;/h3&gt;
&lt;p&gt;Oftentimes when private/public keys are mentioned, it is often done so in the context of encryption, that is, asymmetric encryption. The reality is that the use of public and private keys is not restricted to encryption and decryption alone, there are other primitives in cryptography that make use of private/public keys.&lt;/p&gt;
&lt;p&gt;For example, the Diffie-Hellman Key Exchange, which I wrote about in &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-key-exchange-for.html&quot;&gt;Introduction to Key Exchange for the Working Developer&lt;/a&gt; is an example of a cryptographic primitive that makes use of asymmetric keys but has nothing to do with encryption. &lt;/p&gt;
&lt;p&gt;&lt;i&gt;&lt;b&gt;Asymmetric cryptography&lt;/b&gt;&lt;/i&gt; is the broad term that refers to all the various cryptosystems that do not depend on having two identical secret keys to function. Asymmetric encryption falls under asymmetric cryptography but so do other primitives. I believe this tidbit needs to be highlighted to prevent the assumption that when public and private keys are used, they are always used in encryption and decryption.&lt;/p&gt;
&lt;p&gt;With that clarification out of the way, let us dig into asymmetric encryption by taking a broad look at the different asymmetric encryption algorithms.&lt;/p&gt;
&lt;h3 id=&quot;asymmetric-encryption-algorithms&quot;&gt;Asymmetric Encryption Algorithms&lt;/h3&gt;
&lt;p&gt;Asymmetric encryption makes use of key pairs. A private key and a public key. This pair of keys can be used to achieve confidentiality. This is because messages encrypted by a key in the pair can be decrypted by the other key.&lt;/p&gt;
&lt;p&gt;This is how it usually works. The public key, as the name implies, is made public. This can be shared at the beginning of confidential message exchange, or it can be made available free via any other means: email, on a website, etc. The private portion, on the other hand, is kept secret. To communicate confidentially, the public key is used to encrypt a message, which is then sent to the entity that controls the corresponding private key. This encrypted message can only be decrypted by the owner of the corresponding private key. &lt;/p&gt;
&lt;p&gt;A two-way encrypted communication then involves the communicating parties using each other&#39;s public key to encrypt messages. That is Alice uses Bob&#39;s public key to encrypt messages she wants to send to Bob. Bob can then decrypt these messages from Alice. To reply to Alice&#39;s confidentiality, Bob also makes use of Alice&#39;s public key to encrypt replies that are sent to Alice.&lt;/p&gt;
&lt;p&gt;There are a couple of algorithms that implement the ability to encrypt and decrypt using private/public key pairs. For example &lt;a href=&quot;https://en.wikipedia.org/wiki/ElGamal_encryption&quot;&gt;ElGamal&lt;/a&gt;, &lt;a href=&quot;https://en.wikipedia.org/wiki/Paillier_cryptosystem&quot;&gt;Paillier cryptosystem&lt;/a&gt;, and &lt;a href=&quot;https://en.wikipedia.org/wiki/Cramer%E2%80%93Shoup_cryptosystem&quot;&gt;Cramer–Shoup cryptosystem&lt;/a&gt; but by far, the most popular and most used algorithm is &lt;a href=&quot;https://en.wikipedia.org/wiki/RSA_(cryptosystem&quot;&gt;RSA cryptosystem&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The acronym &quot;RSA&quot; is from the last names of the three cryptographers Ron &lt;strong&gt;Rivest&lt;/strong&gt;, Adi &lt;strong&gt;Shamir&lt;/strong&gt;, and Leonard &lt;strong&gt;Adleman&lt;/strong&gt;, who proposed the algorithm in 1977.&lt;/p&gt;
&lt;p&gt;Like with most asymmetric cryptosystems, the underpinning of RSA and its security is based on mathematics. But since the aim of this post is to provide the necessary information needed for a working developer to form a working mental model of asymmetric encryption, we will avoid a rigorous take but gloss over the mathematical details instead. Readers who are interested in digging more into mathematics can check the additional section of this post. There, I share links that cover some of the mathematics that is fundamental to RSA.&lt;/p&gt;
&lt;p&gt;For now, we take a bird&#39;s eye view of the RSA algorithm. &lt;/p&gt;
&lt;h3 id=&quot;how-rsa-works&quot;&gt;How RSA Works&lt;/h3&gt;
&lt;p&gt;RSA is based on factorization problem. Factorization is the mathematical operation of splitting an integer into products of smaller integers. For example, the numbers 21, 7, and 3 are its factors.&lt;/p&gt; 
&lt;p&gt; The factorization problem is the observation that it is easy to find an integer given its factors, but the reverse, that is finding the factors of a given number is hard. A small number like 21 in the example above does not demonstrate this difficulty, but given a substantial large integer, finding its individual factors is extremely hard, with no algorithm to speed up the process, and finding such factors essentially involves brute force.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;Can the reader say what two numbers multiplied together will produce the number 8,616,460,799? I think it unlikely that anyone but myself will ever know.&quot; &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The above challenge was posed by William Stanley Jevons in his 1874 book, Principles of Science. The number becomes known as &lt;a href=&quot;https://en.wikipedia.org/wiki/William_Stanley_Jevons#Jevons&#39;s_number&quot;&gt;Jevon&#39;s number&lt;/a&gt;. It is essentially a factorization problem challenge. It took 15 years to crack. It was factored by Charles J. Busk in 1889 who found that 89,681 and 96,079 are factors of 8,616,460,799.&lt;/p&gt;
&lt;p&gt;Factoring is the underlying, presumably hard problem upon which the RSA algorithm is based. An in-depth explanation is beyond the scope of this post, but the general algorithm is outlined below. &lt;/p&gt;
&lt;p&gt;Note that the outline below is often referred to as textbook RSA and this is not how RSA is implemented in practice because it is insecure. There are slight improvements mainly in the area of padding that fortifies the algorithm.&lt;/p&gt;
&lt;p&gt;The general outline of the algorithm is as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Choose very two large prime numbers. Let&#39;s call them &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;Let &lt;em&gt;N = p * q&lt;/em&gt; &lt;em&gt;N&lt;/em&gt; is usually referred to as the modulus&lt;/li&gt;
&lt;li&gt;Find the Euler totient of &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt;, that is &lt;em&gt;T = (p-1)(q-1)&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;Choose another number &lt;em&gt;e&lt;/em&gt; where &lt;em&gt;1 &amp;lt; e &amp;lt; T&lt;/em&gt; and &lt;em&gt;e&lt;/em&gt; do not share any factors with N and T&lt;/li&gt;
&lt;li&gt;&lt;em&gt;e&lt;/em&gt; is used for the encryption process.&lt;/li&gt;
&lt;li&gt;Choose another number &lt;em&gt;d&lt;/em&gt; where &lt;em&gt;e * d mod T = 1&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;d&lt;/em&gt; is used for the decryption process.&lt;/li&gt;
&lt;li&gt;The pair N and e is the public key. This is published&lt;/li&gt;
&lt;li&gt;The pair N and d is the private key. This is kept a secret.&lt;/li&gt;
&lt;li&gt;To encrypt, a message, represent the message as a numeric value, say &lt;em&gt;m&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;Then calculate &lt;em&gt;m ^ e mod N&lt;/em&gt; = ciphertext c&lt;/li&gt;
&lt;li&gt;To decrypt ciphertext c back to &lt;em&gt;m&lt;/em&gt; calculate &lt;em&gt;c ^ d mod N&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the general outline. To see this in practice, let&#39;s try it out with 2 prime numbers that are small enough to make demonstration possible. We choose &lt;em&gt;p = 2 and q = 7&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Choose very two large prime numbers. Let&#39;s call them &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;p = 2 and q = 7&lt;/strong&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Let &lt;em&gt;N = p * q&lt;/em&gt; &lt;em&gt;N&lt;/em&gt; is usually referred to as the modulus&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;N = 2 * 7 = 14&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Find the Euler coefficient of &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt;, that is &lt;em&gt;T = (p-1)(q-1)&lt;/em&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt; T = (2-1)(7-1) = 1 * 6 = 6 &lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Choose another number &lt;em&gt;e&lt;/em&gt; where &lt;em&gt;1 &amp;lt; e &amp;lt; T&lt;/em&gt; and &lt;em&gt;e&lt;/em&gt; do not share any factors with N and T&lt;ul&gt;
&lt;li&gt;&lt;strong&gt; e = 5 &lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;em&gt;e&lt;/em&gt; is used for the encryption process.&lt;/li&gt;
&lt;li&gt;Choose another number &lt;em&gt;d&lt;/em&gt; where &lt;em&gt;e * d mod T = 1&lt;/em&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt; d = 11 because:&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt; 5 * 11 mod 6 = 55 mod 6 = 1&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;em&gt;d&lt;/em&gt; is used for the decryption process.&lt;/li&gt;
&lt;li&gt;The pair N and e is the public key. This is published&lt;ul&gt;
&lt;li&gt;&lt;strong&gt; Public key is (5, 14) &lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The pair N and d is the private key. This is kept a secret.&lt;ul&gt;
&lt;li&gt;&lt;strong&gt; Private key is (11, 14) &lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;To encrypt, a message, represent the message as a numeric value, say &lt;em&gt;m&lt;/em&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt; Let the message be B which in numeric form we have as 2 &lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Then calculate &lt;em&gt;m ^ e mod N&lt;/em&gt; = ciphertext c&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;2 ^ 5 mod 14 = 4&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt; Cipher text is 4&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt; Which in our encoding scheme is D&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;To decrypt ciphertext c back to &lt;em&gt;m&lt;/em&gt; calculate &lt;em&gt;c ^ d mod N&lt;/em&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;4^ 11 mod 14 = 2&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Plain text is 2&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Which in our encoding is B - which is the original value encrypted&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The underlying security of this algorithm is the fact that given the value &lt;em&gt;N&lt;/em&gt; which is public, it is practically impossible to figure out the factors &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt;. If it were possible then it would be possible to derive &lt;em&gt;d&lt;/em&gt; which would make the whole scheme insecure.&lt;/p&gt;
&lt;p&gt;As mentioned earlier, textbook RSA is not used in practice as it is not secure. For example, using textbook RSA to encrypt small messages is insecure, because an eavesdropper can encrypt all the small numbers and quickly observe if any of their encrypted numbers match the ciphertext. This is why in practice, RSA makes use of padding schemes that pad the message before encryption. &lt;/p&gt;
&lt;p&gt;The very first such a padding scheme in PKCS#1. This padding scheme has been shown to also be insecure and should not be used. Hence in practice, the padding scheme recommended to be used with RSA is the Optimal Asymmetric Encryption Padding (OAEP). Hence RSA-OAEP&lt;/p&gt;
&lt;p&gt;Let&#39;s now see how RSA-OAEP looks with a working code example.&lt;/p&gt;
&lt;h3 id=&quot;example-of-rsa-oaep-using-web-crypto-api&quot;&gt;Example of RSA-OAEP using web crypto API&lt;/h3&gt;
&lt;p&gt;In the code sample below, we generate a private/public key pair, use it to encrypt a text, and then decrypt it to retrieve the original plaintext. The code makes use of &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API&quot;&gt;web crypto API&lt;/a&gt; so it should work in most browsers, Deno, or the latest version of node.&lt;/p&gt;

&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;let plainText = &quot;Hello world!&quot;;

const keys = await window.crypto.subtle.generateKey({
   name: &quot;RSA-OAEP&quot;,
   // The length in bits of the RSA modulus
   modulusLength: 2048,
   // The public component e. Recommended value is 65537
   publicExponent: new Uint8Array([1, 0, 1]),
   // hash function required by OAEP
   hash: &quot;SHA-256&quot;,
},
   // A boolean value indicating whether it will be possible
   // to export the key using SubtleCrypto.exportKey() or
   // SubtleCrypto.wrapKey().
   true,
   // An Array indicating what can be done
   // with the newly generated key
   [&quot;encrypt&quot;, &quot;decrypt&quot;]
)

// We encrypt
const ciphertext = await window.crypto.subtle.encrypt(
   { name: &quot;RSA-OAEP&quot; },
   keys.publicKey,
   new TextEncoder().encode(plainText)
)


// We convert ciphertext to a hex string and console logged it
console.log(buf2hex(ciphertext))

// We decrypt
const decrypted = await window.crypto.subtle.decrypt(
   {
       name: &quot;RSA-OAEP&quot;
   },
   keys.privateKey,
   ciphertext
)

// We convert to string
const decryptedPlaintext = new TextDecoder().decode(decrypted);
console.log(`Encrypting and decrypting was successful: ${plainText === decryptedPlaintext}`)

// utility to convert ArrayBuffer to hex string
function buf2hex(buffer: ArrayBuffer) {
   return [...new Uint8Array(buffer)]
       .map(x =&amp;gt; x.toString(16).padStart(2, &#39;0&#39;))
       .join(&#39;&#39;);
}
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;Executing the following code, for example using Deno should give the following output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;deno run &lt;span class=&quot;hljs-built_in&quot;&gt;index&lt;/span&gt;.&lt;span class=&quot;hljs-keyword&quot;&gt;ts&lt;/span&gt;
Check &lt;span class=&quot;hljs-keyword&quot;&gt;file&lt;/span&gt;:///Users/dadepoaderemi/Documents/&lt;span class=&quot;hljs-keyword&quot;&gt;delete&lt;/span&gt;/blogging/assymmetric/&lt;span class=&quot;hljs-built_in&quot;&gt;index&lt;/span&gt;.&lt;span class=&quot;hljs-keyword&quot;&gt;ts&lt;/span&gt;
&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;b69df6eee76c660b8c9c307f89c4a023f455b06cf8da6622c9ff2073...
Encrypting &lt;span class=&quot;hljs-built_in&quot;&gt;and&lt;/span&gt; decrypting was successfu&lt;span class=&quot;hljs-variable&quot;&gt;l:&lt;/span&gt; true
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;drawbacks-of-rsa-and-introduction-to-hybrid-encryption&quot;&gt;Drawbacks of RSA and Introduction to Hybrid Encryption&lt;/h3&gt;
&lt;p&gt;RSA is inefficient. It can only encrypt a small amount of plaintext at a time, and the speed of encryption and decryption is quite slow. This drawback is not limited to RSA but applies to most asymmetric encryption algorithms. This is mainly because these algorithms implement math operations.&lt;/p&gt;
&lt;p&gt;Because of these drawbacks, asymmetric encryption is usually not used to encrypt messages. Instead, it is used as part of what is usually referred to as hybrid encryption constructions. &lt;/p&gt;
&lt;p&gt;The general idea behind hybrid encryption is this: use symmetric encryption for the actual encryption since symmetric encryption is more efficient while asymmetric cryptography is used to exchange the symmetric keys. The part where asymmetric cryptography is used to ensure the parties communicating have the same key is usually called &lt;em&gt;key encapsulation&lt;/em&gt;, while the actual encryption via symmetric encryption is called &lt;em&gt;data encapsulation&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Asymmetric encryption is an example of asymmetric cryptography that can be used for &lt;em&gt;key encapsulation&lt;/em&gt;. In this case, if Alice wants to communicate confidentially with Bob, she generates a symmetric key and then encrypts it using Bob&#39;s public key. This ensures Bob can decrypt with his private key and retrieve the symmetric key to be used for encryption.&lt;/p&gt;
&lt;p&gt;Another scheme is to use Diffie Hellman key exchange, as the asymmetric cryptography system used in exchanging the symmetric key used for actual encryption and decryption.&lt;/p&gt;
&lt;p&gt;The idea of hybrid encryption is very practical, this has led to the creation of well-defined schemes that makes use of hybrid encryption but only expose the typical asymmetric encryption interface to the use. This means the user of such schemes only need to worry about the private and public keys, while internally the scheme makes use of symmetric encryption. This also means the user does not have to manually perform multiple steps that consist of key encapsulation and data encapsulation but only uses the private and public keys to encrypt and decrypt.&lt;/p&gt;
&lt;p&gt;There are many hybrid encryption schemes in existence, although arguably the most widely adopted standard is Elliptic Curve Integrated Encryption Scheme (ECIES). Hence I will quickly show how ECIES looks in practice.&lt;/p&gt;
&lt;p&gt;Unfortunately, Web Crypto API does not support ECIES, so for this demonstration, I will use nodejs and the &lt;em&gt;&lt;a href=&quot;https://www.npmjs.com/package/eciesjs&quot;&gt;eciesjs&lt;/a&gt;&lt;/em&gt; package.&lt;/p&gt;
&lt;p&gt;Create a new node js project and install &lt;em&gt;eciesjs&lt;/em&gt; by running the following command&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;npm&lt;/span&gt; init ecies_demo -y
&lt;span class=&quot;hljs-built_in&quot;&gt;npm&lt;/span&gt; install eciesjs
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then in the &lt;em&gt;index.js&lt;/em&gt; have the following code:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;import { encrypt, decrypt, PrivateKey } from &#39;eciesjs&#39;

const prvKey = new PrivateKey()
const pubKey = prvKey.publicKey
const message = Buffer.from(&#39;message to b&#39;)

// encrypt the message
const encryptedToB = encrypt(pubKey.toHex(), message);

// console log the encrypted message as hex
console.log(encryptedToB.toString(&#39;hex&#39;))

// decrypt the message
const decrypted = decrypt(prvKey.toHex(), encryptedToB).toString()

// confirm original message and decrypted message is same
const isSame = message.toString() === decrypted
console.log(`decrypted and original message is same: ${isSame}`)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code uses a generated public key to encrypt a message which is then decrypted with the corresponding private key and confirmed that the original message and decrypted message are the same.&lt;/p&gt;
&lt;p&gt;As can be seen, the interface only exposes the usage of public-private key pairs and hides the fact that symmetric encryption is being used. In fact, the ECIES scheme is more complex and makes use of other cryptographic primitives like key-derivation function (KDF) and &lt;a href=&quot;geekabyte.io/2021/10/hash-function-in-action-message.html&quot;&gt;HMAC&lt;/a&gt;, &lt;/p&gt;
&lt;p&gt;A functional diagram of ECIES can be seen below:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMBp7v8EIu6CCvVOxQhIDptovn5RUN4EoktXf9km7vt-nrJXiyicaoXEsTYzZvNiUyeEZjPdr8Gxocza6Hfwcc6l-Q6hqTQH-tBmTk0Tsn8-5cZqN8kNGuomETwxpewgazJW3qm05DjoY_ksS7jksfdlO-tMrp9b6V5QOKyoepnNyuNabdwsM/s1538/ecies.png&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1234&quot; data-original-width=&quot;1538&quot; height=&quot;514&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMBp7v8EIu6CCvVOxQhIDptovn5RUN4EoktXf9km7vt-nrJXiyicaoXEsTYzZvNiUyeEZjPdr8Gxocza6Hfwcc6l-Q6hqTQH-tBmTk0Tsn8-5cZqN8kNGuomETwxpewgazJW3qm05DjoY_ksS7jksfdlO-tMrp9b6V5QOKyoepnNyuNabdwsM/w640-h514/ecies.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;p&gt;Source &lt;a href=&quot;https://core.ac.uk/download/pdf/36042967.pdf&quot;&gt;https://core.ac.uk/download/pdf/36042967.pdf&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The good thing is that the end-user does not need to deal directly with this complexity. A simpler interface based on private and public keys is exposed. This is the advantage of using a hybrid encryption scheme like ECIES.&lt;/p&gt;
&lt;h3 id=&quot;additional-resources&quot;&gt;Additional Resources&lt;/h3&gt;
&lt;p&gt;Here are some of the link that covers some of the fundamental mathematics that makes asynchronous encryption work&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Greatest_common_divisor&quot;&gt;GCD&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=3kg-fRncPAM&quot;&gt;Relative Prime&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=DKy98FWHwdg&quot;&gt;Primitive Root&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=DwQ7-k9LkJ4&quot;&gt;Euler’s ϕ-function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic&quot;&gt;Modular Arithmetic&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JD72Ry60eP4&quot;&gt;Prime Numbers &amp;amp; RSA Encryption Algorithm - Computerphile&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description><link>http://www.geekabyte.io/2022/06/introduction-to-asymmetric-encryption.html</link><author>noreply@blogger.com (dade)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMBp7v8EIu6CCvVOxQhIDptovn5RUN4EoktXf9km7vt-nrJXiyicaoXEsTYzZvNiUyeEZjPdr8Gxocza6Hfwcc6l-Q6hqTQH-tBmTk0Tsn8-5cZqN8kNGuomETwxpewgazJW3qm05DjoY_ksS7jksfdlO-tMrp9b6V5QOKyoepnNyuNabdwsM/s72-w640-h514-c/ecies.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-1423158097700864749</guid><pubDate>Sun, 29 May 2022 20:30:00 +0000</pubDate><atom:updated>2022-05-30T10:29:35.527+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">learning rust</category><category domain="http://www.blogger.com/atom/ns#">rust</category><title>A Neophyte&#39;s Introduction to the async/await landscape in Rust</title><description>&lt;p&gt;The truth of the matter is, the async/await features in other programming languages seem to be more straightforward than it is in Rust. For example in JavaScript, you have the syntax that you use, and that is about it. But in Rust, there seem to be more moving parts. &lt;/p&gt;
&lt;p&gt;Tokio? Future? There is a futures crate? Runtimes? How do all these fit into the async/await picture in Rust? &lt;/p&gt;
&lt;p&gt;This is a short post to help clarify some of the terms a developer would encounter when they start exploring asynchronous programming in Rust. It would explain the main moving parts, which are: the standard library&#39;s &lt;code&gt;std::future::Future&lt;/code&gt;, the &lt;code&gt;futures&lt;/code&gt; crates, and asynchronous runtimes like &lt;code&gt;tokio&lt;/code&gt; and &lt;code&gt;async-std&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let get started:&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
&lt;h3 id=&quot;std-future-future&quot;&gt;std::future::Future&lt;/h3&gt;
&lt;p&gt;The crux of asynchronous programming is to maximize computing resources, especially IO-bound computation. One of the ways this is done, is to code in such a way that the computation is not directly executed but written in a suspended form that can be later executed or paused, or retried. &lt;/p&gt;
&lt;p&gt;The type used to express such a computation is &lt;code&gt;std::future::Future&lt;/code&gt;. For example, a print statement that is not executed directly can be written is as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::future::Future;
fn future_print() -&amp;gt; impl Future&amp;lt;Output = ()&amp;gt; {
    async {
        println!(&quot;Hello World!&quot;);
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The return type &lt;code&gt;impl Future&amp;lt;Output = ()&amp;gt;&lt;/code&gt; means this is a function that returns any type that implements the &lt;code&gt;std::future::Future&lt;/code&gt; trait. &lt;/p&gt; To fully understand the syntax which might be a bit obscure, check the &lt;a href=&quot;https://doc.rust-lang.org/book/ch10-02-traits.html&quot;&gt;Trait section&lt;/a&gt; of the Rust book.

&lt;p&gt;The &lt;code&gt;std::future::Future&lt;/code&gt; is part of the standard library and there is no need to depend on any external crate to have access to it.&lt;/p&gt;
&lt;p&gt;To confirm that the &lt;code&gt;future_print&lt;/code&gt; function does not execute directly, let us try and call it in &lt;code&gt;main&lt;/code&gt; to see what happens:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::future::Future;

fn future_print() -&amp;gt; impl Future&amp;lt;Output = ()&amp;gt; {
    async {
        println!(&quot;Hello World!&quot;);
    }
}

fn main() {
    future_print();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The output should be something similar to:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;warning: `async_await` (bin &lt;span class=&quot;hljs-string&quot;&gt;&quot;async_await&quot;&lt;/span&gt;) generated &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; warnings
    Finished dev [unoptimized + debuginfo] target(s) &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0.01&lt;/span&gt;s
     Running `target&lt;span class=&quot;hljs-regexp&quot;&gt;/debug/&lt;/span&gt;async_await`

Process finished with &lt;span class=&quot;hljs-keyword&quot;&gt;exit&lt;/span&gt; code &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, there is no &lt;em&gt;Hello World&lt;/em&gt; printed to the console. Confirming that the &lt;code&gt;std::future::Future&lt;/code&gt;&amp;nbsp;&amp;nbsp;denotes computation that has been described but that is not executed directly and this is the crux of asynchronous programming in Rust.&lt;/p&gt;
&lt;p&gt;In practice, there is usually no need to use the &lt;code&gt;std::future::Future&lt;/code&gt; type directly as the return type. Rust has a syntactic sugar in the form of the &lt;code&gt;async&lt;/code&gt; keyword that makes the code less noisy. The above code snippet can be re-written as:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;async fn future_print() {
    println!(&quot;Hello World!&quot;);
}

fn main() {
    future_print();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is less noisy, even though it is essentially the same as the verbose code that directly uses the &lt;code&gt;std::future::Future&lt;/code&gt; type.&lt;/p&gt;
&lt;p&gt;The question now is, how do a method that returns a future be executed? To answer this we look at the next piece of the async/await story in Rust. The &lt;code&gt;futures&lt;/code&gt; crate, which can be found &lt;a href=&quot;https://crates.io/crates/futures&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;futures-crate-&quot;&gt;futures crate.&lt;/h3&gt;
&lt;p&gt;Formally&amp;nbsp;&lt;code&gt;futures-rs. &lt;/code&gt;This crate provides the other core foundational components needed for asynchronous programming in Rust.&lt;/p&gt;
&lt;p&gt;The components it provides, are not included in the standard library like &lt;code&gt;std::future::Future&lt;/code&gt;, and hence to bring them in, the crate needs to be defined as a dependency in &lt;code&gt;Cargo.toml&lt;/code&gt;. It can be done as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-section&quot;&gt;[dependencies]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;futures&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;0.3.21&quot;&lt;/span&gt; # change to the current version
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Even though it is not included in the standard library it is worth noting that the &lt;code&gt;futures-rs&lt;/code&gt; crate is developed by the Rust core team, as can be seen from the fact that the code repository is under the rust-lang namespace on &lt;a href=&quot;https://github.com/rust-lang/futures-rs&quot;&gt;Github&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;futures-rs&lt;/code&gt; crates include key trait definitions like &lt;code&gt;Stream&lt;/code&gt;, as well as utilities like &lt;code&gt;join!&lt;/code&gt;, &lt;code&gt;select!&lt;/code&gt;, and various futures combinator methods that enable expressive asynchronous control flow. &lt;/p&gt;
&lt;p&gt;This post won&#39;t look at the utilities like &lt;code&gt;join!&lt;/code&gt;, &lt;code&gt;select!&lt;/code&gt;, instead we go back to the initial question we are yet to answer: We have a function that returns a &lt;code&gt;Future&lt;/code&gt;&amp;nbsp;how do we run it?&lt;/p&gt;
&lt;p&gt;To run a &lt;code&gt;Future&lt;/code&gt; in Rust, there is a need for an asynchronous runtime. This runtime is usually called the &lt;em&gt;executor&lt;/em&gt;. The executor is a machinery that is tasked with the management of all the resources required for executing futures. It takes a computation described as a &lt;code&gt;Future&lt;/code&gt; and ensures it is executed asynchronously. &lt;/p&gt;
&lt;p&gt;The &lt;code&gt;futures-rs&lt;/code&gt; crate comes with such an executor which can be accessed via &lt;code&gt;futures::executor::block_on&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;The following code snippet shows its usage:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use futures::executor::block_on;

async fn future_print()  {
    println!(&quot;Hello world&quot;);
}

fn main() {
    block_on(future_print());
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now if the following code is executed, the output should look like the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/Users/dadepoaderemi/.cargo/bin/cargo &lt;span class=&quot;hljs-built_in&quot;&gt;run&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;--color=always --package async_await --bin async_await&lt;/span&gt;
    Finished dev [unoptimized + debuginfo] target(s) &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0.01&lt;/span&gt;s
     Running `target/debug/async_await`
Hello world

Process finished &lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;exit&lt;/span&gt; code &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Confirming that we can execute the future code with the usage of &lt;code&gt;futures::executor::block_on&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;At this point, we have looked at &lt;code&gt;std::future::Future&lt;/code&gt; which is part of the standard library and is used to describe computation to be executed later by a runtime. We also looked at the &lt;code&gt;futures-rs&lt;/code&gt; crate, which provides such a runtime in the form of the &lt;code&gt;futures::executor::block_on&lt;/code&gt; executor.&lt;/p&gt;
&lt;p&gt;The only problem is that the &lt;code&gt;futures::executor::block_on&lt;/code&gt; executor is quite primitive and not powerful enough to be used in a real life production environment. &lt;/p&gt;
&lt;p&gt;To fill the gap for more powerful, feature-rich asynchronous runtimes, various crates have spurned up within the Rust ecosystem. Some popular ones include: &lt;a href=&quot;https://tokio.rs/&quot;&gt;Tokio&lt;/a&gt;, &lt;a href=&quot;https://async.rs/&quot;&gt;async-std&lt;/a&gt;, and &lt;a href=&quot;https://github.com/smol-rs/smol&quot;&gt;smol&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;They all do the same thing: Provide a sophisticated and more powerful runtime that executes asynchronous computations.&lt;/p&gt;
&lt;p&gt;We will use &lt;code&gt;Tokio&lt;/code&gt; to demonstrate. Update the dependencies as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[dependencies]
&lt;span class=&quot;hljs-attr&quot;&gt;futures&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;0.3.21&quot;&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;# change to the current version&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;tokio&lt;/span&gt; = { &lt;span class=&quot;hljs-attr&quot;&gt;version=&quot;1.18.2&quot;,&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;features&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;full&quot;&lt;/span&gt;] } &lt;span class=&quot;hljs-comment&quot;&gt;# change to the current version&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that using external runtimes like &lt;code&gt;tokio&lt;/code&gt; does not necessarily remove the need for the &lt;code&gt;futures-rs&lt;/code&gt; crate, as it contains useful utilities that can still be used alongside the runtime.&lt;/p&gt;
&lt;p&gt;Using the &lt;code&gt;tokio&lt;/code&gt; runtime would look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use tokio::runtime::Runtime;

async fn future_print() {
    println!(&quot;Hello world&quot;)
}

fn main() {
    Runtime::new().unwrap().block_on(future_print());
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works. The only problem though is that this is a bit verbose. To make the code less noisy, we use another Rust language keyword related to async/await, the &lt;code&gt;.await&lt;/code&gt;, and a macro from Tokio: &lt;code&gt;#[tokio::main]&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;In code, it looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;async fn future_print() {
    println!(&quot;Hello world&quot;)
}

#[tokio::main]
async fn main() {
    future_print().await;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running the above code would print something like this into the console:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;hljs-regexp&quot;&gt;/Users/&lt;/span&gt;dadepoaderemi&lt;span class=&quot;hljs-regexp&quot;&gt;/.cargo/&lt;/span&gt;bin/cargo run --color=always --&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; async_await --bin async_await
    Finished dev [unoptimized + debuginfo] target(s) &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0.02&lt;/span&gt;s
     Running `target&lt;span class=&quot;hljs-regexp&quot;&gt;/debug/&lt;/span&gt;async_await`
Hello World!
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Seeing the &lt;em&gt;Hello World!&lt;/em&gt; confirms that we were able to use a runtime provided by Tokio runtime to execute the computation.&lt;/p&gt;

&lt;h3 id=&quot;summary&quot;&gt;Summary&lt;/h3&gt;
&lt;p&gt;Using async/await in Rust is not as straightforward as just using the language syntax as it is with languages like JavaScript or C# etc that have similar asynchronous constructs.&lt;/p&gt;
&lt;p&gt;More moving parts might not be obvious to the beginner Rust developer. This post gave a quick overview of the crucial components:&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;std::future::Future&lt;/code&gt; type is part of the standard library that forms the crux of the asynchronous programming model as it is used to denote computation that can be executed asynchronously. &lt;/p&gt;
&lt;p&gt;The &lt;code&gt;futures-rs&lt;/code&gt; crates, maintained by the Rust team, provide more of the foundations for asynchronous programming in Rust. It comes with a simple executor that can be used as a runtime to execute asynchronous code.&lt;/p&gt;
&lt;p&gt;And finally, we looked at Tokio, as an example of an external crate that provides a more sophisticated asynchronous runtime that is usually used in a production-like environment. &lt;/p&gt;&lt;p&gt;Other well known crates providing asynchronous runtimes include smol, and async-std.&lt;/p&gt;
&lt;p&gt;In summary, the core async/await landscape can be described as comprising the standard library type of &lt;code&gt;std::future::Future&lt;/code&gt; which denotes asynchronous computation. The &lt;code&gt;futures-rs&lt;/code&gt; crate provides additional foundational components: traits, macros utilities, etc and then finally the 3rd party runtimes that are external to the standard library which provide sophisticated executors used for running asynchronous code.&lt;/p&gt;
&lt;p&gt;This post does not attempt to go into details about how to use async/await in Rust. It seeks to just be the introductory text that explains the lay of the land. To learn more about asynchronous programming in Rust, you can check the following resources:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ThjvMReOXYM&quot;&gt;Crust of Rust: async/await&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=FNcXf-4CLH0&quot;&gt;Async/await in Rust: Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://rust-lang.github.io/async-book/01_getting_started/01_chapter.html&quot;&gt;Asynchronous Programming in Rust&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description><link>http://www.geekabyte.io/2022/05/a-neophytes-introduction-to-asyncawait.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-7265213964199956081</guid><pubDate>Sat, 07 May 2022 19:37:00 +0000</pubDate><atom:updated>2022-06-15T18:52:57.169+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Introduction to Key Exchange for the Working Developer</title><description>&lt;p&gt;In &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-symmetric-encryption.html&quot;&gt;Introduction to Symmetric Encryption for the Working Developer&lt;/a&gt;, we saw how to encrypt and decrypt data. Being symmetric encryption, both the process of encryption and decryption needed the same key. This poses a challenge, which was not addressed in the post: How do one get across the same key to both parties who want to engage in encrypted communication?&lt;/p&gt;
&lt;p&gt;Basically how do we perform key exchange? How do we get the same key to parties who want to encrypt and decrypt messages? &lt;/p&gt;
&lt;p&gt;An approach is perhaps for the parties involved to first meet in person and exchange the key? &lt;/p&gt;
&lt;p&gt;Another approach could be to use another communication channel to first share the key? But then again, if the other communication channel is digital, and it uses symmetric encryption, how should its encryption key be also exchanged? This becomes a catch 22 real quick.&lt;/p&gt;
&lt;p&gt;This is the problem Key exchange schemes seek to solve, and thankfully there is a secure way to have two parties exchange secret keys without the need to physically meet in person. This is what this post is about. We will be looking at two popular mechanisms for key exchange: Diffie-Hellman key exchange procedures and application of RSA for key exchange.&lt;/p&gt;
&lt;p&gt;As always, as with the other posts in this series, the idea is to provide the basic information needed by the working developer to be able to understand and use these cryptographic primitives without going into the thick of their internal details or implementation.&lt;/p&gt;
&lt;p&gt;This post contains the following sections&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Entering the realm of Public Key Cryptography&lt;/li&gt;
&lt;li&gt;Introduction to Diffie-Hellman Key Exchange: An Intuition.&lt;/li&gt;
&lt;li&gt;Whirlwind tour of the Mathematics&lt;/li&gt;
&lt;li&gt;Diffie-Hellman in code&lt;/li&gt;
&lt;li&gt;Diffie-Hellman Standards&lt;/li&gt;
&lt;li&gt;Using RSA for key exchange&lt;/li&gt;
&lt;li&gt;Conclusion and References&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;entering-the-realm-of-public-key-cryptography&quot;&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;Entering the Realm of Public Key Cryptography&lt;/h2&gt;
&lt;p&gt;Public key cryptography (or Asymmetric key cryptography) is a class of cryptography primitives that makes use of dissimilar keys. This is different from Symmetric key cryptography which makes use of similar keys for its operations. &lt;/p&gt;
&lt;p&gt;Public key cryptography also relies more heavily on Mathematics, especially number theory, and the security properties and guarantees it provides is often as a result of a direct consequence of some mathematical theory. Hence in discussion of cryptographic primitives that can be classified as public key cryptography there is more encounter of mathematical notations and theorems.&lt;/p&gt;
&lt;p&gt;This post will not go into the mathematical underpinning of the cryptography primitives discussed. Instead, I will highlight the mathematical theories in this post and point to resources, motivated readers can check out to learn more.&lt;/p&gt;
&lt;p&gt;Let&#39;s start by exploring one of the two schemes that uses public key cryptography for key exchange: that is: Diffie-Hellman. &lt;/p&gt;
&lt;h2 id=&quot;introduction-to-diffie-hellman-key-exchange-an-intuition&quot;&gt;Introduction to Diffie-Hellman Key Exchange: An Intuition&lt;/h2&gt;
&lt;p&gt;The Diffie-Hellman key exchange is a method that allows two parties, communicating in a public, insecure channel, to exchange messages that allows them to derive the same secret key. But the method has the property that eavesdroppers observing the messages being exchanged won&#39;t be able to use it to construct the secret key derived by the parties engaged in the key exchange.&lt;/p&gt;
&lt;p&gt;How is this possible? To have two parties exchange two numbers, that anyone can see, and then, separately, these two parties use the numbers they receive from each other to compute another number privately, and the number they compute will end up being the same (ie the secret key) but the people that observed the numbers that was exchange cannot do the same computation to arrive at the secret key?&lt;/p&gt;
&lt;p&gt;A good intuition to have about how the process works is this. It is a process for two parties to first exchange two secret numbers. But they do not just exchange this secret number, they first mix it up with another number both parties agree with. &lt;/p&gt;
&lt;p&gt;So each party comes up with a secret number, mixes it up with a publicly agreed number and shares.  &lt;/p&gt;
&lt;p&gt;After the sharing, both parties have the secret number generated by the other party mixed up with an agreed number. Anyone observing the exchange can only see the results of the mixed number (that is, &lt;em&gt;party A&#39;s&lt;/em&gt; secret number mixed with an agreed number which is not secret and &lt;em&gt;party B&#39;s&lt;/em&gt; secret number mixed with the same agreed number). The security of this exchange boils down to the inability to break apart the result of this number mixing to reveal the secret number that was mixed with it. In Diffie-Hellman, this is impossible to achieve based on the discrete algorithm problem which will be briefly explored later on. But for this intuition, we agree that, parties mixed numbers and share, and anyone observing cannot break this number apart.&lt;/p&gt;
&lt;p&gt;After the mixing and sharing what do we have? We actually have both parties having each other&#39;s secret number. Only that, this secret number they have of each other is not &quot;bare&quot; but mixed up with an agreed number.&lt;/p&gt;
&lt;p&gt;What then happens is that both parties perform a computation using their secret number on the other party&#39;s secret number (but mixed up in an agreed number) and they will both arrive at another secret number which can be used as the secret key.&lt;/p&gt;
&lt;p&gt;That is the intuition. The Diffie-Hellman is a process for two parties to first initially exchange a secret number mixed up with an agreed and non-secretive number, and then use this to perform a computation. What ends up happening is that the inputs to the computation on each party&#39;s side are the same. That is for &lt;em&gt;party A&lt;/em&gt;, it is &lt;em&gt;compute(secret A,  M1 = (mixing number + secret B))&lt;/em&gt; while for &lt;em&gt;party B&lt;/em&gt;, it is &lt;em&gt;compute(secret B, M2 = (mixing number + secret A))&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;Even if the mixing number is known, as long as it is impossible to break &lt;em&gt;M1&lt;/em&gt; or &lt;em&gt;M2&lt;/em&gt; apart to retrieve &lt;em&gt;secret B&lt;/em&gt; or &lt;em&gt;secret A&lt;/em&gt;, then the scheme works.&lt;/p&gt;
&lt;p&gt;That is the intuition of the process. Now let&#39;s dig deeper into how things work, without also going into too much of the mathematics.&lt;/p&gt;
&lt;h2 id=&quot;whirlwind-tour-of-the-mathematics&quot;&gt;Whirlwind tour of the Mathematics&lt;/h2&gt;
&lt;p&gt;The idea of this section is to give an overview of the key concepts from mathematics that come together to make Diffie-Hellman possible. For obvious reasons, an in depth coverage of these concepts is not possible in this one post, but links would be sprinkled in pointing to where more information can be gotten.&lt;/p&gt;
&lt;p&gt;So let&#39;s start.&lt;/p&gt;
&lt;p&gt;We all know about &lt;a href=&quot;https://www.os3.nl/_media/info/set_theory.pdf&quot;&gt;sets&lt;/a&gt; from elementary mathematics. When sets fulfil certain characteristics, they are said to form a &lt;a href=&quot;https://brilliant.org/wiki/group-theory-introduction/&quot;&gt;group&lt;/a&gt;. These characteristics include &lt;a href=&quot;https://www.youtube.com/watch?v=BXg3cAbmDjM&quot;&gt;Closure&lt;/a&gt;, Associativity, Presence of an Identity Element and presence of an Inverse element. The study of these characteristics is called group theory.&lt;/p&gt;
&lt;p&gt;A key part of a group is the presence of a &lt;a href=&quot;https://en.wikipedia.org/wiki/Binary_operation&quot;&gt;binary operation&lt;/a&gt;. That is an operation that operates on two inputs to produce an output that is also a member of the set. Examples of binary operations include addition, or multiplication or Modulo multiplication. &lt;a href=&quot;https://brilliant.org/wiki/modular-arithmetic/&quot;&gt;Modulo operation&lt;/a&gt; are mathematical operations involving numbers that wrap around. It is also often called clock arithmetics. &lt;/p&gt;
&lt;p&gt;The two flavors of Diffie-Hellman algorithms that we have, Diffie-Hellman in a modulo multiplicative group and Elliptic Curve Diffie Hellman (ECDH) both make use of groups and binary operations. &lt;/p&gt;
&lt;p&gt;In the first flavor, the group includes the set of strictly positive integers 1, 2, p – 1 for p a prime number, along with modular multiplication, where the modulo is a prime. &lt;/p&gt;
&lt;p&gt;The second flavor makes use of groups that form an &lt;a href=&quot;https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/&quot;&gt;elliptic curve&lt;/a&gt;, while the binary operation is addition. The algorithm for ECDH is a bit involved when compared hence a quick overview of the first flavor is given in this post.&lt;/p&gt;
&lt;p&gt;So as stated, the first (or classic) Diffie-Hellman algorithm makes use of groups made up of positive integers, with binary operation being multiplication with the modulo being a prime P.&lt;/p&gt;
&lt;p&gt;The algorithm involves picking a number that forms a &lt;a href=&quot;https://brilliant.org/wiki/primitive-roots/&quot;&gt;primitive root&lt;/a&gt; with the modulo prime. This number that we pick when multiplied with itself ad-infinitum, in modulo prime, will generate a &lt;a href=&quot;https://brilliant.org/wiki/subgroup/&quot;&gt;cyclic subgroup&lt;/a&gt;, ie when it is raised to power n, where n = 1,2,3, (infinity - 1), under modulo prime P, will produce a cyclic group. This extra characteristic is important in order to ensure the &lt;a href=&quot;https://www.youtube.com/watch?v=za9azzh4v9A&quot;&gt;discrete logarithm problem&lt;/a&gt; is sufficiently hard enough to ensure the security of the algorithm.&lt;/p&gt;
&lt;p&gt;And the discrete logarithm problem is a class of problems that is sometimes referred to as &lt;a href=&quot;https://en.wikipedia.org/wiki/One-way_function&quot;&gt;one way function&lt;/a&gt;, i.e. functions easy to compute given inputs, but hard or almost impossible to retrieve the inputs given the results of the computation. The discrete logarithm problem simply states that, given a number &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y&lt;/em&gt; where &lt;em&gt;y&lt;/em&gt; is greater than &lt;em&gt;x&lt;/em&gt;, it is hard to find the number of times &lt;em&gt;n&lt;/em&gt;, &lt;em&gt;x&lt;/em&gt; needs to be multiplied by itself to result into &lt;em&gt;y&lt;/em&gt;, under modulo of another number &lt;em&gt;p&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;In the classic Diffie-Hellman algorithm, a prime number &lt;em&gt;P&lt;/em&gt; and an integer &lt;em&gt;g&lt;/em&gt;, the generator is agreed upon by the two parties. This is what they use to mix the secret number they want to pass on to each other that would be used to derive the private key.&lt;/p&gt;
&lt;p&gt;Party A generates a secret number &lt;em&gt;sa&lt;/em&gt;, and then &lt;em&gt;mixes&lt;/em&gt; it up with prime p and generator g by computing = &lt;em&gt;AK = g^sa mod p&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;AK&lt;/em&gt; is referred to as a public key and Party A sends this value to party B.&lt;/p&gt;
&lt;p&gt;Party B generates a secret number &lt;em&gt;sb&lt;/em&gt;, and then &lt;em&gt;mixes&lt;/em&gt; it up with prime &lt;em&gt;p&lt;/em&gt; and generator &lt;em&gt;g&lt;/em&gt; by computing = &lt;em&gt;BK = g^sb mod p&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;BK&lt;/em&gt; is referred to as a public key and party B sends this value to party A.&lt;/p&gt;
&lt;p&gt;At this point, party A has &lt;em&gt;BK&lt;/em&gt;, while party B has &lt;em&gt;AK&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;Party A now computes the secret key by computing &lt;em&gt;SK= BK^sa mod p&lt;/em&gt; and party B also computes the secret key by computing &lt;em&gt;SK= AK^sb mod p&lt;/em&gt;. They both arrive at the same value because:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;BK^sa = (g^sb)sa = g^(sb)(sa) = (g^sa)sb = AK^sa mod p&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The two values publicly transmitted are &lt;em&gt;AK = g^sa mod p&lt;/em&gt; and &lt;em&gt;BK = g^sb mod p&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;&lt;em&gt;g&lt;/em&gt; and &lt;em&gt;p&lt;/em&gt; are known, &lt;em&gt;AK&lt;/em&gt; and &lt;em&gt;BK&lt;/em&gt; are also known, as they are communicated in the clear. But anyone observing these numbers won&#39;t be able to derive what &lt;em&gt;sa&lt;/em&gt; or &lt;em&gt;sb&lt;/em&gt; is. Because of the discrete logarithm problem. &lt;/p&gt;&lt;p&gt;It is worth mentioning that in practice, the &lt;i&gt;SK &lt;/i&gt;arrived is not used directly as the secret key, but usually passed through a &lt;a href=&quot;https://en.wikipedia.org/wiki/Key_derivation_function&quot;&gt;Key derivation function&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let&#39;s see how this procedure looks in code.&lt;/p&gt;
&lt;h2 id=&quot;diffie-hellman-in-code&quot;&gt;Diffie-Hellman in code&lt;/h2&gt;
&lt;p&gt;Before showing the code, let&#39;s go over the steps again.&lt;/p&gt;
&lt;p&gt;As stated, the objective is for two parties to arrive at the same secret key that can be used for symmetric encryption, without having to directly share the key.&lt;/p&gt;
&lt;p&gt;A rough step by step outline of how it works is as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Both Alice and Bob agree on using Diffie-Hellman. This involves agreeing on two numbers. One small usually referred to as g, and another big, which is a prime number, usually referred to as p. &lt;/li&gt;
&lt;li&gt;Alice generates a secret number. Performs a modulus computation with it together with g and the prime number p. This computation derives another number called the public key. This is why this procedure falls under Public Key Cryptography.&lt;/li&gt;
&lt;li&gt;Bob also does the same.  &lt;/li&gt;
&lt;li&gt;Alice gives Bob her public number, while keeping her secret one. Bob also gives Alice his public number and keeps his secret number. 
Now Alice has her secret number and technically Bob&#39;s secret number mixed within Bob&#39;s public number. Bob also has his secret number and Alice&#39;s secret number mixed in the public number he received from her.&lt;/li&gt;
&lt;li&gt;Alice uses her secret number and Bob&#39;s public number to calculate another number&lt;/li&gt;
&lt;li&gt;Bob does the same, using his own secret number and Alice&#39;s public number.&lt;/li&gt;
&lt;li&gt;Both Alice and Bob will then arrive at the same generated number which can then be used for symmetric encryption.&lt;/li&gt;
&lt;li&gt;Eve who observed all the exchanges, could know the algorithm being used and can see all the numbers exchanged, including the g and p agreed upon, won&#39;t be able to compute the shared secret both Alice and Bob compute independently.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The following Javascript code snippets in nodejs demonstrates how the Diffie-Hellman scheme can be put to use.&lt;/p&gt;
&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; crypto = require(&#39;crypto&#39;)
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;assert&lt;/span&gt; = require(&#39;&lt;span class=&quot;hljs-keyword&quot;&gt;assert&lt;/span&gt;&#39;);


&lt;span class=&quot;hljs-comment&quot;&gt;// -- Select mod p group&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;// Alice is using the modp15 group&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; groupA = crypto.getDiffieHellman(&#39;modp15&#39;)
&lt;span class=&quot;hljs-comment&quot;&gt;// const groupA = crypto.createECDH(&#39;brainpoolP160t1&#39;)&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;// Bob is also using the modp15 group&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; groupB = crypto.getDiffieHellman(&#39;modp15&#39;)
&lt;span class=&quot;hljs-comment&quot;&gt;// const groupB = crypto.createECDH(&#39;brainpoolP160t1&#39;)&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;// The modp15 group just like others define same generator and prime. hence the prime and generator for groupA and groupB should be same&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;assert&lt;/span&gt;(groupA.getPrime().&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;) === groupB.getPrime().&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;))
&lt;span class=&quot;hljs-keyword&quot;&gt;assert&lt;/span&gt;(groupA.getGenerator().&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;) === groupB.getGenerator().&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;))


&lt;span class=&quot;hljs-comment&quot;&gt;// -- Generate the keys&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;// With this call, the secret key k1 is generated&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// The k1 is then use to generate the public key, which is = g^k1 mod p&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// Note that new k1 is generated on each invocation of this function.&lt;/span&gt;
groupA.generateKeys()

&lt;span class=&quot;hljs-comment&quot;&gt;// With this call, the secret key k2 is generated&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// The k2 is then use to generate the public key, which is = g^k2 mod p&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// Note that new k2 is generated on each invocation of this function.&lt;/span&gt;
groupB.generateKeys()


&lt;span class=&quot;hljs-comment&quot;&gt;// At this point the public key can be shared with other parties which can then be used to arrive at the shared secret&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// Not that the private key is also available via getPrivateKey call but there should be no need to retrieve this. Having&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// this value known by a malicious actor will compromise the integrity of the protocol&lt;/span&gt;
console.&lt;span class=&quot;hljs-built_in&quot;&gt;log&lt;/span&gt;(`Public key of group A &lt;span class=&quot;hljs-variable&quot;&gt;${groupA&lt;/span&gt;.getPublicKey().&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;)}`)
console.&lt;span class=&quot;hljs-built_in&quot;&gt;log&lt;/span&gt;(`Public key of group B &lt;span class=&quot;hljs-variable&quot;&gt;${groupB&lt;/span&gt;.getPublicKey().&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;)}`)


&lt;span class=&quot;hljs-comment&quot;&gt;// --- Now each party use the other public key to generate the shared secret&lt;/span&gt;

let sharedSecretA = groupA.computeSecret(groupB.getPublicKey())
let sharedSecretB = groupB.computeSecret(groupA.getPublicKey())


&lt;span class=&quot;hljs-comment&quot;&gt;// Confirm that same value was arrived at&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;assert&lt;/span&gt;(sharedSecretA.&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;) === sharedSecretB.&lt;span class=&quot;hljs-keyword&quot;&gt;toString&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hex&quot;&lt;/span&gt;))
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;diffie-hellman-standards&quot;&gt;Diffie-Hellman Standards&lt;/h2&gt;
&lt;p&gt;The Diffie-Hellman scheme is made up of components that can be varied. Depending on how these components are configured, the security guarantees of the scheme can be affected. &lt;/p&gt;
&lt;p&gt;The main components that are configurable is the value of g (the generator), and p (the prime) to be used.&lt;/p&gt;
&lt;p&gt;Thing is, anyone implementing Diffie-Hellman key exchange is free to pick whatever value they think is secured for these two components. For example this &lt;a href=&quot;https://github.com/cryptosense/diffie-hellman-groups/blob/master/gen/common.json&quot;&gt;file&lt;/a&gt; contains some popular Diffie-Hellman configuration observed in the wild.&lt;/p&gt;
&lt;p&gt;The only problem is, not all values lead to a secured scheme. For example in 2016, it was discovered that &lt;a href=&quot;https://linux.die.net/man/1/socat&quot;&gt;socat&lt;/a&gt; a networking utility, was using Diffie-Hellman configuration that makes it insecure. Hence as a developer, implementing or using any service that makes use of Diffie-Hellman key, to be aware what secured configurations are being used.&lt;/p&gt;
&lt;p&gt;To help with this, there are recommendations stated in various RFCs. These recommendations are largely categorized into two: Recommended values to be used for multiplicative groups and those based on elliptic curves.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Recommendation for DH&lt;/strong&gt;
For the multiplicative groups, it is advised to use prime numbers whose values are not less than 2048 bits. This ensures that a minimum of 128 bit of security is provided. The recent RFC that contains up to date best practices and recommendations can be found in &lt;a href=&quot;https://datatracker.ietf.org/doc/html/rfc7919&quot;&gt;RFC 7919&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Recommendation for ECDH&lt;/strong&gt;
For the Elliptic curve diffie-hellman, there are a couple of curves that most applications have standardized around. These include P-256, Curve25519, and Curve448. The curve  P-256, and Curve25519 provides 128 bit of security, while Curve448 offers around 224 bit of security. When Curve25519 is used to implement the Diffie-Hellman key exchange, it is also referred to as &lt;a href=&quot;https://cryptography.io/en/latest/hazmat/primitives/asymmetric/x25519/&quot;&gt;X25519&lt;/a&gt;. ECDH is preferred over DH due to its smaller key size. To get a 128 bit of security DH requires nothing less than 2048 bits, but with ECDH, the requirement is nothing less than 256 bits.&lt;/p&gt;
&lt;h2 id=&quot;using-rsa-for-key-exchange&quot;&gt;Using RSA for key exchange&lt;/h2&gt;
&lt;p&gt;RSA is a popular asymmetric crypto-system which can also be used for exchanging keys. RSA by itself is a distinct topic that should be covered separately but for completeness it is mentioned here as another way for two parties to exchange secret keys. &lt;/p&gt;
&lt;h2 id=&quot;conclusion-and-references&quot;&gt;Conclusion and References&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Two parties can arrive at the same secret number by performing the Diffie Hellman key exchange. This helps solve the problem of how two parties securely share the secret key needed for encryption.&lt;/li&gt;
&lt;li&gt;Diffie Hellman requires numbers that form what is mathematically known as groups. Two popular groups are widely used: Multiplicative groups modulo a prime number and Elliptic curves&lt;/li&gt;
&lt;li&gt;When Multiplicative groups modulo a prime number is used, it is usually referred to as just Diffie-Hellman ie DH&lt;/li&gt;
&lt;li&gt;When Elliptic curves are used, it is usually referred to as Elliptic Curve Diffie Hellman ie  ECDH&lt;/li&gt;
&lt;li&gt;The recommended standard to use for DH is found in RFC 7919&lt;/li&gt;
&lt;li&gt;The popular curves used in ECDH are P-256, Curve25519, and Curve448, with Curve25519 being quite popular.&lt;/li&gt;
&lt;li&gt;When Curve25519 is used to implement the Diffie-Hellman key exchange, it is also referred to as X25519.&lt;/li&gt;
&lt;li&gt;ECDH is preferred over DH due to its smaller key size. To get a 128 bit of security DH requires nothing less than 2048 bits, but with ECDH, the requirement is nothing less than 256 bits.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Mathematical Concepts&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.os3.nl/_media/info/set_theory.pdf&quot;&gt;Introduction to set theory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://brilliant.org/wiki/group-theory-introduction/&quot;&gt;Introduction to group theory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://brilliant.org/wiki/subgroup/&quot;&gt;Subgroup&lt;/a&gt;
&lt;a href=&quot;https://en.wikipedia.org/wiki/Generating_set_of_a_group&quot;&gt;Generators&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic&quot;&gt;Modular Arithmetic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.khanacademy.org/computing/computer-science/cryptography/modern-crypt/v/discrete-logarithm-problem&quot;&gt;Discrete Log Problem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NF1pwjL9-DE&quot;&gt;Elliptic Curves&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Yjrfm_oRO0w&quot;&gt;Diffie-Hellman Explained&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description><link>http://www.geekabyte.io/2022/05/introduction-to-key-exchange-for.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-5945205437818580595</guid><pubDate>Thu, 05 May 2022 16:06:00 +0000</pubDate><atom:updated>2022-05-05T18:20:12.253+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Introduction to Authenticated Encryption for the Working Developer</title><description>&lt;p&gt;In &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-symmetric-encryption.html&quot;&gt;Introduction to Symmetric Encryption for the Working Developer&lt;/a&gt;, I presented an overview of symmetric encryption. Which as explained in the post, is a process for establishing confidentiality during communication between two parties. &lt;/p&gt;
&lt;p&gt;The only problem is that just encrypting data using symmetric encryption does not provide all the security requirements needed during secure communication. &lt;/p&gt;
&lt;p&gt;The issue is that, it is still possible for an eavesdropper to tamper with the message even without being able to make sense of the ciphertexts, and the receiving party won&#39;t be made aware that the message they are decrypting has been tampered with and is not exactly the original one that was sent.&lt;/p&gt;
&lt;p&gt;Hence even though encryption gives us confidentiality, done alone, it does not guarantee the other security requirements like authenticity/integrity that is often needed - i.e. it does not guarantee that a message came from the right party (authenticity) and it has not been modified in any way (integrity). &lt;/p&gt;
&lt;p&gt;Encryption alone is not enough, we need authenticated encryption. This post will introduce the concept of authenticated encryption.&lt;/p&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;

&lt;h2 id=&quot;what-is-authenticated-encryption&quot;&gt;What is Authenticated Encryption?&lt;/h2&gt;
&lt;p&gt;In &lt;a href=&quot;https://www.geekabyte.io/2021/10/hash-function-in-action-message.html&quot;&gt;Hash Function in Action: Message Authentication Codes&lt;/a&gt; a similar argument was made regarding hash functions. Where it was stated that hash functions are never enough and there is the need for message authentication to also ensure things like authenticity and integrity.&lt;/p&gt;
&lt;p&gt;How then can authenticated encryption be achieved? Do we use a similar approach that was used in message authentication?&lt;/p&gt;
&lt;p&gt;Well, an approach to achieving authenticated encryption is to take the output of encryption and then apply message authentication code to it. &lt;/p&gt;
&lt;p&gt;For example, using HMAC to create an authentication tag (hash/digest of the cipher text)). Both the ciphertext and the authentication tag is then sent during communication. &lt;/p&gt;
&lt;p&gt;In general such manual constructions are referred to as EtM (Encrypt-then-MAC) and a specific construction of it would be AES-CBC-HMAC. Which is a construction where you encrypt using AES-CBC and then create an authentication tag using HMAC.&lt;/p&gt;
&lt;p&gt;The problem with this approach is that it is error prone. It is fickle and possible to make simple errors that lead to tremendous security issues. &lt;/p&gt;
&lt;p&gt;For example one needs to ensure that the same key is not used for both encryption and generating the HMAC. &lt;/p&gt;
&lt;p&gt;Also special care needs to be taken that the IV values used for the AES are truly random and never reused. Also because two separate cryptographic primitives need to be separately implemented, it does not make for the most efficient approach.&lt;/p&gt;
&lt;p&gt;Because of these problems with manually constructed EtM schemes, it is not recommended to manually construct authenticated encryptions. Instead the safe advice is to make use of all-in-one constructions that simplify the process of having authenticated encryption. &lt;/p&gt;
&lt;p&gt;This is what is discussed in the next section.&lt;/p&gt;
&lt;h2 id=&quot;all-in-one-authenticated-encryption-constructions-and-associated-data&quot;&gt;All-in one Authenticated Encryption Constructions and Associated Data&lt;/h2&gt;
&lt;p&gt;All-in-one authenticated encryptions can either be based on Advanced Encryption Scheme (AES) or using another algorithm apart from AES.&lt;/p&gt;
&lt;p&gt;The all-in-one construction for achieving authenticated encryption that builds on AES does so by having an AES mode of operations that include authentication. For more about modes of operation, see &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-symmetric-encryption.html&quot;&gt;Introduction to Symmetric Encryption for the Working Developer&lt;/a&gt;. &lt;/p&gt;
&lt;p&gt;They do so in such a way as to hide the complexity and the various moving parts, presenting a much simpler interface to developers. &lt;/p&gt;
&lt;p&gt;These all-in-one constructs also provide the ability to optionally attach some metadata with the ciphertext, if that is the case, then they are called Authenticated Encryption with Associated Data (AEAD). &lt;/p&gt;
&lt;p&gt;An example of such a mode that supports both authentication with the ability to attach associated data is Galois/counter mode (GCM). &lt;/p&gt;

&lt;p&gt;The associated data that is attached is unencrypted. &lt;/p&gt;
&lt;p&gt;What then is the use you might ask? &lt;/p&gt;
&lt;p&gt;The associated data is for scenarios where you have data that does not need to be hidden, but must go along with some other data that needs to be hidden.&lt;/p&gt;

&lt;p&gt;An example of such a scenario is a network packet, where the body which contains the data should be encrypted, while the headers, which do not contain any sensitive data and are used by network equipment like routers, can remain in plaintext. But even though the headers are in plaintext, each header needs to be associated with the encrypted data it belongs with. Using AEAD, the header can be the associated data. This means that the same associated data used during encryption, needs to be provided on decryption. If the associated data has been tampered with, the decryption process will fail. &lt;/p&gt;

&lt;p&gt;The associated data is a flexible component of AEAD, and can be used for anything. The general idea is that it provides some sort of encryption context. This encryption context can be whatever that is required for it to be.&lt;/p&gt;

&lt;p&gt;There are other modes of operation that can be used with AES that are AEAD. This Wikipedia &lt;a href=&quot;https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Authenticated_encryption_with_additional_data_(AEAD&quot;&gt;link&lt;/a&gt;&amp;nbsp;provides an overview of some of this mode. &lt;/p&gt;
&lt;p&gt;There is also ChaCha20-Poly1305 which is an AEAD. It is a separate encryption scheme and not just a mode of operation of AES. &lt;/p&gt;
&lt;p&gt;Even though ChaCha20-Poly1305 is newer than AES and not a standard, it has grown to be a solid scheme and a popular alternative to AES. &lt;/p&gt;
&lt;p&gt;The rest of this post looks at AES-GCM and ChaCha20-Poly1305.&lt;/p&gt;
&lt;h2 id=&quot;aes-gcm-authenticated-encryption-and-additional-data-&quot;&gt;AES-GCM Authenticated Encryption and Associated Data.&lt;/h2&gt;
&lt;p&gt;AES-GCM is an AEAD. It is constructed from AES used with the Galois/Counter Mode. By it being an AEAD, it means it provides authenticated encryption out of the box (the AE part in AEAD), with the ability to add associated data (the ED part in AEAD). &lt;/p&gt;
&lt;p&gt;The Web Crypto API supports AES-GCM, hence can be used within a browser or Deno. Using it is similar to the code snippet presented in &lt;a href=&quot;https://www.geekabyte.io/2022/05/introduction-to-symmetric-encryption.html&quot;&gt;Introduction to Symmetric Encryption for the Working Developer&lt;/a&gt;. The only difference is, instead of passing in &quot;AES-CBC&quot; and the algorithm identifier, the string &quot;AES-GCM&quot; is used instead. The updated code is reproduced below. It also makes use of associated data. &lt;/p&gt;

&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;// We generate a key
// See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey
let key = await crypto.subtle.generateKey({
   name: &#39;AES-GCM&#39;,
   length: 128
}, false, [&#39;encrypt&#39;, &#39;decrypt&#39;]);

// We generate random 16 bytes to be used as initialization vector
let iv = new Uint8Array(16);
// and fill it with random numbers
// see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
await crypto.getRandomValues(iv);

// The web crypto requires data to be in ArrayBuffer
let plaintext = new TextEncoder().encode(&quot;hello world&quot;);

// The encryption and decryption requires specifying certain parameters:
// the algorithm and initialization vector, associated data etc
// see https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams
let associatedData = new TextEncoder(&quot;utf-8&quot;).encode(&quot;Greeting&quot;);

let param = {
   name: &#39;AES-GCM&#39;,
   iv,
   associatedData,
};

// We encrypt the plaintext to get the ciphertext
let ciphertext = await crypto.subtle.encrypt(param, key, plaintext);

// We decode and console logged the ciphertext
console.log(new TextDecoder(&quot;utf-8&quot;).decode(ciphertext))

// We decrypt the ciphertext back to plaintext
let deCryptedPlaintext = await window.crypto.subtle.decrypt(param, key, ciphertext);

// We tranform the plaintext from bytes to string and then print it out
console.log(new TextDecoder(&quot;utf-8&quot;).decode(deCryptedPlaintext));

// Causing decryption to fail by providing different associated data

// Create another associated data and param
let wrongAssociatedData = new TextEncoder(&quot;utf-8&quot;).encode(&quot;Payment&quot;);

let wrongParam = {
   name: &#39;AES-GCM&#39;,
   iv,
   wrongAssociatedData,
};


// Decryption would fail because the associated data used for decryption &quot;Payment&quot;
// is different from one used for encryption &quot;Greeting&quot;
await window.crypto.subtle.decrypt(wrongParam, key, ciphertext);

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code above makes use of AES-GCM as the AEAD. It provided an associated data. It demonstrates encryption and decryption. It also shows that the decryption will fail, if a different associated data, from the one used at encryption is attempted for decryption. &lt;/p&gt; 


&lt;h2 id=&quot;chacha20-poly1305&quot;&gt;ChaCha20-Poly1305&lt;/h2&gt;
&lt;p&gt;Unlike AES-GCM, (which is an AES), ChaCha20-Poly1305 is an entirely different encryption scheme designed by Daniel J. Bernstein. It is really a combination of a stream cipher (ChaCha20) and a MAC (Poly1305). &lt;/p&gt;
&lt;p&gt;Even though ChaCha20-Poly1305 is not standardised by NIST, it has been specified as an RFC by Google in rfc7539. It has also seen massive adoption in the industry, being supported in protocols like OpenSSH, TLS etc. Hence it is a battle tested encryption scheme and can be safely used.&lt;/p&gt;
&lt;p&gt;As of this writing, Web Crypto API does &lt;a href=&quot;https://github.com/w3c/webcrypto/issues/223&quot;&gt;not support&lt;/a&gt; ChaCha20-Poly1305, so by extension is not available in a browser environment or Deno. &lt;/p&gt;
&lt;p&gt;On the other hand, ChaCha20-Poly1305 can be used from Node since the Node crypto API depends on OpenSSL. So if you have the version of OpenSSL that supports ChaCha20-Poly1305, it can be used via Node.&lt;/p&gt;

&lt;p&gt;The code snippet below shows how to use ChaCha20-Poly1305 in Node.&lt;/p&gt;

&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;const { randomBytes, createDecipheriv, createCipheriv } = await import(&#39;node:crypto&#39;);

// chacha20-poly1305 requires 256 bit (32 byte) as key 
const key = randomBytes(32);
// Also a 96 bit iv/nonce
const iv = randomBytes(12);;
// create some associated data
let aad = Buffer.from(&quot;Greeting&quot;)

// create the cipher
let cipher = createCipheriv(&#39;chacha20-poly1305&#39;, key, iv, { authTagLength: 16 });

// Add the associated data to the cipher
cipher.setAAD(aad, {
  plaintextLength: Buffer.byteLength(plaintext)
})

// Data to encrypt
let plaintext = &quot;Hello world&quot;;

// Encrypt and finalize encryption
const ciphertext = cipher.update(plaintext);
cipher.final()

// Console log the cipher text in hex
console.log(&quot;ciphertext:&quot;, ciphertext.toString(&#39;hex&#39;))

// Decrytpion

// Create the decipher using exactly same parameters used to create the cipher
let decipher = createDecipheriv(&#39;chacha20-poly1305&#39;, key, iv, { authTagLength: 16 });
// Get the auth tag from the cipher and set it on the decipher
// This ensures the authentication done is done on decryption
decipher.setAuthTag(cipher.getAuthTag())
// We set the same associated data used in encryption
decipher.setAAD(aad);
// We start the decryption
let decrypted = decipher.update(ciphertext)
// We finalise the decryption and save the plaintext in a variable
decrypted = Buffer.concat([decrypted, decipher.final()])
// Print out the plaintext
console.log(&quot;plaintext:&quot;, decrypted.toString())

console.log(&quot;Encryption then Decryption Works&quot;, plaintext.toString() === decrypted.toString());

// Causing decryption to fail by providing different associated data

// Create the decipher using exactly same parameters used to create the cipher
let wrongDecipher = createDecipheriv(&#39;chacha20-poly1305&#39;, key, iv, { authTagLength: 16 });
// Get the auth tag from the cipher and set it on the decipher
// This ensures the authentication done is done on decryption
wrongDecipher.setAuthTag(cipher.getAuthTag())
// We set the another associated data, that differs from one used in encryption
let wrongAssocData = Buffer.from(&#39;Payment&#39;);

// We set the wrong associated data
wrongDecipher.setAAD(wrongAssocData, {
  plaintextLength: ciphertext.length
});

// We start the decryption
let wrongDecrypted = wrongDecipher.update(ciphertext)
// We finalise the decryption and save the plaintext in a variable
try {
  // This leads to exception
  wrongDecipher.final();
} catch (err) {
  throw new Error(&#39;Authentication failed!&#39;, { cause: err });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code above makes use of chacha20-poly1305 as the AEAD. It provided an associated data. It demonstrates encryption and decryption. It also shows that the decryption will fail, if a different associated data, from the one used at encryption is attempted for decryption. &lt;/p&gt; </description><link>http://www.geekabyte.io/2022/05/introduction-to-authenticated.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-8704734794247926161</guid><pubDate>Sun, 01 May 2022 16:37:00 +0000</pubDate><atom:updated>2022-05-12T15:49:30.226+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Introduction to Symmetric Encryption for the Working Developer</title><description>&lt;p&gt;Encryption is all about establishing confidentiality. That is, making sure only authorised parties have access to specific data. It involves transforming data into a form that is inscrutable to unauthorised parties but with the ability for authorised parties to transform the data back into its legible form. &lt;/p&gt;
&lt;p&gt;Think about two parties communicating without wanting other persons privy to the messages. This is achieved via the cryptographic primitive of Encryption.&lt;/p&gt;
&lt;p&gt;In this post, I will provide a whirlwind tour of what encryption is for the working developer. The goal is to provide the basic information needed to be able to properly wield this cryptography tool without going into the inner workings of the algorithm. It is part of the Cryptography101 series of posts.&lt;/p&gt;

&lt;p&gt;This post contains the following &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What Encryption is and its main components&lt;/li&gt;
&lt;li&gt;What Encryption is not&lt;/li&gt;
&lt;li&gt;Symmetric Encryption vs Asymmetric Encryption.&lt;/li&gt;
&lt;li&gt;Block Cipher vs Stream Cipher.&lt;/li&gt;
&lt;li&gt;Overview of encryption Standards&lt;/li&gt;
&lt;li&gt;Components of AES&lt;ul&gt;
&lt;li&gt;Key&lt;/li&gt;
&lt;li&gt;Padding&lt;/li&gt;
&lt;li&gt;Mode&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;encryption-and-its-main-components&quot;&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;Encryption and its main components&lt;/h2&gt;
&lt;p&gt;Encryption is the part of cryptography that deals with ensuring confidentiality of data. This usually involves taking data and transforming it into what looks like gibberish to unauthorised parties. &lt;/p&gt;
&lt;p&gt;Encryption can be used as part of secured communication, where two parties communicate without any eavesdropper being able to make sense of the communication. It is also used to encrypt data at rest, for example the data on a harddisk; making sure it is only accessible by the owner or any other authorised parties. This can also be seen as securing communication, where the other party is the future self that needs to access the content of the harddisk.&lt;/p&gt;
&lt;p&gt;It should be noted that encryption must also include the reversible component; that is decryption. This is the process of taking the gibberish output of the encryption process and transforming it back to the original data. Without being able to decrypt, encryption becomes useless. &lt;/p&gt;
&lt;p&gt;Both the &lt;b&gt;encryption&lt;/b&gt; and &lt;b&gt;decryption&lt;/b&gt; process makes use of a critical component called the &lt;b&gt;secret key&lt;/b&gt;. The secret key together with the encryption/decryption algorithm is what is used to transform a message into gibberish and also to recover the original message. As long as an eavesdropper does not know the secret key, there is no way to access the message. Hence the secrecy of the key is at the heart of the security of encryption. &lt;/p&gt;
&lt;p&gt;The encryption, decryption and secret key generation algorithm is oftentimes together referred to as &lt;b&gt;Encryption Scheme&lt;/b&gt;.&lt;/p&gt;
&lt;p&gt;The data to encrypt is usually called &lt;b&gt;plaintext&lt;/b&gt;, the algorithm that encrypts the data is usually called &lt;b&gt;cipher&lt;/b&gt; and it makes use of a secret component called key. The encrypted data is usually called &lt;b&gt;ciphertext&lt;/b&gt;. &lt;/p&gt;

&lt;h3 id=&quot;what-encryption-is-not&quot;&gt;What Encryption is not&lt;/h3&gt;
&lt;p&gt;Just as it is important to say what encryption is, it is also important to make clear what encryption is not. &lt;/p&gt;

&lt;strong id=&quot;cryptographic-hashing-is-not-encryption&quot;&gt;Cryptographic Hashing is not Encryption&lt;/strong&gt;
&lt;p&gt;Cryptographic Hashing is another cryptography primitive that is sometimes confused with encryption. A cryptographic hash algorithm takes data and produces a random bit string, often called digest, which serves as a form of fingerprints of the data. &lt;/p&gt;
&lt;p&gt;Hashing is a one way operation, that is, with a secure hashing algorithm, it should be practically impossible to retrieve the original data from the digest. This is in contrast with what you want with encryption. With encryption you need to be able to retrieve the original message.&lt;/p&gt;
&lt;p&gt;See &lt;a href=&quot;https://www.geekabyte.io/2021/10/introduction-to-cryptographic-hash.html&quot;&gt;Introduction to Cryptographic Hash Functions for the Working Developer&lt;/a&gt; for more about Cryptographic Hash Functions.&lt;/p&gt;

&lt;strong id=&quot;encoding-decoding-is-not-encryption&quot;&gt;Encoding/Decoding is not Encryption&lt;/strong&gt;
&lt;p&gt;Encoding/Decoding schemes like base64 or even representing data in hexadecimal or binary string is not encryption even though they might also appear to be hiding data. They are not encryption because they do not make use of any secret key, hence they provide no confidentiality since anyone can perform the reverse decoding operation on the encoded data.&lt;/p&gt;

&lt;span id=&quot;stenography-is-not-encryption&quot;&gt;&lt;b&gt;Steganography&amp;nbsp;is not Encryption&lt;/b&gt;&lt;/span&gt;
&lt;p&gt;In infosec there is sometimes the need to hide the fact that communication between two parties is taking place. This usually involves hiding a secret message in something that is not secret. This is done via Steganography. This is different from Encryption which does not seek to hide that communication is taking place but only to hide the message that is being communicated.&lt;/p&gt;
&lt;p&gt;With Steganography&amp;nbsp;an eavesdropper won&#39;t be aware that communication is taking place. &lt;/p&gt;
&lt;p&gt;With encryption an eavesdropper can observe communication taking place but won&#39;t be able to see what is being communicated.&lt;/p&gt;
&lt;p&gt;So having touched on a couple of things that are not encryption, let us go on to see some different aspects of encryption that are often used to put them into different categories or types.&lt;/p&gt;

&lt;h3 id=&quot;symmetric-encryption-vs-asymmetric-encryption&quot;&gt;Symmetric Encryption vs Asymmetric Encryption&lt;/h3&gt;
&lt;p&gt;As mentioned earlier, the process of encryption depends on the usage of a secret key. You then have two flavours of encryption depending on how this secret key is used.&lt;/p&gt;
&lt;p&gt;An encryption scheme where the same key is used for both encryption and decryption is called symmetric Encryption. While an encryption scheme where the key used for encryption is different from the key used for decryption is called asymmetric encryption (also known as asymmetric cryptography or public key cryptography).&lt;/p&gt;
&lt;p&gt;This post is about symmetric encryption&lt;/p&gt;

&lt;h3 id=&quot;block-cipher-vs-stream-cipher&quot;&gt;Block Cipher vs Stream Cipher&lt;/h3&gt;
&lt;p&gt;Encryption schemes can also be categorised based on how the plaintext is passed on to the encryption algorithm.&lt;/p&gt;
&lt;p&gt;Encryption schemes that require the plaintext to be encrypted a fixed size at a time are called Block ciphers. &lt;/p&gt;
&lt;p&gt;This involves having the plaintext broken down to a certain fixed bit size, and each bit size encrypted. This is a hard requirement, hence if the plaintext or the last piece of the chopped up plaintext is not up to the required fixed size, it would have to be padded till it meets the required size.&lt;/p&gt;
&lt;p&gt;Stream ciphers, on the other hand, can encrypt plaintexts at varied bits at a time. Since they do not require a fixed block to be passed in for encryption, stream ciphers hence do not have a need for padding.&lt;/p&gt;
&lt;p&gt;This post is about symmetric encryption that are block ciphers.&lt;/p&gt;

&lt;h3 id=&quot;overview-of-encryption-standards&quot;&gt;Overview of Encryption Standards&lt;/h3&gt;
&lt;p&gt;As stated in &lt;a href=&quot;https://www.geekabyte.io/2021/10/introduction-to-cryptographic-hash.html&quot;&gt;Introduction to Cryptographic Hash Functions for the Working Developer&lt;/a&gt; there are different agencies that publish cryptographic related standards. In this post, we only limit to standards published by National Institute of Standards and Technology (NIST).&lt;/p&gt;
&lt;p&gt;When it comes to symmetric encryption, the go to encryption scheme as standardised by NIST is &lt;a href=&quot;https://www.nist.gov/publications/advanced-encryption-standard-aes&quot;&gt;Advanced Encryption Standard&lt;/a&gt;, usually referred to as just AES.  &lt;/p&gt;
&lt;p&gt;As with most standards by NIST, what later came to be the AES was as a result of an open competition that started in 1997. The competition was an open call to all interested cryptographers to come up with an encryption scheme to replace the then standard scheme: Data Encryption Standard usually referred to as DES. &lt;/p&gt;
&lt;p&gt;In 2001, the competition was concluded and out of 15 different submissions, the Rijndael encryption scheme, designed by Vincent Rijmen and Joan Daemen emerged the winner and was named the AES.&lt;/p&gt;
&lt;p&gt;AES has since then been the main encryption scheme. Replacing DES, which for all intents and purposes is broken and should not be used. Hence the remaining part of this post would be basically an overview of AES.&lt;/p&gt;


&lt;h3 id=&quot;components-of-aes&quot;&gt;Components of AES&lt;/h3&gt;
&lt;p&gt;In this section, I will go over some of the key components of AES. This are key size, padding schemes, and mode of operation.&lt;/p&gt;
&lt;br /&gt;
&lt;strong id=&quot;keys-in-aes&quot;&gt;Keys in AES&lt;/strong&gt;
&lt;p&gt;Like any symmetric encryption scheme, AES also requires a secret key. AES comes in 3 different versions depending on the size of the key. &lt;/p&gt;
&lt;p&gt;We have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;AES-128 takes a key of 128 bits (16 bytes)&lt;/li&gt;
&lt;li&gt;AES-192 takes a key of 192 bits (24 bytes)&lt;/li&gt;
&lt;li&gt;AES-256 takes a key of 256 bits (32 bytes)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The size of the key dictates the level of security. Larger keys provide higher security but for almost all use cases, AES-128 will suffice.&lt;/p&gt;
&lt;p&gt;AES keys are random bits. That means any method that can generate true cryptographic random numbers of 128, 192, and 256 bits can be used to generate AES keys.  As mentioned earlier on, the security of AES depends on the key, hence the methods used to generate the key needs to be truly random and unguessable. &lt;/p&gt;
&lt;p&gt;For example, in JavaScript environment with Web API available, like in the browser or Deno, &lt;code&gt;window.crypto.getRandomValues(new Uint8Array(16))&lt;/code&gt; can be used to generate random 256 bits that can be used as a AES-256 key.&lt;/p&gt;
&lt;p&gt;In Deno, this look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Deno &lt;span class=&quot;hljs-number&quot;&gt;1.16&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;.4&lt;/span&gt;
exit using ctrl+d or close()
&amp;gt; let counter = window.crypto.getRandomValues(new Uint8Array(&lt;span class=&quot;hljs-number&quot;&gt;16&lt;/span&gt;));
undefined
&amp;gt; console.log(counter)
Uint8Array(&lt;span class=&quot;hljs-number&quot;&gt;16&lt;/span&gt;) [
  &lt;span class=&quot;hljs-number&quot;&gt;189&lt;/span&gt;,  &lt;span class=&quot;hljs-number&quot;&gt;59&lt;/span&gt;,  &lt;span class=&quot;hljs-number&quot;&gt;14&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;161&lt;/span&gt;,  &lt;span class=&quot;hljs-number&quot;&gt;84&lt;/span&gt;,
  &lt;span class=&quot;hljs-number&quot;&gt;117&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;160&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;119&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;175&lt;/span&gt;,  &lt;span class=&quot;hljs-number&quot;&gt;96&lt;/span&gt;,
  &lt;span class=&quot;hljs-number&quot;&gt;130&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;233&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;121&lt;/span&gt;,  &lt;span class=&quot;hljs-number&quot;&gt;99&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;176&lt;/span&gt;,
  &lt;span class=&quot;hljs-number&quot;&gt;240&lt;/span&gt;
]
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&quot;padding-scheme-in-aes&quot;&gt;Padding scheme in AES&lt;/h3&gt;
&lt;p&gt;AES is also a block cipher, hence it can only encrypt a fixed size at a time. AES block size is 128 bit hence it can only encrypt plaintext 128 bit at a time. &lt;/p&gt;

&lt;p&gt;This means if your plaintext is larger than 128 bit, it would have to be broken up into blocks of 128 bit each. If the plaintext is less than 128 bit, or after breaking into 128 bits blocks, there remains a last piece that is less than 128 bit, then that piece needs to be padded somehow to become 128 bit. &lt;/p&gt;

&lt;p&gt;Note that the block size of 128 bit is independent of the key size. Meaning that even if a key size of 192 bits or 256 bits is used, the encryption/decryption would still be done 128 bits at a time.&lt;/p&gt;

&lt;p&gt;The padding scheme needs to be such that upon decryption the padding portion can be removed and discarded to reveal the original plaintext.&lt;/p&gt;
&lt;p&gt;Hence AES needs a padding scheme. One of the popular standardized padding scheme, which is also used in AES implementation is PKCS#7. Simply put the PKCS#7 algorithm states the value of each padding byte should be the length of the padding required. So in the case where you have a plaintext of 12 bytes, this will require 4 bytes of padding to make it 16 bytes (that is to make it 128 bit that is required by AES). Hence the value of the 4 bytes should be 4.&lt;/p&gt;
&lt;p&gt;To prevent ambiguity in the case where the plaintext is already a multiple of 128 bits, PKCS#7 stipulates that we add a full block of padding set to the value 16. This ensures that, to remove the padding, one can always look at the last byte, and the value found there, is the number of bytes to discard in order to get to the main data.&lt;/p&gt;
&lt;p&gt;Most implementations of AES do not make the padding scheme configurable to the developer, hence you won&#39;t need to fiddle around with the padding scheme most of the time. Irrespective it is good to know, to have a better understanding of AES.&lt;/p&gt;

&lt;h3 id=&quot;mode-of-operation&quot;&gt;Mode of operation&lt;/h3&gt;
&lt;p&gt;The consequence of AES being a block cipher, that is being able to only encrypt 128 bits at a time leads to two things: We need to provide a padding mechanism, which was mentioned in the previous section. &lt;/p&gt;

&lt;p&gt;We also need a way to put the pieces of encrypted 128 bits together to get the final ciphertext. The way by which the individual encrypted 128 bits are assembled together is called Mode of operation and there are various ways to go about this. &lt;/p&gt;

&lt;p&gt;There are various modes that have been defined for block ciphers (i.e. not limited only to AES), but to have a better understanding of what they are actually supposed to help with, we look at two modes: ECB mode and CBC mode.&lt;/p&gt;

&lt;em id=&quot;ecb-electronic-code-block-mode&quot;&gt;ECB - Electronic Code Block - Mode&lt;/em&gt;
&lt;p&gt;A naive way to piece back the encrypted blocks, is to assemble them back exactly the way the plaintext was broken up. This mode of encryption is called Electronic Code Book (ECB). &lt;/p&gt;
&lt;p&gt;The ECB mode has the drawback that it leaks information about the plaintext. &lt;/p&gt;&lt;p&gt;&lt;span id=&quot;docs-internal-guid-632ca3ef-7fff-86c1-21aa-397b9b2b552e&quot;&gt;&lt;span style=&quot;font-family: Arial; font-size: 11pt; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;border: none; display: inline-block; height: 233px; overflow: hidden; width: 624px;&quot;&gt;&lt;img height=&quot;233&quot; src=&quot;https://lh3.googleusercontent.com/R1MyeIVPZ2t96NbEEpwwb0fIY58KhU-tu6rVvkQtMkl7vkMf_FTCHY6-FJXd4okmdNc2B8IY1JdXD69_xHxPNQNYyVXO34dQ0To7HuV2aaMRehgV0r8VzAMMW_-1PJp28qQsgBgR5M3e20u4cQ&quot; style=&quot;margin-left: 0px; margin-top: 0px;&quot; width=&quot;624&quot; /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;If the plaintexts are broken apart, encrypted and assembled back the same way, patterns about the data can still be carried over into the encrypted version, because similar bits in the plaintext would encrypt to similar cipher text. This allows some information to still be learnt about the plaintext, which defeats the purpose of encryption. A good encryption scheme should not reveal any useful information about the encrypted message, none at all.  &lt;/p&gt;
&lt;p&gt;A very good example of illustrating this weakness of the ECB mode is the ECB penguin. An  image of a penguin is encrypted using the ECB mode, but the shape of the penguin can still be seen in the encrypted image.&lt;/p&gt;&lt;p&gt;&lt;span id=&quot;docs-internal-guid-caa334a0-7fff-1189-f360-f4e5c624ca18&quot;&gt;&lt;span style=&quot;font-family: Arial; font-size: 11pt; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;border: none; display: inline-block; height: 383px; overflow: hidden; width: 624px;&quot;&gt;&lt;img height=&quot;383&quot; src=&quot;https://lh4.googleusercontent.com/TaStVOfOflHDi6q5q2355Q2uLNYZGgdTEYJ2N1IrHbRjCEAM7fiFqwbincr8U9VUHCrIleHKKjGnI_bRDnc7nMb14zD4bSu_5nb2Zxg3JTGnBDEG9FNbE9lpFcSCyzfPe7Xq9RLbtMN_OA0p2g&quot; style=&quot;margin-left: 0px; margin-top: 0px;&quot; width=&quot;624&quot; /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Hence for all intents and purposes, ECB mode is usually not used.&lt;/p&gt;

&lt;em id=&quot;cbc-cipher-block-chaining-mode&quot;&gt;CBC - Cipher Block Chaining - Mode&lt;/em&gt;
&lt;p&gt;The Cipher Block Chaining mode is another mode of operation that can be used with AES that does not suffer from the weakness of ECB. &lt;/p&gt;
&lt;p&gt;The problem with the ECB mode is that identical portions of the plaintext would encrypt to identical cipher text. This is what enables patterns to still be carried over to the ciphertext. &lt;/p&gt;
  
&lt;p&gt;The CBC mode avoids this problem by including a procedure in its algorithm that first randomises the plaintext before encryption. This process of randomisation ensures that identical portions of the plaintext will never encrypt to the same ciphertext.&lt;/p&gt;
&lt;p&gt;Simply put, CBC achieves this randomisation by taking a previous encrypted block and using this to randomise (by performing an XOR operation) the next block to be encrypted. This then provides the output that is then fed as the next block to the encryption. This chaining goes on until the plaintext is fully encrypted into the ciphertext.&lt;/p&gt;
&lt;p&gt;You might ask, how will the first block be randomised before encryption since there is no previous cipher text that can be used for the XOR operation? The answer is that CBC used with AES requires an additional 16 bytes value called the &lt;strong&gt;Initialisation vector (IV)&lt;/strong&gt; to kickstart the encryption process. This is the value that is used to randomise the first block to kickstart the encryption process. It should be noted that the IV also needs to be random and unpredictable in order to have a secured encryption scheme.&lt;/p&gt;&lt;p&gt;&lt;span id=&quot;docs-internal-guid-e839c692-7fff-47d8-f084-f7f766c31cb6&quot;&gt;&lt;span style=&quot;font-family: Arial; font-size: 11pt; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;border: none; display: inline-block; height: 259px; overflow: hidden; width: 624px;&quot;&gt;&lt;img height=&quot;259&quot; src=&quot;https://lh3.googleusercontent.com/DsAU_W3z0C-0B9XYX9UdY7q1eeKlYoTaV1peNvulGlHzEyqK4HI3BTpmhSrJB0p5r_dbZXVI9doqI2EOOIv1jX31eKd6HAd6bvqUUMR6R4Xlkd-CTB9OA-zbHR6alAxzpjOP08Y_EpBeKIceJQ&quot; style=&quot;margin-left: 0px; margin-top: 0px;&quot; width=&quot;624&quot; /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;So far we have seen what encryption is, what it is not, the difference between symmetric encryption and asymmetric encryption and also the difference between block ciphers and stream ciphers. We also saw how block ciphers lead to needing padding and mode of operation. The weakness of ECB mode and how CBC avoids that.&lt;/p&gt;
&lt;p&gt;Next we will see how encrypting data with CBC looks like in code. To do this, we would again be using Deno.&lt;/p&gt;
&lt;p&gt;The following code shows how to encrypt and deprect a piece of text using AES with the CBC mode.&lt;/p&gt;


&lt;pre style=&quot;width: fit-content;&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;// We generate a key
&lt;span class=&quot;hljs-comment&quot;&gt;// See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; key = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; crypto.subtle.generateKey({
   &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&#39;AES-CBC&#39;&lt;/span&gt;,
   &lt;span class=&quot;hljs-attr&quot;&gt;length&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;128&lt;/span&gt;
}, &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;, [&lt;span class=&quot;hljs-string&quot;&gt;&#39;encrypt&#39;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&#39;decrypt&#39;&lt;/span&gt;]);

&lt;span class=&quot;hljs-comment&quot;&gt;// We generate random 16 bytes to be used as initialization vector&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; iv = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Uint8Array&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;16&lt;/span&gt;);
&lt;span class=&quot;hljs-comment&quot;&gt;// and fill it with random numbers&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; crypto.getRandomValues(iv);

&lt;span class=&quot;hljs-comment&quot;&gt;// The web crypto requires data to be in ArrayBuffer&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; plaintext = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; TextEncoder().encode(&lt;span class=&quot;hljs-string&quot;&gt;&quot;hello world&quot;&lt;/span&gt;);

&lt;span class=&quot;hljs-comment&quot;&gt;// The encryption and decryption requires specifying&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// the algorithm and initialization vector&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; param = {
   &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&#39;AES-CBC&#39;&lt;/span&gt;,
   &lt;span class=&quot;hljs-attr&quot;&gt;iv&lt;/span&gt;: iv
};

&lt;span class=&quot;hljs-comment&quot;&gt;// We encrypt the plaintext to get the ciphertext&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; ciphertext = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; crypto.subtle.encrypt(param, key, plaintext);

&lt;span class=&quot;hljs-comment&quot;&gt;// We decode and console logged the ciphertext&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;console&lt;/span&gt;.log(&lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; TextDecoder(&lt;span class=&quot;hljs-string&quot;&gt;&quot;utf-8&quot;&lt;/span&gt;).decode(ciphertext))

&lt;span class=&quot;hljs-comment&quot;&gt;// We decrypt the ciphertext back to plaintext&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; deCryptedPlaintext = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;window&lt;/span&gt;.crypto.subtle.decrypt(param, key, ciphertext);

&lt;span class=&quot;hljs-comment&quot;&gt;// We tranform the plaintext from bytes to string and then print it out&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;console&lt;/span&gt;.log(&lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; TextDecoder(&lt;span class=&quot;hljs-string&quot;&gt;&quot;utf-8&quot;&lt;/span&gt;).decode(deCryptedPlaintext));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you copy this code into a filename &lt;i&gt;enc_dec_aec_cbc.ts&lt;/i&gt; and then execute &lt;i&gt;deno run enc_dec_aec_cbc.ts&lt;/i&gt;, you should see two lines printed out. One looks like gibberish binary blob, while the second line should be &quot;hello world&quot;&lt;/p&gt;
&lt;p&gt;As the comment in the code shows, we are generating a key, and IV, and then used to encrypt the text &quot;hello world&quot;. Then print the cipher text and then decrypt it back to the plain text &quot;hello world&quot;.&lt;/p&gt;


</description><link>http://www.geekabyte.io/2022/05/introduction-to-symmetric-encryption.html</link><author>noreply@blogger.com (dade)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lh3.googleusercontent.com/R1MyeIVPZ2t96NbEEpwwb0fIY58KhU-tu6rVvkQtMkl7vkMf_FTCHY6-FJXd4okmdNc2B8IY1JdXD69_xHxPNQNYyVXO34dQ0To7HuV2aaMRehgV0r8VzAMMW_-1PJp28qQsgBgR5M3e20u4cQ=s72-c" height="72" width="72"/><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-9222140925396765363</guid><pubDate>Sat, 23 Oct 2021 16:20:00 +0000</pubDate><atom:updated>2021-12-06T16:09:12.174+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Hash Function in Action: Message Authentication Codes</title><description>&lt;p&gt;In&amp;nbsp;&lt;a href=&quot;https://www.geekabyte.io/2021/10/introduction-to-cryptographic-hash.html&quot;&gt;Introduction to Cryptographic Hash Functions for the Working Developer&lt;/a&gt;, I presented a straight to the point, overview of some essential things a developer should know about cryptographic hash functions.&amp;nbsp;&lt;/p&gt;&lt;p&gt;This post continues in the theme around hash functions, by taking a look at another cryptographic construction hash functions make possible, that is: Message Authentication Codes (MACs).&lt;/p&gt;&lt;p&gt;It is worth quoting Bruce schneier again:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;blockquote&gt;Much more than encryption algorithms, one-way hash functions are the workhouses of modern cryptography&lt;/blockquote&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;Because Message Authentication Code based on hash functions is a perfect demonstration of how crucial hash functions are.&lt;/p&gt;&lt;p&gt;This post contains the following sections:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Why Hash Functions alone are not enough&lt;/li&gt;&lt;li&gt;What is Message Authentication Code&lt;/li&gt;&lt;li&gt;What is a Hash Based Authentication Code (HMAC)&lt;/li&gt;&lt;li&gt;What is a Keccak Based Authentication Code (KMAC)&lt;/li&gt;&lt;li&gt;Some real world applications of Message Authentication Code&lt;/li&gt;&lt;/ul&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Hash Functions alone are not enough&lt;/h3&gt;&lt;div&gt;Hash functions produce random fixed length finger print of input data. As it turns out, this construction alone by itself, is hardly ever enough for any real life use. This is because just hash functions alone are not enough to guarantee things like integrity and authentication. Things hash functions would be used for.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To illustrate this, take browser cookies for example. There is the need to check the integrity of cookies. To ascertain that cookies placed with a browser by a server, is the same returned by the browser on consequent requests. A naive way to check this, is to just use hash functions: hash the contents of the cookie and place it on the browser alongside the data.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This has a loop hole, in the sense that an attacker can intercept the request back to the server, modify the cookie data, generate another hash and send both back to the server. The server won&#39;t be able to detect there has been a modification.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This shows, how in most use cases, just a hash function is never enough. In the scenario described, the loop hole is due to the fact that hash functions are public and hence anyone can use them. Therefore we need a way to include something not public, something secret into the mechanism that can be used as a way to authenticate the output of the hash function. Message authentication code (MAC) are constructs that can be used for this.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It turns out that hash functions can be used to generate these MACs when used together with secrets.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Understanding what this construction is all about is the goal of this post and we start with first looking at Message Authentication Code.&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;What is Message Authentication Code&lt;/h3&gt;&lt;p&gt;A message authentication code, is extra data or information that is used to confirm that a piece of data came from the stated sender (confirming authenticity) and has not been changed (providing integrity). This piece of extra data/information is often referred to as the authentication tag.&amp;nbsp;&lt;/p&gt;&lt;p&gt;In general authentication tag can be broadly classified into 4 categories:&amp;nbsp;unconditionally secure, hash function-based, stream cipher-based and block cipher-based. In this post, I would only be touching on two of the hash function-based: HMAC (Keyed-hash message authentication code) and KMAC (KECCAK Message Authentication Code).&lt;/p&gt;&lt;p&gt;In summary, the &lt;i&gt;hash function based MACs&lt;/i&gt; can be seen as a mix of a hash function and a secret. Let&#39;s look first at HMACs.&lt;/p&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;What is HMAC&lt;/h3&gt;&lt;p&gt;HMAC is a MAC created from using a cryptographic hash function and a secret cryptographic key.&amp;nbsp;&lt;/p&gt;&lt;p&gt;The&amp;nbsp;cryptographic hash function can be any secure hash function, such as SHA-2 or SHA-3. This is reflected in the name of the given HMAC. For example,&amp;nbsp;HMAC-SHA256 and HMAC-SHA3-512 is created using a secret key with SHA-2 (256) and SHA-3 (512) respectively.&lt;/p&gt;&lt;p&gt;As noted in&amp;nbsp;&lt;a href=&quot;https://www.geekabyte.io/2021/10/introduction-to-cryptographic-hash.html&quot;&gt;Introduction to Cryptographic Hash Functions for the Working Developer&lt;/a&gt;&amp;nbsp;naively using SHA-2 to hash concatenated secrets with a message is insecure due to the weakness of SHA-2 to the length extension attack. This is why HMAC is needed when the requirement is to use SHA-2 with a key in other to create an authenticated tag.&amp;nbsp;&lt;/p&gt;&lt;p&gt;Although it is beyond the scope of this post to dig into how HMAC works, it is worth pointing out that HMAC construction is not a naive concatenation of secret keys and data. HMAC uses a nested construction which avoids the length extension attack pitfall, Hence it is a special one that takes care of combining secret keys and data together in such a way to avoid being susceptible to the length extension attack.&lt;/p&gt;&lt;p&gt;SHA-3 on the other hand is not susceptible to the length extension attack and it is relatively safe to create an authentication tag manually using&amp;nbsp;SHA-3-&lt;span face=&quot;sans-serif&quot; style=&quot;background-color: white; color: #202122; font-size: 14px;&quot;&gt;512&lt;/span&gt;(𝐾𝐸𝑌‖𝑚𝑒𝑠𝑠𝑎𝑔𝑒), but since the HMAC construction is available, it is also possible to use the construction with SHA-3 instead, hence&amp;nbsp;HMAC-SHA3-512.&lt;/p&gt;&lt;p&gt;Using HMAC-SHA3-512 is not advised though, as it is not efficient. As stated in&amp;nbsp;&lt;a href=&quot;https://keccak.team/2016/sp_800_185.html&quot;&gt;NIST SP 800-185&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;blockquote&gt;KMAC is a keyed hash function or pseudo-random function (PRF) that can be used, e.g., to compute a message authentication code (MAC) or to derive a session key from a master key. It is more efficient than HMAC by removing the need for HMAC&#39;s nested construction&amp;nbsp;&lt;/blockquote&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;Hence when there is the need to use SHA-3 hash functions to create authentication tag, it is preferable to do so using KMAC, which we look at next.&lt;/p&gt;&lt;h3&gt;What is KMAC&lt;/h3&gt;&lt;p&gt;The KECCAK Message Authentication Code (KMAC) algorithm is also a keyed hash function but based on KECCAK.&amp;nbsp;&lt;/p&gt;&lt;p&gt;It provides variable-length output, and unlike SHAKE and cSHAKE, altering the requested output length also generates a new, unrelated output.&amp;nbsp;&lt;/p&gt;&lt;p&gt;KMAC has two variants, KMAC128 and KMAC256, built from cSHAKE128 and cSHAKE256, respectively.&amp;nbsp;&lt;/p&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Some real world applications of Message Authentication Code&lt;/h3&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;JSON Web Token&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The JSON Web Token: JWT is an open, industry standard for representing claims securely between two parties. It guarantees integrity and also authenticity. For example JWT can be used to solve the problem of servers being able to verify the integrity and authenticity of the cookies they receive browser clients.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;JWT provides the option of&amp;nbsp; specifying HMAC construction as a signing algorithm.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;See &lt;a href=&quot;https://jwt.io/introduction&quot;&gt;here&lt;/a&gt;&amp;nbsp;and &lt;a href=&quot;https://auth0.com/blog/json-web-token-signing-algorithms-overview/&quot;&gt;here&lt;/a&gt; for more information on JWT.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;HMAC-based one-time password&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;A One Time Password (OTP) is a dynamic password that is valid for only one login session or transaction, or a short period of time. Certain implementations of OTP makes use of HMAC. These are called HOTP: HMAC-based one-time password. A popular example of such an HOTP is the &lt;a href=&quot;https://en.wikipedia.org/wiki/Google_Authenticator&quot;&gt;Google Authenticator&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;b&gt;Signing HTTP Requests&lt;/b&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;HTTP links used for sensitive operations like password resets or payment links can be accompanied with MACs. This helps in ensuring the integrity and authenticity of such links.&amp;nbsp;&amp;nbsp;&lt;/div&gt;</description><link>http://www.geekabyte.io/2021/10/hash-function-in-action-message.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-7467508112848156929</guid><pubDate>Wed, 20 Oct 2021 18:49:00 +0000</pubDate><atom:updated>2022-01-25T00:39:49.206+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cryptography</category><category domain="http://www.blogger.com/atom/ns#">Cryptography101</category><title>Introduction to Cryptographic Hash Functions for the Working Developer</title><description>&lt;p&gt;&lt;/p&gt;&lt;blockquote&gt;Much more than encryption algorithms, one-way hash functions are the workhouses of modern cryptography - &lt;a href=&quot;https://www.schneier.com/blog/about/&quot;&gt;Bruce schneier&lt;/a&gt;&lt;/blockquote&gt;&lt;p&gt;&lt;/p&gt;&lt;div&gt;&lt;div&gt;This post would be a quick, straight to the point, overview of some essential things a developer should know about cryptographic hash functions. It is targeted at the working developer who needs to be familiar enough with cryptographic hash functions in order to use them, but who does not need to know the gory details of how they are implemented, all their possible use cases or how they work internally.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;This post contains the following sections:&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Cryptographic hash function: A definition&lt;/li&gt;&lt;li&gt;Properties of cryptographic hash functions.&lt;/li&gt;&lt;li&gt;Types of hash functions&lt;/li&gt;&lt;ol&gt;&lt;li&gt;Fixed length hash Functions&lt;/li&gt;&lt;li&gt;Extendable Output Functions (XOF)&lt;/li&gt;&lt;li&gt;Password hashing functions&amp;nbsp;&lt;/li&gt;&lt;/ol&gt;&lt;li&gt;Some Hashing Hygiene&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Cryptographic Hash Function: A Definition&lt;/h3&gt;&lt;div&gt;&lt;div&gt;A hash function is a function that converts any arbitrary data into a random, fixed sized data. One can see it as a way to generate a unique fingerprint for any arbitrary data. The output of a hash function, the generated fingerprint, is usually referred to as hash values, hash codes, digests, or simply hashes.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For example, using OpenSSL, generating a digest for the phrase &quot;hello world&quot; using the Sha256 hashing algorithm will look like this:&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&amp;gt; echo &#39;hello world&#39; | openssl dgst -sha256&lt;/div&gt;&lt;div&gt;a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The&amp;nbsp; `a94890…` is the digest of the string &quot;hello world&quot;.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;A somewhat similar looking output, similar in the sense of it being unique and random looking, can also be generated using the `cksum` utility&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&amp;gt; echo &#39;hello world&#39; | cksum&lt;/div&gt;&lt;div&gt;3733384285 12&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;What then is the difference between the output of the cksum utility and that of sha256 using the openssl cli?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;They are both hash functions, but sha256 is the one that can be described as a cryptographic hash function, while cksum is, well, just a hash function. You also have hash functions that are not cryptographic hash functions used for instance in data structures like Hash map. Being able to turn an arbitrary data into some sort of unique finger prints is not enough to make a cryptographic hash function.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The question then is, what makes a hash function a cryptographic hash function?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For a hash function, to be actually considered a cryptographic hash function, it has to satisfy certain properties. These properties are what we would look at next.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Properties of cryptographic hash functions&lt;/h3&gt;&lt;div&gt;For a hash function to be a cryptographic hash function it most posses the following properties:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Pre-image resistant&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;This property guarantees it should be infeasible to get the original data that produced a particular hash. A less fancy term, it is to say the hash function should be one-way. You should only be able to go from the data to the hash value, and there should be no practical way to determine the original date from the hash value.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Second pre-image resistant&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;This property guarantees if you have a data and it&#39;s hash, it should be infeasible to come up with another data that hashes to the same value as the previous data. Expressed In a more mathematical format: it says given x (original data) and h(x) (hash of original data), it is infeasible to find y (another data) such that h(y) = h(x). This property is also called Weak collision resistance.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Collision resistant&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;This property guarantees that it should be infeasible to come up with two different data that hashes to the same value. Again, in a slightly mathematical format: it should be infeasible to find any x and y, with x != y such that h(x) = h(y)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Avalanche effect&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;This property guarantees that the output of a cryptographic hash function is as random as possible and bears no semblance or connection to the input data. The avalanche effect ensures the output changes significantly if the input is changed slightly.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&amp;gt; echo raw | openssl dgst --sha256&lt;/div&gt;&lt;div&gt;SHA2-256(stdin)= 8e5ceeca3a438135cfd1372eafe969ccc4440798e378d8b8ed24242f026a704f&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&amp;gt; echo rat | openssl dgst --sha256&lt;/div&gt;&lt;div&gt;SHA2-256(stdin)= fd439a2284b3e6aaa3c0b6d8fc21142ce0398dc42d12315165e22908aadca92f&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A single change in the input: from raw to rat, changes the output significantly. This is the avalanche effect.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;These properties, if present, means you have a cryptographic hash function and not just an ordinary harsh function.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Next we would take a quick look at how one might categorise cryptographic hash functions based on their types/usage.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Types of hash functions&lt;/h3&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;There are different agencies that publish cryptographic related standards. In this post, we only limit to standards published by National Institute of Standards and Technology (NIST). Curious readers, with the help of their favourite search engine can find similar bodies, that for example are responsible for cryptographic standards in China, Israel etc. Having said this, let&#39;s take a look at some of the categorisation.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In this section, we look at: Fixed size hash functions or message digests, XOF: Extendable Output Functions and Password hashing functions.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Fixed length Hash Functions&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;The hash functions listed in this section are the ones that take an arbitrary length of data and always produce a fixed length digest as output.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;u&gt;SHA-2&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;SHA-2 stands for &lt;b&gt;S&lt;/b&gt;ecure &lt;b&gt;H&lt;/b&gt;ash &lt;b&gt;A&lt;/b&gt;lgorithm 2 and was invented by NSA and standardised by NIST in 2001. SHA-2 provides 4 different versions each producing different bit sizes. The bit sizes are 224, 256, 384, and 512 bits, and named SHA-224, SHA-256, SHA-384, and SHA-512 respectively. (Note that the names omit the version).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;SHA-2 is a Merkle–Damgård construction. No need to worry yet what this means. This detail is only mentioned now, as it will be used to make the point on how SHA-3 is further different from SHA-2.&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;u&gt;SHA-3&lt;/u&gt;&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;SHA-3 is another family of hashing algorithms that was standardised by NIST. It came about from a competition that was initiated by NIST in 2007 to find a replacement for SHA-2. One of the submissions, Keccak, emerged as the winner and took the name SHA-3.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;SHA-3 offers the same variants as SHA-2, but has the&amp;nbsp; full name in their named variants: SHA-3-224, SHA-3-256, SHA-3-384, and SHA-3-512. In 2015, SHA-3 was standardised in the&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf&quot;&gt;FIPS Publication 202&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It should be noted that the padding parameters defined in original Keccak was modified in the resulting SHA-3, hence it is possible to have cryptographic libraries that offer Keccak implementations whose digest will be different from what SHA-3 outputs. This padding difference is the only thing distinguishing Keccak and SHA-3. They both offer the same level of security.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;SHA-3 is built with a sponge construction, which is different from Merkle–Damgård construction which SHA-2 is based on.&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;u&gt;SHA-1 and MD5&lt;/u&gt;&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;SHA-1 and MD5 are also standardised fixed length hash functions. You should not be used though, because they have been found to be broken. They are mentioned here for completeness sake.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;One interesting thing to note is that both SHA-1 and MD5 are also based on the Merkle–Damgård construction. Keccak, from which SHA-3 is derived, uses a sponge construction, which differs from the Merkle–Damgård construction. This&amp;nbsp; was one of the reasons why it was chosen as the winner of the SHA-3 competition. Rationale is if Merkle–Damgård construction is totally broken, then SHA-3 would be spared.&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;span id=&quot;docs-internal-guid-7dc33e23-7fff-2e8e-b403-0e77a29e192e&quot;&gt;&lt;span style=&quot;font-family: Arial; font-size: 11pt; font-variant-east-asian: normal; font-variant-numeric: normal; text-decoration-line: none; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;BLAKE&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div style=&quot;text-decoration-line: underline;&quot;&gt;&lt;span&gt;&lt;span style=&quot;font-family: Arial; font-size: 11pt; font-variant-east-asian: normal; font-variant-numeric: normal; text-decoration-line: none; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-size: 14.6667px; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;font-family: Arial;&quot;&gt;Another popular hash algorithm is BLAKE (and the subsequent improvements: BLAKE2/BLAKE3). &lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-size: 14.6667px; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;font-family: Arial;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-size: 14.6667px; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;font-family: Arial;&quot;&gt;BLAKE made it to the final round of the NIST competition that produced SHA-3, but did not end up being the winner. &lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-size: 14.6667px; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;font-family: Arial;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-size: 14.6667px; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;font-family: Arial;&quot;&gt;One of the reasons why it was not the winning submission is due to the fact that it makes use of&amp;nbsp; the Merkle–Damgård construction, which sort of defeats the purpose of the SHA-3 competition, which is to come up with another hashing standard that won&#39;t be susceptible to the same issues as SHA-2.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-size: 14.6667px; font-variant-east-asian: normal; font-variant-numeric: normal; vertical-align: baseline; white-space: pre-wrap;&quot;&gt;&lt;span style=&quot;font-family: Arial;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;XOF Extendable Output Functions&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;Extendable-output functions (XOFs) are a family of cryptographic hash functions that can output digests of arbitrary size. This is in contrast with the fixed length hash functions that can only output digest of specific sizes.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;These XOF can be used to create other cryptographic constructions like random numbers, as key deriving functions (KDF).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;u&gt;SHAKE&amp;nbsp;&lt;/u&gt;&lt;/div&gt;&lt;div style=&quot;font-weight: bold;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;SHAKE (&lt;b&gt;S&lt;/b&gt;ecure &lt;b&gt;H&lt;/b&gt;ash &lt;b&gt;A&lt;/b&gt;lgorithm &lt;b&gt;K&lt;/b&gt;eccak) is an XOF that was included in the standardisation of SHA-3, as published in &lt;a href=&quot;https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf&quot;&gt;FIPS Publication 202&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;One can think of SHAKE as being exactly like SHA-3 only with the additional option of specifying how long the digest should be.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;u&gt;cSHAKE&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;This is a customisable SHAKE. It is just like SHAKE, in the sense that it allows for the creation of variable sized digest. The difference between cSHAKE and SHAKE is that cSHAKE allows for customisation via an input string.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So with cSHAKE, you can not only generate a varied length digest for an input, the digest can be further customised based on an optional input string passed to the function.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;cSHAKE is part of SHA-3 derived functions; a set of functions that was published a year after SHA-3 was standardised in the &lt;a href=&quot;https://csrc.nist.gov/publications/detail/sp/800-185/final&quot;&gt;Special Publication 800-185&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;u&gt;TupleHash&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;TupleHash is also another XOF, in that it is a variable-length hash function designed to hash tuples of input strings. This hash function should be used in scenarios where a list of data needs to be concatenated together before hashing.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To illustrate why a hash function like TupleHash is needed, imagine a string of the format below:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;font-family: courier;&quot;&gt;&amp;lt;payer&amp;gt;&amp;lt;payee&amp;gt;&amp;lt;amount&amp;gt;&amp;lt;tip&amp;gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Which represents a transaction to pay at a restaurant. A concrete example of such a string and its hash can be seen to be:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&amp;gt; echo &quot;Joe&quot;&quot;Fibo&quot;&quot;50&quot;&quot;20&quot; | openssl dgst -sha256&lt;/div&gt;&lt;div&gt;SHA2-256(stdin)= bb7125e94fcf1df473523022d0d5232c1f45580821bd68c9d01a072004599e44&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The same string can be modified, such that the payment becomes 502, and tip becomes 0 and it will still hash to the same output&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&amp;gt; echo &quot;Joe&quot;&quot;Fibo&quot;&quot;502&quot;&quot;0&quot; | openssl dgst -sha256&lt;/div&gt;&lt;div&gt;SHA2-256(stdin)= bb7125e94fcf1df473523022d0d5232c1f45580821bd68c9d01a072004599e44&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It is for situations like this, that TupleHash should be used.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;TupleHash is part of SHA-3 derived functions; a set of functions that was published a year after SHA-3 was standardised in the &lt;a href=&quot;https://csrc.nist.gov/publications/detail/sp/800-185/final&quot;&gt;Special Publication 800-185&lt;/a&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;u&gt;ParallelHash&lt;/u&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;ParallelHash is another XOF, in that it is a variable-length hash function that can be used to hash very long messages in parallel.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;ParallelHash is part of SHA-3 derived functions; a set of functions that was published a year after SHA-3 was standardised in the &lt;a href=&quot;https://csrc.nist.gov/publications/detail/sp/800-185/final&quot;&gt;Special Publication 800-185&lt;/a&gt;.&amp;nbsp;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Password Hashing Functions&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;There are cryptographic hash functions that are designed specifically to hash passwords. These are hash functions designed to be used together with salts and also slow to deter brute force attacks. Some hash functions that fall under this category include: Argo2, PBKDF2, bcrypt and scrypt.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Some Hashing Hygiene&lt;/h3&gt;&lt;div&gt;&lt;div&gt;To wrap up this post, I&#39;ll outline some common security precautions to keep in mind when using cryptographic hash functions. This is in no way exhaustive, but should still be useful.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Don&#39;t use MD5 and SHA-1&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;These two algorithms are no longer considered secure. Even though all currently known attacks on MD5 and SHA-1 are collision attacks (i.e. they are still resistant to pre-image and second pre-image attack), you are better off using newer hashing algorithms.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Don&#39;t use SHA-2 to hash secrets due to length extension attack&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;There is sometimes the need to append a secret key to message being hashed. This is often done to achieve some level of authentication. Hashing this way should never be done using SHA-2.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Even though SHA-2 is a perfectly fine hash function to use, it is not suitable for hashing message that contain appended secrets. This is because of a downside of the Merkle–Damgård construction, which makes SHA-2 vulnerable to &lt;a href=&quot;https://en.wikipedia.org/wiki/Length_extension_attack&quot;&gt;length extension attack&lt;/a&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Explaining the length extension attack is out of scope of this post, but it worth mentioning that SHA-2 should not be used in situations, where a secret is to be included in data to be hashed. For such use cases, &lt;a href=&quot;https://en.wikipedia.org/wiki/HMAC&quot;&gt;HMAC&lt;/a&gt;s should be used. HMACs would be covered in another post.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Minimum output size of hash function should be 256 bits&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;To reduce the feasibility of a successful collision attack, the minimum output size a hash function must produce should be 256 bits. This ensures a minimum of 128 bits of security. A 128 bits of security means an attacker needs to perform 2 raised to power 128 operations to be exhaustive, which is a huge number. The reason why an output of 256 bits is required to have a 128 bits of security is due to something called &lt;a href=&quot;https://en.wikipedia.org/wiki/Birthday_attack&quot;&gt;Birthday problem&lt;/a&gt;. This has roots in probability theory but explaining it, is out of scope of this post.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Don&#39;t hash small or predictable values&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For example, if it can be predicted that the value that is being hashed is either yes or no, then it would be trivial to hash all possible values suspected to compared to the hash. Technically making it possible to derive the input data from the hash.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Don&#39;t naively hash concatenated inputs&amp;nbsp;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As shown in the section that motivated the use of TupleHashes, naively concatenating strings might lead to unexpected security loop holes.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</description><link>http://www.geekabyte.io/2021/10/introduction-to-cryptographic-hash.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-1471113547315633923</guid><pubDate>Tue, 28 Sep 2021 16:29:00 +0000</pubDate><atom:updated>2021-09-28T18:29:13.468+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Crypto</category><category domain="http://www.blogger.com/atom/ns#">NFTs</category><title>NFTs are not to blame</title><description>&lt;p&gt;T206 Honus Wagner baseball card &lt;a href=&quot;https://www.msn.com/en-us/sports/mlb/honus-wagner-baseball-card-sells-for-6-606-million-shattering-the-record-for-most-expensive-sports-card-ever/ar-AANnfK4?li=BB15ms5q&quot;&gt;sold for $6.606 million&lt;/a&gt; just this August 2021, Pikachu Illustrator, a pokeman card &lt;a href=&quot;https://www.businessinsider.com.au/rare-pokemon-card-pokemon-illustrator-sells-for-195000-2019-10&quot;&gt;sold for $195,000&lt;/a&gt; in 2019. You can get different Micheal Jordan&#39;s basketball card on e-bay ranging from couple of &lt;a href=&quot;https://www.ebay.com/sch/i.html?_from=R40&amp;amp;_nkw=michael+jordan&amp;amp;_sacat=212&amp;amp;LH_TitleDesc=0&amp;amp;toolid=20012&amp;amp;mkcid=1&amp;amp;campid=5338796588&amp;amp;siteid=0&amp;amp;mkrid=711-53200-19255-0&amp;amp;customid=1991michaeljordanupperdecksp1&amp;amp;_sop=16&quot;&gt;thousands to couple of millions&lt;/a&gt;. Sentimental and collectible items have always been part of the human experience. NFTs are not to blame.&lt;/p&gt;&lt;p&gt;Why should pieces of cards with pictures of athletes (or game characters) be worth that much? Why should JPEGs/PNGs be worth that much? Maybe because humans also value things for sentimental reasons just as they do for utilitarian/sustenance reasons.&lt;/p&gt;&lt;p&gt;NFTs only made the act of ownership that was so easy to establish in the physical realm, also possible in the digital realm. It&#39;s only natural it will be used for digital arts/collectible culture.&lt;/p&gt;&lt;p&gt;The mistake to avoid, is thinking NFTs are only about digital arts and collectibles. No! they are more than this. The ability to create unique, non fungible digital items that can be provable owned, can be, and is being deployed for other use cases.&lt;/p&gt;</description><link>http://www.geekabyte.io/2021/09/nfts-are-not-to-blame.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-6130685349748927443</guid><pubDate>Mon, 13 Sep 2021 04:36:00 +0000</pubDate><atom:updated>2021-09-13T13:36:18.492+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Blockchain</category><category domain="http://www.blogger.com/atom/ns#">Crypto</category><category domain="http://www.blogger.com/atom/ns#">NFTs</category><title>Why I am offering NFTs as a crowdfunding perk</title><description>&lt;p&gt;Non-equity funding campaigns are always based on promises: &quot;Back us now, and we promise you early access to the product when we launch, or we promise you a discount, digital shout-out or swags&quot;. I am currently running an &lt;a href=&quot;https://igg.me/at/dishafrik&quot;&gt;Indiegogo campaign&lt;/a&gt; where the promise will also include an NFT: Non Fungible Token, which is a digital artifact that can be used to prove things like ownership. This, as far as I know, is the first time NFTs would be used in this capacity.&lt;/p&gt;&lt;p&gt;In this post, I will shed some light on what NFTs are and share my thoughts on why they are a&amp;nbsp; perfect perk for a non-equity crowdfunding campaign. In doing so, I will touch on my thoughts on the continual march towards the digitalization of the human experience. How digitalization and technologies like virtual/augmented reality, blockchain technology, etc are making it possible to further digitize aspects of society and human interaction that were previously rife with problems or just plain impossible to digitize.&lt;/p&gt;&lt;p&gt;By the way, my campaign is to kickstart the development of DishAfrik: a recipe app to discover, enjoy and share African recipes. Think of it as Yummly or Tasty.co but focused on African cuisine. One of the perks of the campaign is going to be 54 uniquely generated collages made up of 54 recipes from 54 countries. 54 because currently Africa is home to 54 fully recognised sovereign states.&lt;/p&gt;&lt;div&gt;&lt;b&gt;You should check out the IndieGoGo campaign and back the project :) Find it &lt;a href=&quot;https://igg.me/at/dishafrik&quot;&gt;here&lt;/a&gt;&amp;nbsp;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;

TL;dr&amp;nbsp;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Ever since the third industrial revolution, there has been a march towards digitalization of the physical world.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Blockchain-related technologies, like NFTs, provided the possibility to digitize aspects of the physical world that relied on scarcity, uniqueness, and proof of ownership, aspects that were previously hard to digitize.&amp;nbsp;&lt;/li&gt;&lt;li&gt;DishAfrik&#39;s Indiegogo campaign will be making use of NFTs as a perk, using it as a way to capture participation, while also creating digital art in the form of a recipe collage that can also be owned.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;&lt;/h4&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;In the beginning, before the Metaverse&lt;/h4&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;It started with the Third Industrial Revolution, often referred to as the Digital Revolution. A period that began in the late 1900s that led to the spread of automation and digitization through the use of electronics and computers. The technological invention of this era made it possible for things that once existed only in the tactile realm to now also exist in a new and alternative realm: the digital world.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Obviously, such powerful technology would have an impact on society. First, it was radio that killed the town crier, and then video killed the radio star. It was not enough to have good old mails, we got new ones with an e as a prefix: e-mails. The music industry had its Napster scare, and then we had the spotify-cation of music distribution, which killed the CD, at whose hands, cassette and VHS suffered similar fatal fate. Journalism, Medicine, Education, Entertainment you name it, all got impacted by this continual digitalization wave.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Even with all these seismic shifts that digitalization brought, there were certain aspects of society and human interactions that just could not be properly represented in the digital world. This is because these human interactions are inherently at odds with the very nature of digitalization.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For example, digitalization makes it possible to produce digital artifacts once, and then duplicate them till Infinitum with little or no extra costs. Also for all practical purposes, nothing is distinguishing an original copy of a digital artifact from a duplicate.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;These are unique characteristics of digitalization. Given this, how then would it be possible to properly digitize commerce for instance? How would it be possible to create e-money just like e-mail? Electronic mail is not problematic, because duplicating a message and sending it multiple times does not in any way compromise the objective of communication which email serves, the same can&#39;t be said of a naively designed digital version of money.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;If the same endless duplication is possible with digital money, what is stopping someone from making multiple copies of a digital coin, to spend the coin multiple times? Being able to do this negates the ability to carry out commerce in the digital world. This problem, by the way, is called the double-spend problem.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Also, how can things like ownership be properly grafted into this new digital world? Since a digital copy of a digital thing is as good as the original?&amp;nbsp;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;Trusted third parties, bottlenecks, and anarchists&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;To enable commerce, on the internet, humans had to come up with financial institutions that acted as trusted third parties. This is not a new thing. The antithesis of anything digital when it comes to commerce, the paper money, originated in China in the 7th century, on the back of trusted third parties.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Before the use of these notes, the Chinese used circular copper coins. If you were wealthy, these copper coins soon became a burden to carry around, especially when used for larger transactions. To solve this problem, the coins could be deposited with a trusted person, who then gave the wealthy merchant a slip of paper (the receipt) that says how much money they had deposited. This slip of paper was then used in commercial activities in the exchange of goods and services. When the recipient of the paper slip returns to the trusted party, they could then exchange the slip of paper for the actual coins.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In the hundreds of years between 7th century China and the 20th century, human monetary affairs came to follow the Chinese model. Therefore it is no surprise that a model involving trusted third parties was also employed when commerce first moved online. In this model, the trusted party serves as the electronic mint that creates and tracks every digital coin that is being spent. In doing so, they can prove ownership and who is allowed to spend what coin, when it is spent, and that it can&#39;t be spent twice.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The first successful foray into digitizing money was &lt;a href=&quot;https://en.wikipedia.org/wiki/E-gold&quot;&gt;E-gold&lt;/a&gt;. E-gold was a digital gold currency run by Gold &amp;amp; Silver Reserve Inc, which served as trusted third parties. In this capacity they enabled people to transact business online by moving computer bits from one location to another with the assurance that transaction accounting was handled by the E-gold system and the actual money would be made available to parties when requested.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It is also worth pointing out that trusted third parties are not limited to commerce. They are a common modality when there is the need for an intermediary to mediate verification and exchange of value. Value could be money, or it could be real estate (then you need a notary), or IP addresses (then you need internet registries). The scenarios abound where trusted third parties are relied upon.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So with this model, digitalization of commerce, tracking, and transferring anything of value was made possible. Finally! Well, maybe not quite.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There is something not quite kosher, with a model involving a trusted third party: and that is the need to have a trusted third party. As the saying goes, absolute power corrupts absolutely. Trusted parties usually occupy a unique role that bestows upon them, if not absolute power, the closest thing to it.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Apart from the political schools of thought that would rather get rid of trusted third parties, there are other weaknesses to relying on trusted third parties. For one they are usually a single point of failure, or point of corruption, depending on the situation. They can also be bottlenecks as their inefficiencies can have rippling effects. Trusted third parties are also by their very nature centralized, and centralized systems are generally harder to scale. The internet would never have evolved into what it is today if it was centralized. (The internet is decentralized by the way).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;What then do we have? We are left with a deceleration in this march towards the digitalization of everything previously analog. The best we could come up with left us with an internet, where commerce, that quintessential human activity, could not be liberated from trusted third parties. It was also a state where concepts like ownership could not be fully grafted onto the digital world.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;Cryptography wins again!&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;The genius of Satoshi Nakamoto, the creator of blockchain was in conceiving a protocol that relied on cryptographic primitives to mediate the transfer of value without requiring the services of trusted third parties. Instead of trust, the cryptographic proof is relied upon. This creation is often referred to as the blockchain.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The blockchain is often seen as a synonym for bitcoin, which is not surprising, as bitcoin was the first implementation of the blockchain. But the blockchain is more than bitcoin. At the most fundamental level, the blockchain can be seen as a distributed ledger. The protocol outlined by Satoshi Nakamoto made it possible to have a distributed ledger that can track ownership and the transfer of ownership of digital artifacts, without needing a centralized repository. Instead of trusted third parties, a peer-to-peer, decentralized model is used, which relies on cryptographic proofs to keep the integrity of the ledger.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This means, instead of relying on centralized, trusted third parties to keep records of ownership and transfer of ownership of digital artifacts, we rely on cryptography instead. Making it possible to put information in a distributed ledger where everyone and anyone can see its contents, inspect and verify. This means once a transfer of ownership is reflected in the ledger, another attempt to invoke the same ownership transfer would be visible to all relevant parties involved and declined.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This invention made it possible to truly elevate money into the digital realm. Usage of physical money has never had to deal with the problem of double-spending, due to the very nature of it being physical. Once a coin goes from one hand to another, it is impossible for the former holder to still have the exact coin and attempt to transfer it to someone else. This was possible in the digital realm and for a long time, having a mediating third party that serves as a mint, was the only solution. Blockchain created a system that was able to impose constraints similar to those that come with physical money on digital currency, while avoiding the centralization trap. The protocol was able to achieve this without the need to have a trusted third party.&amp;nbsp; &amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Satoshi Nakamoto&#39;s outline of the blockchain was just the spark that ignited other ideas that have led to the emergence of the cryptocurrency/blockchain industry. Once it became clear how to transfer digital artifacts between parties, the next step was to make this programmable. And this is exactly the innovation Ethereum brought into the space.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ethereum created a computation layer on top of the blockchain, making it possible to encode autonomous rules that control how digital artifacts are to be moved between parties on top of the blockchain. This layer of computation on the blockchain is often referred to as smart contracts. Even though it was coined in the 1990s, by Nick Szabo, arguably Ethereum was what made the term smart contract mainstream.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Another important idea that proved to be critical is the idea of permanence. There are cases where information is required to be unmodifiable. For example, the details of a contract for instance should be unmodifiable after the fact. Unfortunately digital information cannot generally guarantee such a constraint. Digital information is by nature modifiable.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Permanence is one of the central value propositions of the blockchain. If you think about this, it makes sense. A technology that records transactions of value should not allow rewriting of history. Information contained on the blockchain can be considered permanent because the way the protocol is assembled, again making use of cryptography, is such that the cost of going back to change any information on it is so great that it is effectively impossible.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The only snag is, the blockchain is not designed to be a store of arbitrary large data. It does not scale for such a use case. This is where the idea of a permanent web comes into the picture, which, simply put, is a web where contents are immutable. That is, once content is created it should not be editable.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The current web is mutable. Digital content at a particular URL can be changed even though the URL remains the same. Having such mutability is at odds with the need to make statements about permanent events on the web. For example, a contract between two parties found at a particular URL provides less value when there is no guarantee that the content at the URL would always stay the same. A permanent web provides such guarantees.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There has been, and continues to be many attempts at implementing such a permanent web. Arguably, the effort that has been enjoying the most success is IPFS. Which is not only a permanent web but also a distributed web. With IPFS, it is possible to offload large data that needs to be immutable out of the blockchain to the permanent web and have only a reference stored on the blockchain.&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The appearance of these technologies: blockchain, smart contracts, permanent web, etc has made it possible for us to continue with the onward march of digitizing our world. These technologies have made it possible to replicate the properties of physical items like scarcity, uniqueness, and proof of ownership in the digital world. Properties that were previously hard to digitize.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;Emergence of the NFT&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;Now that we have these technologies, as is usually the case, thanks to human ingenuity, what has followed is the realization that these technologies can be put to use in clever ways. We have since seen their applications in the financial industry (Defi — Decentralized finance), to new and creative ways organization can be managed (DAO — Distributed Autonomous Organisation), to applications in the supply chain industry.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;How blockchain and smart contracts can be used is almost endless and rightly so. This is because a lot of society and human interaction involves dealing with scarcity, uniqueness of things, ownership, and transferring of value. Once we had the means to represent these in the digital world, the possibilities became endless.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A recent application of blockchain and smart contracts that succinctly captures this is the emergence of what is now known as NFTs (Non-Fungible tokens), which have proven to be particularly germane in the creative — music, art, collectible — industry.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;What actually is a NFT?&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;Let&#39;s start with what a token is. A token can be said to be a digital artifact that could either exist 100% in the digital world, without any physical counterpart or a digital representation of something physical.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A token could represent currency, lottery tickets, shares in a company, reputation points in an online platform, title deeds, etc.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Tokens could also be of two kinds. They are either fungible or non-fungible. A fungible token is a digital artifact without identity and hence not unique. Non-fungible tokens on the other hand are inherently unique because they possess an inherent identity.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To illustrate: A 5 dollar bill is as good as the next 5 dollar bill. This is because each banknote does not function on the basis of a unique identity, hence they are fungible. Which is another way of saying they are replaceable with one another, as long as their values are the same. Some other artifacts, on the other hand, carry intrinsic identity and can&#39;t just be replaced by another. For example a birth certificate, if tokenized, would be non-fungible.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;An NFT is then a unique, digital artifact that can exist on a blockchain.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;Why NFTs?&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;It turns out there are a lot of things in the physical world that are valuable because of their non-fungibility. Being able to capture this and represent it in the digital world is what makes an NFT such a valuable piece in the crypto space.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In the digital art sphere, an artist can create a work of art, sell it to a buyer and issue an NFT that can be used to prove ownership of that unique work of art.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In the gaming industry, NFTs can be used to represent and prove ownership of unique in-game items.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In the music industry, an artist can issue a unique NFT to everyone who buys an album. Such an NFT can then be used to prove ownership of purchase and/or to unlock extra content.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;NFTs can also be used to create digital collectibles as well as memorabilia, in which case the NFT can be used to capture and document the authenticity of a memorable event.&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;NFTs can also be used as perks in crowdfunding campaigns. This is exactly what the DishAfrik NFT will do.&amp;nbsp;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;DishAfrik&#39;s NFT perk&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;As earlier stated, I am currently running an IndieGoGo campaign to kickstart the development of DishAfrik: a recipe app to discover, enjoy and share African recipes.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;One of the perks for backers of the Indiegogo campaign will be an NFT. The NFT will be a uniquely generated image collage similar to Beeple’s &lt;a href=&quot;https://en.wikipedia.org/wiki/Everydays:_the_First_5000_Days&quot;&gt;Everydays: The First 5000 Days&lt;/a&gt; . The NFT will consist of pictures of 54 recipes from 54 African countries. The ingredients and cooking steps will be included as part of the NFTs meta-data. The NFT galley would be hosted on &lt;a href=&quot;https://cryptodisho.com/&quot;&gt;CryptoDisho&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The DishAfrik NFT perk will serve as a means for capturing participation in an activity (in this case the backing of a non-equity fundraising campaign) and encode that in the digital world. Recipients of the NFT perk will be able to prove that they indeed backed the IndieGoGo campaign.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The NFT will also be a digital art that can be owned: a picture made up of a collage of 54 recipes from 54 African countries.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As the IndieGoGo campaign will be an event in time, the NFT will also have memorabilia value.&amp;nbsp; Who knows what this will be worth in the coming years?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Participation in an event, prove-able ownership of art, and memorabilia artifacts were all things that existed without hassle in the physical world before now. But with the advent of new technologies that further the convergence of the physical and digital world, it is now possible to represent these things also in the digital world.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is why the DishAfrik NFT perk exists.&amp;nbsp;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;Metaverse, virtual and augmented reality&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;This convergence of the physical and digital world that started with the digital revolution shows no sign of abating. One can say we are on the cusp of breakthroughs in these endeavors. Technologies within the space of virtual and augmented reality are exploring ways to further translate other unique physical attributes like &quot;presence&quot; into the digital world.&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Mark Zuckerberg thinks this is the future. And spurred on by this belief he has laid out his intention to transform &lt;a href=&quot;https://www.theverge.com/22588022/mark-zuckerberg-facebook-ceo-metaverse-interview&quot;&gt;Facebook into a metaverse company&lt;/a&gt;. This would turn Facebook into a place where there is the convergence of physical, augmented, and virtual reality in a shared online space.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Although we do not have such a metaverse yet, and it might take a couple more years before its full realization, we do have technologies like NFTs now. And because of that, there is a campaign to build a platform to showcase African cuisine that if you back, you have an option of owning an NFT.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;https://igg.me/at/dishafrik&quot;&gt;So you should go check that out now!&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://www.geekabyte.io/2021/09/why-i-am-offering-nfts-as-crowdfunding.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-7566309824043363692</guid><pubDate>Fri, 11 Jun 2021 13:50:00 +0000</pubDate><atom:updated>2021-06-11T15:50:17.838+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">TypeScript</category><title>Understanding the Magic behind Utility Types in TypeScript</title><description>&lt;p&gt;This post will be the conlcuding post in the &lt;a href=&quot;https://www.geekabyte.io/2021/01/introduction-to-advance-types-in.html&quot;&gt;Introduction to Advanced Types in TypeScript&lt;/a&gt; series. It looks at some of the utility Types in TypeScript, explain how it works while pointing out the features within the TypeScript type system that makes it possible.&lt;/p&gt;

&lt;h3&gt;Why TypeScript?&lt;/h3&gt;

&lt;p&gt;TypeScript comes with a powerful and expressive type system. Its expressiveness makes it a joy to work with while its powerful features makes it possible to build, and scale large codebases by providing type safety.&lt;/p&gt; 

&lt;p&gt;One of the ways TypeScript brings about type safety is by providing developers the tool to manipulate types in ways that encode constraints within the type system. This then ensures that code that could lead to runtime exception do not compile, making it possible to catch errors during development time and not in production. One of such tools TypeScript provides for this are Utility Types.&lt;/p&gt;

&lt;p&gt;Utility Types are a set of Generic Types that come natively within TypeScript that makes it possible to transform one type into another. This sort of type transformation is useful because it makes it possible to take exiting types, and apply modifications to it which would ensure the enforcement of certain constraints.&lt;/p&gt;

&lt;p&gt;In this post, we would look at 2 of such Utility type and how they could be used to provide more type safety. After that, we would take a step back to understand some of the other TypeScript features that come together to make Utility Types possible.  Armed with this knowledge, we will then demystify Utility types by taking a peek under the hood of the 2 Utility types in focus to see how they are implemented.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The two utility types that will be exmaned are Required&amp;lt;T&amp;gt; and&amp;nbsp; Exclude&amp;lt;T&amp;gt;. This post assumes basic knowledge of TypeScript and what Generic Types are. Other features of TypeScript type systems would be explained.&lt;/p&gt;


&lt;h3&gt;Required&amp;lt;T&amp;gt; and&amp;nbsp; Exclude&amp;lt;T&amp;gt;&lt;/h3&gt;

&lt;p&gt;We first look at how to make use Required&amp;lt;T&amp;gt; and&amp;nbsp; Exclude&amp;lt;T&amp;gt;. Starting with Required&amp;lt;T&amp;gt;.&lt;/p&gt;

&lt;b&gt;Using Required&amp;lt;T&amp;gt;&lt;/b&gt;

&lt;p&gt;Required&amp;lt;T&amp;gt; is an utility type that creates a new type based on an existing one by marking all the properties in the new type &lt;em&gt;required&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To illustrates let’s imagine we have a &lt;code&gt;Post&lt;/code&gt; type. A post can also have a score value which is calculated dynamically or might not even be calculated yet, hence the &lt;code&gt;score&lt;/code&gt; property on the &lt;code&gt;Post&lt;/code&gt; type should be optional. The definition of such a post type could look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;type Post = {
 title: string
 publishedDate: number
 score?: number
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the score on a post has been calculated we want this to be obvious and explicit. Having &lt;code&gt;score&lt;/code&gt; as optional does not give use explicitness. One way to go about this, is to create another type with &lt;code&gt;score&lt;/code&gt; not optional. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;type ScoredPost = {
 title: string
 publishedDate: number
 score: number
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And we can then have a function that scores a post by taking a value of &lt;code&gt;Post&lt;/code&gt; and converting it to a value of &lt;code&gt;ScoredPost&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;function scorePost(post: Post): ScoredPost {
   return {
      title: post.title,
      publishedDate: post.publishedDate,
      score: post.publishedDate * Math.random()
     }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But having both &lt;code&gt;Post&lt;/code&gt; and &lt;code&gt;ScoredPost&lt;/code&gt; is a bit verbose as it is clearly obvious that &lt;code&gt;ScoredPost&lt;/code&gt; is just a &lt;code&gt;Post&lt;/code&gt; with the &lt;code&gt;score&lt;/code&gt; property now required. &lt;/p&gt;
  
&lt;p&gt;Having &lt;code&gt;Post&lt;/code&gt; and &lt;code&gt;ScoredPost&lt;/code&gt; is not only verbose it also adds to maintenance burden as any update to either of the types need to be manually reflected on the other.&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;ScoredPost&lt;/code&gt; is clearly a transformation of &lt;code&gt;Post&lt;/code&gt; with &lt;code&gt;score&lt;/code&gt; now required, we can easily apply the &lt;code&gt;Required&amp;lt;T&amp;gt;&lt;/code&gt; utility type here. To do that, the &lt;code&gt;scorePost&lt;/code&gt; function would be updated as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;function scorePost(post: Post): Required&amp;lt;Post&amp;gt; {
    return {
      title: post.title,
      publishedDate: post.publishedDate,
      score: post.publishedDate * Math.random()
     }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This shows the power of a utility type such as Required&amp;lt;T&amp;gt;: easily create a new type from an existing type while enforcing the required property constraint.&lt;/p&gt;

&lt;b&gt;Using Exclude&amp;lt;T, U&amp;gt;&lt;/b&gt;

&lt;p&gt;Exclude&amp;lt;T, U&amp;gt; is also another utility type that creates a new type based on an existing one. It does this by excluding certain properties from one type to create a new type.&lt;/p&gt;
&lt;p&gt;To illustrates let’s imagine we have a &lt;code&gt;AdminRights&lt;/code&gt; type and a &lt;code&gt;UserRights&lt;/code&gt; type. The &lt;code&gt;UserRights&lt;/code&gt; could either be &lt;code&gt;read&lt;/code&gt; or &lt;code&gt;write&lt;/code&gt;, while &lt;code&gt;AdminRights&lt;/code&gt; is all the permissions presents in &lt;code&gt;UserRights&lt;/code&gt; with the &lt;code&gt;execute&lt;/code&gt; permission added. These two types could be defined as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type  AdminRights = &quot;read&quot; | &quot;write&quot; | &quot;execute&quot;
type  UserRights = &quot;read&quot; | &quot;write&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But having both &lt;code&gt;AdminRights&lt;/code&gt; and &lt;code&gt;UserRights&lt;/code&gt; can be seen as being verbose since &lt;code&gt;UserRights&lt;/code&gt; is &lt;code&gt;AdminRights&lt;/code&gt; without the &lt;code&gt;execute&lt;/code&gt; option. &lt;/p&gt;
  
&lt;p&gt;It also does not make it explicit that &lt;code&gt;UserRights&lt;/code&gt; is all the &lt;code&gt;AdminRights&lt;/code&gt; with the &lt;code&gt;execute&lt;/code&gt; excluded. To make this clearer we can use the &lt;code&gt;Exclude&amp;lt;T, U&amp;gt;&lt;/code&gt; utility type.&lt;/p&gt;

&lt;p&gt;The definition would then look as follows:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type AdminRights = &quot;read&quot; | &quot;write&quot; | &quot;execute&quot; 
type UserRights = Exclude&amp;lt;AdminRights, &quot;execute&quot;&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, we are creating a new type &lt;code&gt;UserRights&lt;/code&gt;, from &lt;code&gt;AdminRights&lt;/code&gt; by excluding the &lt;code&gt;&quot;execute&quot;&lt;/code&gt; property. Making it explicit how &lt;code&gt;UserRights&lt;/code&gt; is related to &lt;code&gt;AdminRights&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now we have seen two examples of Utility types in TypeScript. We would now take a quick look at some of the features of TypeScript that makes these utility types possible.&lt;/p&gt;

&lt;h3&gt;Building Blocks of Utility Types&lt;/h3&gt;
&lt;br /&gt;
&lt;b&gt;KeyOf&lt;/b&gt;

&lt;p&gt;The &lt;code&gt;KeyOf&lt;/code&gt; type operator is an operator that can be used to get all of the properties of a type as a union type. For example, given the type &lt;code&gt;Post&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Post = {
 title: string
 publishedDate: number
 score: number
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All the properties of &lt;code&gt;Post&lt;/code&gt;, that is &lt;code&gt;title&lt;/code&gt;, &lt;code&gt;publishedDate&lt;/code&gt; and &lt;code&gt;score&lt;/code&gt; can be retrieved as union type using the &lt;code&gt;keyOf&lt;/code&gt; operator:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Props = keyof Post
// Props =&amp;gt; &quot;title&quot; | &quot;publishedDate&quot; | &quot;score&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;blockquote&gt;Check &lt;a href=&quot;https://www.geekabyte.io/2021/02/introduction-to-index-types-in.html&quot;&gt;Introduction to Index Types in TypeScript&lt;/a&gt; for a more detailed introduction to the keyof operator.&lt;/blockquote&gt;

&lt;b&gt;Conditional Types&lt;/b&gt;

&lt;p&gt;Conditional types can be thought of as a mechanism by which we can perform ternary operations on types. For conditional types, the operation that determines which type is returned is an assignability check, unlike a boolean check as is the case with normal ternary operation that works on values.  A conditional types look as follows:&lt;/p&gt;&lt;br /&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type  Post = {
   title: string
   publishedDate: number
   score: number
}
// the conditional type
type  RatedPost&amp;lt;T&amp;gt; = &quot;score&quot;  extends  keyof  T ? T : never&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above code snippet, &lt;code&gt;RatedPost\&amp;lt;T&amp;gt;&lt;/code&gt; is defined as a conditional type, which makes use of generics. It returns the type &lt;code&gt;T&lt;/code&gt; as long as it has the &lt;code&gt;score&lt;/code&gt; property, if not it returns &lt;code&gt;never&lt;/code&gt;. &lt;code&gt;never&lt;/code&gt; is a type that has no value &lt;em&gt;ever&lt;/em&gt;, hence if we have a compile error if the conditional type ever evaluates in such a way that the &lt;code&gt;never&lt;/code&gt; is returned.&lt;/p&gt;


&lt;blockquote&gt;See &lt;a href=&quot;https://www.geekabyte.io/2021/04/conditional-types-in-typescript.html&quot;&gt;Conditional Types in Typescript&lt;/a&gt; for a more indepth exploration of Conditional Types. See &lt;a href=&quot;https://www.geekabyte.io/2021/04/any-unknown-and-never-types-in.html&quot;&gt;any, unknown and never types in Typescript&lt;/a&gt; for a more detailed introduction of the &lt;code&gt;never&lt;/code&gt; type &lt;/blockquote&gt;

&lt;p&gt;To see this in use, we can define a function: &lt;code&gt;resetScore&lt;/code&gt; that only takes a post that already has a score. Such definition would look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;function resetScore(post: RatedPost&amp;lt;Post&amp;gt;) {
  // do stuff
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This can be called as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;resetScore({
 title: &quot;hello post&quot;, 
 publishedDate: 1621034427002, 
 score: 2
})&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but passing an object that has no &lt;code&gt;score&lt;/code&gt; property would lead to a compile error:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;resetScore({
  title: &quot;hello post&quot;, 
  publishedDate: 1621034427002
})
&lt;/code&gt;&lt;/pre&gt;

&lt;code&gt;Argument of type ‘{ title: string; publishedDate: number; }’ is not assignable to parameter of type ‘Post’. Property ‘score’ is missing in type ‘{ title: string; publishedDate: number; }’ but required in type ‘Post’&lt;/code&gt;

&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Mapped Types&lt;/b&gt;

&lt;p&gt;A mapped type is a type that is created by using the &lt;code&gt;keyof&lt;/code&gt; operator to access the properties of another type and modifying the extracted properties in some way to create a different type. For example, a Mapped type that takes a &lt;code&gt;Post&lt;/code&gt; type and convert all its properties to &lt;code&gt;string&lt;/code&gt; would be defined as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// initial type
type  Post = {
  title: string
  publishedDate: number
  score: number
}

// mapped type
type  StringPost&amp;lt;T&amp;gt; = {
   [K  in  keyof  T]: string
}

// usage of mapped type
let stringPost: StringPost&amp;lt;Post&amp;gt; = {
   title: &quot;How to do the wiggle&quot;,
   publishedDate: &quot;15/05/2021&quot;,
   score: &quot;2&quot;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Taking a closer look at the mapped type definition:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type  StringPost&amp;lt;T&amp;gt; = {
   [K  in  keyof  T]: string
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can break down the code listed above as : &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;keyof  T&lt;/code&gt; gets all properties of &lt;code&gt;T&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;[K  in  keyof  T]&lt;/code&gt; loop through all the properties of &lt;code&gt;T&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;and finally &lt;code&gt;[K  in  keyof  T]: string&lt;/code&gt;, loop through all the properties of &lt;code&gt;T&lt;/code&gt; and assign &lt;code&gt;string&lt;/code&gt; as their &lt;code&gt;type&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;See &lt;a href=&quot;https://www.geekabyte.io/2021/04/mapped-types-in-typescript.html&quot;&gt;Mapped Types in Typescript&lt;/a&gt; for a more indepth exploration of Mapped Types.&lt;/blockquote&gt;

&lt;p&gt;Now that we are armed with the knowledge of these TypeScript features, let&#39;s now see how they are applied to create Utility types.&lt;/p&gt;

&lt;h3&gt;Demystifying Utility Types&lt;/h3&gt;

&lt;p&gt;Utility types are created from the application of some or all of the TypeScript features highlighted in previous sections. We will now take a look at the source code of the two utility types described above: &lt;code&gt;Required&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;Exclude&amp;lt;T, U&amp;gt;&lt;/code&gt; and see how they are defined. &lt;/p&gt; 
  
&lt;p&gt;The source code can be found in &lt;a href=&quot;https://github.com/microsoft/TypeScript/blob/master/src/lib/es5.d.ts&quot;&gt;es5.d.ts&lt;/a&gt;&lt;/p&gt;

&lt;b&gt;Required&amp;lt;T&amp;gt; Under The Hood&lt;/b&gt;

&lt;p&gt;The Required&amp;lt;T&amp;gt; is defined as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;/**
* Make all properties in T required
*/
type Required&amp;lt;T&amp;gt; = {
    [P in keyof T]-?: T[P];
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/microsoft/TypeScript/blob/f414d136795ab248c551978ad286717c016998eb/src/lib/es5.d.ts#L1455&quot;&gt;source&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let us break it apart:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;This is a Mapped Type&lt;/li&gt;
&lt;li&gt;&lt;code&gt;keyof  T&lt;/code&gt; gets all properties of &lt;code&gt;T&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;[P  in  keyof  T]&lt;/code&gt; loop through all the properties of &lt;code&gt;T&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;-?&lt;/code&gt; in &lt;code&gt;[P in keyof T]-?&lt;/code&gt; means remove the character &lt;code&gt;?&lt;/code&gt; from the definition of the properties. This is how the optionality of the properties are removed and made required&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;T[P]&lt;/code&gt; in the type definition means, take as type whatever property &lt;code&gt;P&lt;/code&gt; is as part of type &lt;code&gt;T&lt;/code&gt;. This way the original type of &lt;code&gt;P&lt;/code&gt; is used in the mapped type.&lt;/li&gt;
&lt;li&gt;Finally &lt;code&gt;[P in keyof T]-?: T[P];&lt;/code&gt; can be read as loop through all the properties of &lt;code&gt;T&lt;/code&gt; remove the optional modifier &lt;code&gt;?&lt;/code&gt;, and keep original type.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is it. Note that in the case where modifiers are to be added, the &lt;code&gt;-&lt;/code&gt; can be dropped which defaults to adding, or &lt;code&gt;+&lt;/code&gt;, can be used.&lt;/p&gt;
&lt;p&gt;For example, instead of making all properties required, if we want to make them option, we would have the definition as &lt;code&gt;[P in keyof T]+?: T[P];&lt;/code&gt; or &lt;code&gt;[P in keyof T]?: T[P];&lt;/code&gt;. In fact there is utility type for this and it is called &lt;code&gt;Partial&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;b&gt;Exclude&amp;lt;T, U&amp;gt; Under The Hood&lt;/b&gt;

&lt;p&gt;The Exclude&amp;lt;T, U&amp;gt; is defined as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;/**
* Exclude from T those types that are assignable to U
*/
type Exclude&amp;lt;T, U&amp;gt; = T extends U ? never : T;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/microsoft/TypeScript/blob/f414d136795ab248c551978ad286717c016998eb/src/lib/es5.d.ts#L1483&quot;&gt;source&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let us break it apart:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;This is a conditional type&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Exclude&amp;lt;T, U&amp;gt;&lt;/code&gt; defines a generic with two variables: &lt;code&gt;T&lt;/code&gt; and &lt;code&gt;U&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;T extends U&lt;/code&gt; is the conditional check of the conditional type.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;T extends U&lt;/code&gt; then &lt;code&gt;never&lt;/code&gt; is returned&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;T extends U&lt;/code&gt; is false, then &lt;code&gt;T&lt;/code&gt; is returned.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code&gt;T extends U&lt;/code&gt; is checking if &lt;code&gt;T&lt;/code&gt; is a subtype of &lt;code&gt;U&lt;/code&gt;. That is, if all properties of &lt;code&gt;U&lt;/code&gt; can be found in &lt;code&gt;T&lt;/code&gt;. If this not the case, then &lt;code&gt;T&lt;/code&gt; is returned which would then be all the properties of&lt;code&gt;U&lt;/code&gt; with the properties found in &lt;code&gt;T&lt;/code&gt; excluded.&lt;/p&gt;
&lt;p&gt;This is how the exclusion in &lt;code&gt;Exclude&amp;lt;T, U&amp;gt;&lt;/code&gt; is implemented.&lt;/p&gt;
&lt;p&gt;As can be seen, even though utility types are powerful, there is nothing mysterious about them and they are understandable. They are created by using other features of TypeScript.&lt;/p&gt;
&lt;p&gt;TypeScript comes with more utility types defined which can be found &lt;a href=&quot;https://github.com/microsoft/TypeScript/blob/master/src/lib/es5.d.ts&quot;&gt;here&lt;/a&gt;, and hopefully this post now helps in appreciating what they are and how they are implemented to do what they do.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2021/06/understanding-magic-behind-utility.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-5745663827166054260</guid><pubDate>Mon, 07 Jun 2021 17:15:00 +0000</pubDate><atom:updated>2021-06-08T15:09:29.986+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Deno</category><category domain="http://www.blogger.com/atom/ns#">TypeScript</category><title>First impressions with Deno from building PlanetTypeScript.com</title><description>&lt;p&gt;&lt;a href=&quot;http://www.planettypescript.com&quot;&gt;PlanetTypeScript.com&lt;/a&gt;&amp;nbsp;is a content aggregator for all things TypeScript. It regularly polls RSS feeds for TypeScript related content, which it then list on the site, send out as a tweet via &lt;a href=&quot;https://twitter.com/planetypescript&quot;&gt;@planetypescript&lt;/a&gt;, and also as a weekly digest to subscribers.&lt;/p&gt;

&lt;p&gt;Back when I used to write a lot of Java-related content on this blog, I found out that my blog ended up on &lt;a href=&quot;https://www.topjavablogs.com/&quot;&gt;www.topjavablogs.com/&lt;/a&gt;, which is a site that aggregates Java contents. So when I decided to play around with Deno, I thought a nice little idea would be to build something similar to topjavablogs.com, but for TypeScript. And that is how &lt;a href=&quot;https://PlanetTypescript.com&quot;&gt;PlanetTypescript.com&lt;/a&gt; was born.&lt;/p&gt;

&lt;p&gt;In this post, I will share some of my first impressions with Deno. The things I enjoyed and the bits I found inconvenient. Let&#39;s start with the cool stuff.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;

&lt;h3&gt;Native TypeScript Support&lt;/h3&gt;
&lt;p&gt;I find it super convenient that I could just write TypeScript without worrying about setting up a build chain that would take care of the &lt;i&gt;transpilation&lt;/i&gt; to JavaScript. This is really nice and it makes TypeScript feel more like a standalone language in its own rights. This has to be one of the top-selling points of Deno for me.&lt;/p&gt;

&lt;h3&gt;Built-in utilities&lt;/h3&gt;
&lt;p&gt;The deno CLI comes with a whole lot of useful utilities and just comes in handy. For example &lt;span style=&quot;font-family: courier;&quot;&gt;deno info&lt;/span&gt; to check the dependencies. &lt;span style=&quot;font-family: courier;&quot;&gt;deno fmt&lt;/span&gt;, a code formatter,&amp;nbsp;&amp;nbsp;&lt;span style=&quot;font-family: courier;&quot;&gt;deno bundle&lt;/span&gt; for bundling modules and dependencies into a single file, &lt;span style=&quot;font-family: courier;&quot;&gt;deno compile&lt;/span&gt; for creating a self-contained executable, etc.&lt;/p&gt;

&lt;p&gt;I personally find dealing with build pipelines within the JavaScript ecosystem to be a tiring chore. Having something like &lt;span style=&quot;font-family: courier;&quot;&gt;deno bundle&lt;/span&gt;&amp;nbsp;or&amp;nbsp;&lt;span style=&quot;font-family: courier;&quot;&gt;deno compile&lt;/span&gt;, built-in is super useful, as it takes care of most of the heavy lifting when it comes to deployment.&lt;/p&gt;

 
&lt;h3&gt;Web API&lt;/h3&gt;

&lt;p&gt;Deno seeks to provide implementations of Web API, and this I found to be really handy. For &lt;a href=&quot;https://PlanetTypescript.com&quot;&gt;PlanetTypeScript.com&lt;/a&gt;, I need to make HTTP requests and also run background tasks. I could use &lt;span style=&quot;font-family: courier;&quot;&gt;fetch&lt;/span&gt; and &lt;span style=&quot;font-family: courier;&quot;&gt;web workers&lt;/span&gt; for this. API&#39;s I am already familiar with coming from the Web, and no need to install third-party libraries. This is super convenient. &lt;/p&gt;

&lt;h3&gt;Good Standard Library&lt;/h3&gt;

&lt;p&gt;In the course of building &lt;a href=&quot;https://PlanetTypescript.com&quot;&gt;PlanetTypeScript.com&lt;/a&gt;, I needed to have logging, base64 encoding, use hash functions, and generating UUIDs. I was able to find modules within the Deno standard library that I could use for all of these. The Deno standard library is quite decent and has a battery-included feel to it. You can peruse the available modules &lt;a href=&quot;https://deno.land/std&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;


&lt;h3&gt;IDE Support&lt;/h3&gt;

&lt;p&gt;I primarily use Jetbrains IDEs. When not within a full-blown IDE environment, I use Microsoft Visual Studio Code. Both of these tools have plugins that implement support for Deno and they work very well. I was able to use the visual debugger in IntelliJ, which was quite handy. &lt;/p&gt;

 
&lt;p&gt;So these are some of the cool things that made a good first impression on me with Deno. Below are some of the things that were a bit of a hassle.&lt;/p&gt;


&lt;h3&gt;No Registry and Package Manager.&lt;/h3&gt;

&lt;p&gt;Deno does not have any well-known central registry from which a package manager manages dependencies. Instead, Deno works with plain URLs. This setup leads to certain consequences which I believe hamper the developer experience.&amp;nbsp;&lt;/p&gt;&lt;p&gt;For example, there is no central file to look into, to see all the dependencies of a project. To work around this, the convention in the Deno community is to re-import all dependencies from a file called &lt;span style=&quot;font-family: courier;&quot;&gt;deps.ts&lt;/span&gt; - basically recreating some sort of package.json.&lt;/p&gt;

&lt;p&gt;Also, there is no easy way to quickly see if there are new versions of any of my project&#39;s dependencies. Or even better still, no command I could run from the command line that updates dependencies.&amp;nbsp;&lt;/p&gt;&lt;p&gt;I later learned about &lt;a href=&quot;https://github.com/crewdevio/Trex&quot;&gt;Trex&lt;/a&gt; and &lt;a href=&quot;https://github.com/drashland/dmm&quot;&gt;dmm&lt;/a&gt; which could be used to achieve some of these tasks. I can&#39;t comment on them now as I have not gotten around to try them out yet.&lt;/p&gt;

&lt;p&gt;From the perspective of the developer, I am yet to see the advantage the Deno model brings to the table. Instead, it feels to me more like a philosophical design decision, rather than a pragmatic one.&lt;/p&gt;

&lt;h3&gt;Nascent Library Ecosystem.&lt;/h3&gt;

&lt;p&gt;The inability to find needed third-party libraries proved to be one of the main inconveniences. &lt;/p&gt;

&lt;p&gt;I had issues finding a third-party library to deal with OAuth. I tried &lt;a href=&quot;https://github.com/oslabs-beta/dashport&quot;&gt;Dashport&lt;/a&gt;, but it has become incompatible with recent versions of Deno and &lt;a href=&quot;https://oakserver.github.io/oak/&quot;&gt;Oak&lt;/a&gt; (the HTTP middleware library I used). I tried using Firebase-auth, but there is no support for Deno.&lt;/p&gt;

&lt;p&gt;I use MailChimp for sending the Weekly digests. Since the content of the emails would be different weekly, I needed to build the message dynamically. This involves interacting with MailChimp via its API. Unfortunately, MailChimp does not have an API client library for Deno, so I ended up having to directly call the needed HTTP endpoints.&lt;/p&gt;

&lt;p&gt;Deno does have a compatibility layer that makes it possible to use Node/npm modules from within Deno. There are also CDN&#39;s like &lt;a href=&quot;https://www.skypack.dev/&quot;&gt;Skypack&lt;/a&gt; that make it possible to import npm modules for use within Deno. What I quickly found out, is that these workarounds, work best for the simplest of libraries. It does not work for anything slightly complicated. For example, I could not use any of these methods to get the Node library for Firebase-auth nor Mailchimp client library to work.&lt;/p&gt;    

&lt;p&gt;This nascency is strictly not a structural issue with Deno and something to be expected, given how new Deno is. This is also the sort of thing that would improve with time.&lt;/p&gt;

&lt;h3&gt;Conclusion.&lt;/h3&gt;
&lt;p&gt;I enjoyed using Deno. Having native TypeScript support, various CLI utilities, and a battery included-standard library, makes it easy to get productive real quick. The main inconveniences I encountered can be chucked up to Deno still being relatively new, but even with that, it is still a hell of a lot usable/productive for a 3 years old project.&lt;/p&gt;</description><link>http://www.geekabyte.io/2021/06/first-impressions-with-deno-from.html</link><author>noreply@blogger.com (dade)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-2121423919413422003</guid><pubDate>Fri, 28 May 2021 05:59:00 +0000</pubDate><atom:updated>2021-05-28T08:05:23.993+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">TypeScript</category><title>3 Ways to Name Types in Typescript</title><description>&lt;p&gt;TypeScript type&#39;s system is structural and hence, it allows for the easy creation of types based on the shape of data. These types can be created and used without having a name. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;let john: {name: string, age: number} = { 
  name: &quot;John Doe&quot;, 
  age: 30
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where &lt;span style=&quot;font-family: courier;&quot;&gt;{name: string, age: number}&lt;/span&gt; is the type defined.&lt;/p&gt;

&lt;p&gt;But there is a problem with using the type definition this way. If we want to create another &lt;span style=&quot;font-family: courier;&quot;&gt;person&lt;/span&gt; and annotate another variable with the type, we would need to repeat ourselves:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;let john: {name: string, age: number} = {
  name: &quot;John Doe&quot;, 
  age: 30
}

let jane: {name: string, age: number} = {
   name: &quot;Jane Doe&quot;, 
   age: 45
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is not &lt;i&gt;dry&lt;/i&gt;.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;

&lt;p&gt;It is not dry because we have to repeat the types. A more efficient approach would be to define the type once, give it a name and then use the name when applying the type annotation. Fortunately, we can do exactly this.&lt;/p&gt;

&lt;p&gt;TypeScript provides mechanisms for giving a name to a type, which can then be used when applying type annotations. We are going to look into the 3 different mechanisms through which this can be done. Namely: via classes, type aliases and interfaces.&lt;/p&gt;

&lt;h3&gt;Classes&lt;/h3&gt;

&lt;p&gt;A class can be seen as a blueprint for the creation of objects. For example given the following class definition:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }

}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can use it to create various instance objects:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// class definition
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }

}

// creating instances
let john = new Person(&quot;John Doe&quot;, 30)
let jane = new Person(&quot;Jane Doe&quot;, 45)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The interesting thing with classes is they are also &lt;i&gt;a mechanism for defining and naming types&lt;/i&gt;. They not only serve as a blueprint for object creation, but they also create a type, which is named.&lt;/p&gt; 

&lt;p&gt;The &lt;span style=&quot;font-family: courier;&quot;&gt;Person&lt;/span&gt; class we defined also simultaneously creates a &lt;span style=&quot;font-family: courier;&quot;&gt;Person&lt;/span&gt; type, which we can use as a type annotation:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// class definition
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }

}

// annotating instances
let john: Person = new Person(&quot;John Doe&quot;, 30)
let jane: Person = new Person(&quot;Jane Doe&quot;, 45)&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Type Aliase&lt;/h3&gt;

&lt;p&gt;Type aliases are another mechanism for naming types in TypeScript. It is a feature that makes it possible to give a name (or alias) to another type.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;type Person = {name: string, age: number}
type MyString = string
// An alias can be given for an existing alias
type OhMyString = MyString&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hence it is best to see type aliases as a way to give a name to an already existing anonymous type, primitive type, or even another type alias. &lt;/p&gt;

&lt;h3&gt;Interfaces&lt;/h3&gt;

&lt;p&gt;Interfaces are another mechanism for creating types and naming them in TypeScript. It takes the following form:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;interface Person {
    name: string,
    age: number
}&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;As can be seen, even though &lt;i&gt;interface&lt;/i&gt; looks similar to using &lt;i&gt;type aliases&lt;/i&gt;, they are not the same. Unlike type aliases, interfaces actually create a new type, and gives it a name, while type aliases only create a name for an existing type.&lt;/p&gt;

&lt;p&gt;The 3 mechanisms shown thus far (classes, type aliases, and interfaces) provide us with 3 ways for doing the same thing: the naming of types. Even though they allow us to achieve similar things, there are some differences. In the next section, we take a look at some of these differences.&lt;/p&gt;

&lt;h3&gt;Difference Between Classes, Type Aliases, and Interfaces&lt;/h3&gt;
&lt;br/&gt;
&lt;b&gt;The Presence or absence of a constructor&lt;/b&gt;

&lt;p&gt;Classes differ from type aliases and interfaces in that it also provides a constructor that can be used to create well form instances of values for the type being defined. This is achieved by using the familiar &lt;i&gt;new&lt;/i&gt; keyword:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// class definition
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }

}

// creating instances using constructor
let john: Person = new Person(&quot;John Doe&quot;, 30)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Constructors are not created as part of using type aliases nor interfaces.&lt;/p&gt;

&lt;b&gt;Extension mechanism&lt;/b&gt;

&lt;p&gt;Classes, type aliases, and interfaces all provide a mechanism for type extension, which is the ability to create a new type based on an already existing type. The only difference is the syntax used.&lt;/p&gt;

&lt;p&gt;Extending types via classes takes the following form:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;//type definition 
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
      
}

// type extension
class Employee extends Person {
       isManager: boolean;
       
       constructor(name: string, age: number, isManager: boolean) {
           super(name, age)
           this.isManager = isManager
       }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;doing the same via type aliases look like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// type definition
type Person = {
    name: string
    age: number
}

// type extension
type Employee = Person &amp;amp; {isManager: boolean}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and finally with interface we have:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;interface Person {
    name: string
    age: number
}

interface Employee extends Person {
    isManager: boolean
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The syntax for extension with classes and interfaces looks similar while it is different for type aliases. Extending type aliases makes use of intersection types, which is a topic that is explored in details in &lt;a href=&quot;https://www.geekabyte.io/2021/01/union-and-intersection-types-in.html&quot;&gt;Union and Intersection Types in TypeScrip&lt;/a&gt;t&lt;/p&gt;

&lt;b&gt;Possibility for multiple definition&lt;/b&gt;

&lt;p&gt;Interfaces differ from the other mechanisms in that, the type being named can be spread across multiple definitions.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;//first definition 
interface Employee {
    name: string
}

// second definition
interface Employee {
    age: number
}

// third definition
interface Employee {
    isManager: boolean
}

// Merged Employee type being used
let john: Employee = {
    name: &quot;John Doe&quot;,
    age: 30,
    isManager: true
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;TypeScript will take all the definitions of the interface &lt;i&gt;Employee&lt;/i&gt;, and merges them into one. This is not possible with type aliases nor interfaces as their definition needs to be unique.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2021/05/3-ways-to-name-types-in-typescript.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-6213652815043453000</guid><pubDate>Fri, 21 May 2021 23:06:00 +0000</pubDate><atom:updated>2021-06-01T20:46:10.472+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>How to implement sleep function in JavaScript</title><description>&lt;p&gt;Most popular mainstream languages have a &lt;i&gt;sleep&lt;/i&gt; functionality that allows for the pausing of code execution for a specified amount of time. Not surprising this functionality is often implemented via a function usually named &lt;i&gt;sleep&lt;/i&gt;. For example: &lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// ruby
sleep(time_secs)
// python
import time
time.sleep(time_secs)
// Java
Thread.sleep(time_milli_secs)
// Perl
sleep(time_secs)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;JavaScript does not have a similar sleep function, although it has the &lt;span style=&quot;font-family: courier;&quot;&gt;setTimeout&lt;/span&gt; function which can be used to achieve a similar purpose. The only problem is, using &lt;span style=&quot;font-family: courier;&quot;&gt;setTimeout&lt;/span&gt; is not as convenient as one would like. This is due to the fact that &lt;span style=&quot;font-family: courier;&quot;&gt;setTimeout&lt;/span&gt; is an asynchronous function, hence one would have to continue the execution of the code, in the callback passed to it, after the elapsed time.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;console.log(&quot;Executing code...&quot;); 
setTimeout(() =&amp;gt; { 
console.log(&quot;continue after pause&quot;); 
}, 3000)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is not convenient.&lt;/p&gt;

&lt;p&gt;A more convenient option would be to have something similar to: &lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;console.log(&quot;Executing code...&quot;); 
// sleep for some time
// sleep()
console.log(&quot;continue after pause&quot;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Unfortunately, this does not exist natively in JavaScript. But this is not to say we can&#39;t implement one!&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;

&lt;p&gt;We can implement such a sleep function by combining the capabilities of Promises and Async/Await in JavaScript. For a quick recap of the syntax involved, see &lt;a href=&quot;https://www.geekabyte.io/2021/05/callback-promise-and-asyncawait-by.html&quot;&gt;Callback, Promise and Async/Await by Example in JavaScript.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The implementation of such a sleep function, involves &lt;i&gt;&quot;Promisifying&quot;&lt;/i&gt; the &lt;span style=&quot;font-family: courier;&quot;&gt;setTimeout&lt;/span&gt; function, and then using the Async/Await syntax to provide a synchronous feel to a rather asynchronous function. It looks this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;function sleep(milliseconds) {
    return new Promise(resolve =&amp;gt; {
        setTimeout(() =&amp;gt; {
            resolve({})
        }, milliseconds);
    })
}&lt;/code&gt;&lt;/pre&gt;

In a less verbose syntax this would be:

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;(milliseconds: number) =&gt; new Promise(resolve =&amp;gt; setTimeout(resolve, milliseconds))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Usage would have to be within a function marked as async:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// definition
function sleep(milliseconds) {
    return new Promise(resolve =&amp;gt; {
        setTimeout(() =&amp;gt; {
            resolve({})
        }, milliseconds);
    })
}

//usage
async function doStuff() {
    console.log(&quot;start&quot;)
    await sleep(3000)
    console.log(&quot;continue&quot;)
}

doStuff()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The requirement to put the code in an async function is because, as of now, browsers and NodeJS do not support top-level async functions. Attempting to have the code used in the browser, outside of an async function, would lead to an error similar to this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Attempting to run it in Node, would also lead to an error:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;SyntaxError: await is only valid in async functions and the top level bodies of modules&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;https://deno.land/&quot;&gt;Deno&lt;/a&gt; on the other hand, already supports top-level async functions, hence with Deno, the code can be used right away:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// definition
function sleep(milliseconds) {
    return new Promise(resolve =&amp;gt; {
        setTimeout(() =&amp;gt; {
            resolve({})
        }, milliseconds);
    })
}

//usage
console.log(&quot;start&quot;)
await sleep(3000)
console.log(&quot;continue&quot;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Assuming the above code is in a file named &lt;span style=&quot;font-family: courier;&quot;&gt;script.js&lt;/span&gt; it can be executed using Deno as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;$&amp;gt; deno run script.js 
start
// pause for 3 seconds
continue
&lt;/code&gt;&lt;/pre&gt;

And there you have it: an implementation of a sleep function in JavaScript, which has a synchronous feel to it&#39;s usage. Definitely more convenient than using &lt;span style=&quot;font-family: courier;&quot;&gt;setTimeout&lt;/span&gt; directly.
</description><link>http://www.geekabyte.io/2021/05/how-to-implement-sleep-function-in.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-3669313055292237940</guid><pubDate>Thu, 20 May 2021 19:23:00 +0000</pubDate><atom:updated>2021-05-21T00:21:13.510+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>Callback, Promise and Async/Await by Example in JavaScript </title><description>&lt;p&gt;This post is going to show,&amp;nbsp; by way of code examples, how to take a callback based API, modify it to use Promises and then use the Async/Await syntax. This post won&#39;t go into a detailed explanation of callbacks, promises or the Async/Await syntax. For such a detailed explanation of these concepts please check &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous&quot;&gt;Asynchronous JavaScript&lt;/a&gt;, which is a section of MDN Web Docs, that explains &lt;i&gt;asynchronicity&lt;/i&gt;&amp;nbsp;and how callbacks, promises, and the Async/Await syntax helps with working with asynchronous JavaScript.&lt;/p&gt;

&lt;p&gt;This post is meant for the developer who has somewhat of an understanding of &lt;i&gt;asynchronicity&lt;/i&gt;&amp;nbsp;in JavaScript, but requires a straight to the point code example to serve as a quick syntax reference for how to take a callback based API, update it to use promises and finally use the Async/Await with it.&lt;/p&gt;

&lt;p&gt;For demonstration purposes, we are going to use the &lt;a href=&quot;https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback&quot;&gt;fs.readFile&lt;/a&gt;, which is a callback based API from reading files. We will have a file&amp;nbsp;&lt;span style=&quot;font-family: courier;&quot;&gt;test.txt&lt;/span&gt;&amp;nbsp;that would contain some text, we will then have a file &lt;span style=&quot;font-family: courier;&quot;&gt;script.js&lt;/span&gt; that would open the file, read the contents, and print it to the terminal.&lt;/p&gt;&lt;p&gt;The code will first be implemented using callbacks, it would then be updated to use Promises, and finally, instead of using Promise directly, it will be updated to use Async/Await. &lt;/p&gt;

&lt;p&gt;Let&#39;s get started.&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;p&gt;&lt;/p&gt;

&lt;br /&gt;
&lt;h3&gt;Using Callbacks&lt;/h3&gt;

&lt;p&gt;We first create a directory where we are going to work from, create also the file that will contain our code, and the two files that we would be reading from.&lt;/p&gt;

&lt;p&gt;We first create the two files with contents.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;$ mkdir ~/code
$ touch ~/code/script.js
$ echo &quot;Beam me up, Scotty&quot; &amp;gt; ~/code/test.txt
$ cd ~/code/&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next in the &lt;span style=&quot;font-family: courier;&quot;&gt;script.js&lt;/span&gt; file, we have the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;const fs = require(&quot;fs&quot;)

function readFileCallBack() {

fs.readFile(&quot;./test.txt&quot;, &#39;utf8&#39;,  (err, data) =&amp;gt; {
  if (err) {
    console.error(err)
    return
  }
  
  console.log(data.trim() + &quot; [callback]&quot;)
 })

}

readFileCallBack()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Executing the script by running &lt;span style=&quot;font-family: courier;&quot;&gt;node script.js&lt;/span&gt; should get &quot;&lt;i&gt;Beam me up, Scotty&lt;/i&gt;&quot; printed to the terminal:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;$ node script.js
Beam me up, Scotty [callback]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the callback style, the result of the asynchronous operation is handled by a function passed in to the function performing the asynchronous operation.&lt;/p&gt;

&lt;br /&gt;
&lt;h3&gt;Using Promises&lt;/h3&gt;

&lt;p&gt;Update &lt;span style=&quot;font-family: courier;&quot;&gt;script.js&lt;/span&gt; and add a version of &lt;span style=&quot;font-family: courier;&quot;&gt;readFileCallback&lt;/span&gt; that uses promises. It looks like this:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;function readFilePromise() {
  return new Promise((resolve, reject) =&amp;gt; {
     fs.readFile(&quot;./test.txt&quot;, &#39;utf8&#39;,  (err, data) =&amp;gt; {
     if (err) {
       reject(err)
       return
     }

      resolve(data.trim())
    })
  });
}


readFilePromise()
 .then(data =&amp;gt; console.log(data  + &quot; [promise]&quot;))
 .catch(err =&amp;gt; console.log(err))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Execute the script by running &lt;span style=&quot;font-family: courier;&quot;&gt;node script.js&lt;/span&gt;: &lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;$ node script.js
Beam me up, Scotty [callback]
Beam me up, Scotty [promise]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With promises, the result of the asynchronous operation is handled by a function passed to the &lt;span style=&quot;font-family: courier;&quot;&gt;then&lt;/span&gt; function exposed by the promise object.&lt;/p&gt;

&lt;br /&gt;
&lt;h3&gt;Using Async/Await&lt;/h3&gt;

&lt;p&gt;Update &lt;span style=&quot;font-family: courier;&quot;&gt;script.js&lt;/span&gt; and add a third version that uses the Async/Await syntax. Since Async/Await is a syntax that makes using promises easier, the Async/Await implementation would make use of the &lt;span style=&quot;font-family: courier;&quot;&gt;readFilePromise()&lt;/span&gt; function. It looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;async function readFileAsync() {
  try {
    const data = await readFilePromise()
    console.log(data.trim() + &quot; [async-await]&quot;)
  } catch (err) {
    console.log(err)
  }
}

readFileAsync()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Executing the script by running &lt;span style=&quot;font-family: courier;&quot;&gt;node script.js&lt;/span&gt; will print something similar to this, to the terminal:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;Beam me up, Scotty [callback]
Beam me up, Scotty [promise]
Beam me up, Scotty [async-await]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With async/await, the result of the asynchronous operation is handled as if it was a synchronous operation. The &lt;span style=&quot;font-family: courier;&quot;&gt;await&lt;/span&gt; is responsible for this, while the function in which it is used has to be preceeded with &lt;span style=&quot;font-family: courier;&quot;&gt;async&lt;/span&gt; keyword.&lt;/p&gt;

&lt;p&gt;The complete file with the 3 implementations is presented below:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;const fs = require(&quot;fs&quot;)

// callback
function readFileCallBack() {

fs.readFile(&quot;./test.txt&quot;, &#39;utf8&#39;,  (err, data) =&amp;gt; {
  if (err) {
    console.error(err)
    return
  }
  console.log(data.trim() + &quot; [callback]&quot;)
  
 })

}

readFileCallBack()

// promise
function readFilePromise() {
  return new Promise((resolve, reject) =&amp;gt; {
     fs.readFile(&quot;./test.txt&quot;, &#39;utf8&#39;,  (err, data) =&amp;gt; {
     if (err) {
       reject(err)
       return
     }

      resolve(data.trim())
    })
  });
}


readFilePromise()
 .then(data =&amp;gt; console.log(data  + &quot; [promise]&quot;))
 .catch(err =&amp;gt; console.log(err))


// async/await
async function readFileAsync() {
  try {
    const data = await readFilePromise()
    console.log(data.trim() + &quot; [async-await]&quot;)
  } catch (err) {
    console.log(err)
  }
}

readFileAsync()&lt;/code&gt;&lt;/pre&gt;

&lt;br /&gt;
&lt;h3&gt;Error Handling&lt;/h3&gt;

&lt;p&gt;To illustrate that the error handling in the 3 implementation work as expected, rename the &lt;span style=&quot;font-family: courier;&quot;&gt;test.txt&lt;/span&gt; file and rerun the script:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;
$ mv test.txt test.txt.backup
$ node script.js
[Error: ENOENT: no such file or directory, open &#39;./test.txt&#39;] {
  errno: -2,
  code: &#39;ENOENT&#39;,
  syscall: &#39;open&#39;,
  path: &#39;./test.txt&#39;
}
[Error: ENOENT: no such file or directory, open &#39;./test.txt&#39;] {
  errno: -2,
  code: &#39;ENOENT&#39;,
  syscall: &#39;open&#39;,
  path: &#39;./test.txt&#39;
}
[Error: ENOENT: no such file or directory, open &#39;./test.txt&#39;] {
  errno: -2,
  code: &#39;ENOENT&#39;,
  syscall: &#39;open&#39;,
  path: &#39;./test.txt&#39;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Showing that the error handling code, which is to just print the error to the console, works as expected in the 3 implementations.&lt;/p&gt;


</description><link>http://www.geekabyte.io/2021/05/callback-promise-and-asyncawait-by.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-5047988099667861838</guid><pubDate>Sun, 09 May 2021 07:51:00 +0000</pubDate><atom:updated>2021-05-18T06:49:59.311+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ip-num</category><category domain="http://www.blogger.com/atom/ns#">TypeScript</category><title>ip-num v1.3.2 has been released</title><description>&lt;p&gt;ip-num is A TypeScript/JavaScript library for working with ASN, IPv4, and IPv6 numbers. It provides representations of these internet protocol numbers with the ability to perform various IP related operations like parsing, validating etc, on them.&lt;/p&gt;


&lt;p&gt;A new version of &lt;span style=&quot;font-family: courier;&quot;&gt;ip-num&lt;/span&gt;, &lt;a href=&quot;https://www.npmjs.com/package/ip-num/v/1.3.2&quot;&gt;version 1.3.2&lt;/a&gt; is now available.&lt;/p&gt;

&lt;p&gt;This release contains one new feature and a bug fix.&lt;/p&gt;

&lt;h3&gt;Add method to split range into smaller ranges of certain size&lt;/h3&gt;

&lt;p&gt;In previous versions of &lt;span style=&quot;font-family: courier;&quot;&gt;ip-num&lt;/span&gt;, it was possible to take IP ranges with prefix less than /32 and split them into two. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import {IPv4CidrRange} from &quot;ip-num/IPRange&quot;;
import {IPv4Prefix} from &quot;ip-num/Prefix&quot;;

let ipv4CidrRange = IPv4CidrRange.fromCidr(&quot;192.168.208.0/24&quot;);
let splitRanges: Array&amp;lt;IPv4CidrRange&amp;gt; = ipv4CidrRange.split();

// console logs:
// 192.168.208.0/25
// 192.168.208.128/25

splitRanges.forEach(range =&amp;gt; console.log(range.toCidrString()))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But what if one needs to take an IP range and instead of just splitting into two, there is the requirement to split into a number of ranges with a specified prefix? Well, that is now possible with the addition of &lt;span style=&quot;font-family: courier;&quot;&gt;splitInto&lt;/span&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import {IPv4CidrRange} from &quot;ip-num/IPRange&quot;;
import {IPv4Prefix} from &quot;ip-num/Prefix&quot;;

let ipv4CidrRange = IPv4CidrRange.fromCidr(&quot;192.168.208.0/24&quot;);
let splitRanges: Array&amp;lt;IPv4CidrRange&amp;gt; = 
ipv4CidrRange.splitInto(IPv4Prefix.fromNumber(26));

// console logs:
// 192.168.208.0/26
// 192.168.208.64/26
// 192.168.208.128/26
// 192.168.208.192/26

splitRanges.forEach(range =&amp;gt; console.log(range.toCidrString()))&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;

&lt;h3&gt;RangedSet.isCidrAble() incorrect results&lt;/h3&gt;
&lt;p&gt;Previous versions of ip-num failed to properly report that a string representing a single IP can be represented in the CIDR notation. This has now been fixed:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import {RangedSet} from &quot;ip-num/IPRange&quot;;

let rangedSet= RangedSet.fromRangeString(&quot;1.2.3.4-1.2.3.4&quot;);

// now returns true
console.log(rangedSet.isCidrAble())&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As always, &lt;span style=&quot;font-family: courier;&quot;&gt;ip-num&lt;/span&gt; is just an &lt;i&gt;npm install&lt;/i&gt; or &lt;i&gt;npm upgrade&lt;/i&gt; away.&lt;/p&gt;

&lt;p&gt;Feel free to &lt;a href=&quot;https://github.com/ip-num/ip-num/issues&quot;&gt;open an issue&lt;/a&gt; to discuss a feature or to report a bug.&lt;/p&gt;
</description><link>http://www.geekabyte.io/2021/05/ip-num-v132-has-been-released.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-34374221.post-4919671440907666855</guid><pubDate>Sat, 24 Apr 2021 23:21:00 +0000</pubDate><atom:updated>2021-04-25T08:13:53.319+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">TypeScript</category><title>Mapped Types in Typescript</title><description>This post will explore Mapped Types, another advanced feature of the Typescript type system. It is part of the &lt;a href=&quot;https://www.geekabyte.io/2021/01/introduction-to-advance-types-in.html&quot;&gt;Introduction to Advanced Types in TypeScript&lt;/a&gt; series.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A useful mental model to have when approaching some of the advanced type system features of Typescript is to view them as a mechanism for constructing other types from existing types. This view is spot on when it comes to mapped types as they are a mechanism that Typescript provides by constructing new types by &lt;i&gt;mapping&lt;/i&gt; existing types into new ones.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This post would show how this looks like. It would be as beginner-friendly as possible, but having some knowledge of &lt;a href=&quot;https://www.geekabyte.io/2021/01/introduction-to-generics-in-typescript.html&quot;&gt;Generics&lt;/a&gt;,&amp;nbsp;&lt;a href=&quot;https://www.geekabyte.io/2021/01/union-and-intersection-types-in.html&quot;&gt;Union Types&lt;/a&gt; and &lt;a href=&quot;https://www.geekabyte.io/2021/02/literal-and-template-literal-types.html&quot;&gt;Literal types in Typescript &lt;/a&gt;would be a plus.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To kickstart we take a quick again, at the k&lt;span style=&quot;font-family: courier;&quot;&gt;eyof&lt;/span&gt; Operator, as it is essential to the workings of Mapped Types.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;

&lt;h3 style=&quot;text-align: left;&quot;&gt;keyof Operator&lt;/h3&gt;
&lt;br /&gt;
&lt;div&gt;The key idea of Mapped Types is to create a new type by mapping (read modifying) the properties of existing types. And how do we get access to these properties? We use the &lt;span style=&quot;font-family: courier;&quot;&gt;keyof&lt;/span&gt; operator. As explained in &lt;a href=&quot;https://www.geekabyte.io/2021/02/introduction-to-index-types-in.html&quot;&gt;Introduction to Index Types in Typescript&lt;/a&gt;, The&amp;nbsp;&lt;span style=&quot;font-family: courier;&quot;&gt;keyof&lt;/span&gt;&amp;nbsp;type operator is an operator that allows the retrieval of all the indexes (read properties) of a type as a union type. The individual components of the retrieved union types are the literal types that represent the properties of that type.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This can be illustrated as follows. Given the following type definition:&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Employee = {
name: string
employedOn: Date
age: string
role: {
  title: string
  salary: number
  isManagement: boolean
 }
}
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;The properties can be extracted as a union type as follows:

&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Properties = keyof Employee&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;We can demonstrate that &lt;span style=&quot;font-family: courier;&quot;&gt;Properties&lt;/span&gt; is indeed a union type that consists of literal types based off the properties of &lt;span style=&quot;font-family: courier;&quot;&gt;Employee:&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;var value: Properties = &quot;name&quot; // compiles
var value: Properties = &quot;employedOn&quot; // compiles
var value: Properties = &quot;age&quot; // compiles
var value: Properties = &quot;role&quot; // compiles
var value: Properties = &quot;gender&quot; // does not compiles&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;All the variable definition compiles except the one where &quot;&lt;span style=&quot;font-family: courier;&quot;&gt;gender&lt;/span&gt;&quot; is to be assigned to a variable of &lt;span style=&quot;font-family: courier;&quot;&gt;Properties&lt;/span&gt;. And the reason why this does not compile is due to the fact that &quot;&lt;span style=&quot;font-family: courier;&quot;&gt;gender&lt;/span&gt;&quot; is not part of the properties of the &lt;span style=&quot;font-family: courier;&quot;&gt;Employee&lt;/span&gt; type.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So in summary, the&amp;nbsp;&lt;span style=&quot;font-family: courier;&quot;&gt;keyof&lt;/span&gt; operator allows us to get access to the properties of a type as a union type.&lt;/div&gt;

&lt;br /&gt;
&lt;h3&gt;A Mapped Type&lt;/h3&gt;
&lt;br /&gt;

A mapped type is then a type that is created by accessing the properties of another type, using the &lt;span style=&quot;font-family: courier;&quot;&gt;keyof&lt;/span&gt; operator, and modifying the extracted properties in some sort of way to create another type.&amp;nbsp; As an example, given a type definition as follows:

&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Person = {
    age: string | number
    height: string | number
}&lt;/code&gt;&lt;/pre&gt;


&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This type can be turned into another type where the properties are mapped from type&amp;nbsp;&lt;span style=&quot;font-family: courier;&quot;&gt;string | number&lt;/span&gt; to &lt;span style=&quot;font-family: courier;&quot;&gt;string.&amp;nbsp;&lt;/span&gt;To achieve that, a mapped type can be defined as such:&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type ToStringProps&amp;lt;T&amp;gt; = {
    [P in keyof T]: string
}&lt;/code&gt;&lt;/pre&gt;


&lt;div&gt;&lt;br /&gt;Which can then be used on the &lt;span style=&quot;font-family: courier;&quot;&gt;Person&lt;/span&gt; type as follows:&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type StringPerson = ToStringProps&amp;lt;Person&amp;gt;

var person: StringPerson = {
    age: &quot;10&quot;,
    height: &quot;6&quot;
}&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;The &lt;span style=&quot;font-family: courier;&quot;&gt;StringPerson&lt;/span&gt; type thus created can only have properties of type &lt;span style=&quot;font-family: courier;&quot;&gt;string&lt;/span&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The Mapped type above is &lt;span style=&quot;font-family: courier;&quot;&gt;ToStringProps&amp;lt;T&amp;gt;&amp;nbsp;&lt;/span&gt;and in this case,&amp;nbsp; it is used to modify the return type. But it is not only the return type of properties that can be modified using Mapped Types, property names and property identifiers (&lt;i&gt;mutability&lt;/i&gt; and &lt;i&gt;optionality&lt;/i&gt; identifier) can also be modified. The next example shows how these looks.&lt;/div&gt;

&lt;br /&gt;
&lt;h3&gt;Modifying Identifiers using Mapped Types&lt;/h3&gt;
&lt;br /&gt;
&lt;div&gt;Two identifiers can be modified using Mapped types. These are mutability, which is implemented via the &lt;i&gt;readonly&lt;/i&gt; keyword, and optionality which is implemented via the &lt;i&gt;?&lt;/i&gt; symbol. The modification that can be achieved via mapped types involves adding or removing these identifiers. To add the identifier the Mapped type definition makes use of the + symbol, while to remove the target identifier, the - symbol is used.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To illustrate, a Mapped type that takes a type and produced an immutable version of it would look like this:&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Immutable&amp;lt;T&amp;gt; = {
    +readonly [P in keyof T]: T[P]
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;While a mapped type that takes a type and produced a mutable version would look like this:&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Mmutable&amp;lt;T&amp;gt; = {
    -readonly [P in keyof T]: T[P]
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;Note, when no symbol is used, then addition is assumed. Hence the Immutable mapped type can also be defined like this:&lt;/div&gt;&lt;div&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Immutable&amp;lt;T&amp;gt; = {
    readonly [P in keyof T]: T[P]
}&lt;/code&gt;&lt;/pre&gt;
  
The above examples show how the &lt;i&gt;readonly&lt;/i&gt; which is responsible for mutability can be mapped. On the other hand, to illustrate how a mapped type can be used to produce another type with all of its properties turned optional, we have:
  
&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Optional&amp;lt;T&amp;gt; = {
    [P in keyof T]+? : T[P]
}

&lt;/code&gt;&lt;/pre&gt;
  
While a mapped type that takes a type and produced another type where all its properties would have to be specified will look like this:
  
&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type NonOptional&amp;lt;T&amp;gt; = {
    [P in keyof T]-? : T[P]
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Again, note, when no symbol is used, then addition is assumed. Hence the Optional mapped type can also be defined like this:
  
&lt;br /&gt;&lt;br /&gt;&lt;pre style=&quot;font-family: Times; white-space: normal;&quot;&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Optional&amp;lt;T&amp;gt; = {
   [P in keyof T]? : T[P]
}&lt;/code&gt;&lt;/pre&gt;
  
&lt;br /&gt;  
&lt;h3&gt;Modifying Property Name using Mapped Types&lt;/h3&gt;
&lt;br /&gt; 
Mapped type can also be used to produce a new type by modifying the property names of an existing type. This is achieved by using the as keyword, in combination with Template literals. For example, a mapped type that updates the given type by prepending &quot;_&quot; to the property names will look like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type UnderlineProp&amp;lt;T&amp;gt; = {
    [P in keyof T as `_${string &amp;amp; P}`]: T[P]
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;which can then be used as follows:
  
&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type Person = {
    name: string
    age: number
}

type _Person = UnderlineProp&amp;lt;Person&amp;gt;

var _person: _Person = {
    _name: &quot;John&quot;,
    _age: 20
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&amp;nbsp;In the above example &lt;span style=&quot;font-family: courier;&quot;&gt;_Person&lt;/span&gt; is a type produced from &lt;span style=&quot;font-family: courier;&quot;&gt;Person&lt;/span&gt; type, using the mapped type definition of &lt;span style=&quot;font-family: courier;&quot;&gt;UnderlineProp&lt;/span&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Mapped types are quite powerful and allow for sophisticated manipulation of types in Typescript, especially when used with other features of the type system. Above, it is used together with Template literals. It is also possible to make use mapped types together with &lt;a href=&quot;https://www.geekabyte.io/2021/04/conditional-types-in-typescript.html&quot;&gt;Conditional types&lt;/a&gt; in determining the type of property to be updated.&lt;/div&gt;
&lt;hr /&gt;
&lt;div&gt;This post is part of a series. See &lt;a href=&quot;https://www.geekabyte.io/2021/01/introduction-to-advance-types-in.html&quot;&gt;Introduction to Advance Types in TypeScript&lt;/a&gt; for more posts in the series&lt;/div&gt;</description><link>http://www.geekabyte.io/2021/04/mapped-types-in-typescript.html</link><author>noreply@blogger.com (dade)</author><thr:total>0</thr:total></item></channel></rss>