<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Romualds Bahvalovs on Medium]]></title>
        <description><![CDATA[Stories by Romualds Bahvalovs on Medium]]></description>
        <link>https://medium.com/@romualds-bahvalovs1?source=rss-43139b0c815c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gQs75ktpCjlGblzk.jpg</url>
            <title>Stories by Romualds Bahvalovs on Medium</title>
            <link>https://medium.com/@romualds-bahvalovs1?source=rss-43139b0c815c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:08:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romualds-bahvalovs1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Кошелёк LEO инструкция]]></title>
            <link>https://romualds-bahvalovs1.medium.com/%D0%BA%D0%BE%D1%88%D0%B5%D0%BB%D1%91%D0%BA-leo-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%86%D0%B8%D1%8F-e9284b6b7784?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9284b6b7784</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 18:59:23 GMT</pubDate>
            <atom:updated>2023-04-22T18:59:23.315Z</atom:updated>
            <content:encoded><![CDATA[<p>Привет! Сегодня я расскажу тебе про функционал кошелька Aleo. В данной статье я отвечу на такие вопросы как: «Как создать кошелек Aleo?», «Как отправить и получить токены?», «Какой функционал доступен в кошельке?». Будет приведена подробная инструкция со скриншотами. Если вы предпочитаете видео-формат, то можете посмотреть видео на моём канале по этой теме. Ссылка на видео будет приведена в конце статьи, как дополнительные материалы. Приступаем!</p><p><strong>Введение.</strong></p><p>Создание кошелька является значимым этапом в жизни проекта. Нам, поскольку мы являемся простыми пользователями, интересно прикоснуться к понятному графическому интерфейсу. Команда Aleo уже разработала много инструментов, один язык программирования Leo — это уже колоссальная работа. Для него даже есть отдельное IDE программа — это Aleo Studio. Кстати, если Вам интересно программирование приватных и децентрализованных приложений, то Вы можете посмотреть мой видео курс по языку программирования Leo. Ссылка также будет в дополнительных материалах к этому видео. Используя кошелек Leo Wallet, Вы можете хранить, передавать и получать токены Leo. Функционал схож с другими кошельками, такими как MetaMask (используется для хранения токенов в сети eth, bnb и так далее) или Martian Wallet (используется для хранения токенов в сети Aptos и Sui). Далее в статье я подробно расскажу про функционал.</p><p><strong>Загрузка расширения.</strong></p><p>Установить кошелек Вы можете в свой браузер Google Chrome. Для этого необходимо перейти по ссылке и установить расширение.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFSjAkV9h3ZPQPFcnz2-2w.png" /></figure><p><a href="https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm"></a></p><p>Никаких дополнительных настроек здесь проводить не требуется. Всё предельно просто.</p><p>После загрузки необходимых данных на Ваш компьютер и установки расширения, Вы сможете открыть его. Вы увидите следующую картину:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ctuRl65tBACr9EHVv49lg.png" /></figure><p>Вы можете или импортировать уже существующий кошелек или создать новый. Поскольку мы только открываем для себя Leo Wallet, то мы создаем новый кошелек.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lx8xzI8Y8JkNJMNbtS1iUQ.png" /></figure><p>Нам нужно записать данную seed фразу. Если нам потребуется восстановить кошелек или открыть на новом компьютере, то именно она нам и понадобится. При восстановлении, мы бы выбрали кнопку «Импорт существующего кошелька».</p><p>Желательно записать эту seed фразу на бумажный носитель и хранить в безопасном месте. В крайнем случае Вы можете создать зашифрованный текстовый документ и хранить эту фразу там. Она открывает доступ к владению над Вашим аккаунтом, так что позаботьтесь о ее безопасности.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekQvJNSZgpjDm03yj3MuHg.png" /></figure><p>Далее нам требуется ввести некоторые слова из этой фразы чтобы убедиться, что мы записали всё верно.</p><p>Следующим шагом нам необходимо создать пароль, который мы будем использовать каждый раз для того, чтобы зайти на кошелек. Он достаточно легко сбрасывается, но использовать его придется очень часто.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oij8jici15vVG2EfnO6smQ.png" /></figure><p>Также нужно будет поставить галочку на «принять условия» и нажать «следующий».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4tGpo8eZBsKJrz6IKAq7g.png" /></figure><p>Итак, вы вошли в свой аккаунт. Чтобы получить токены, вы можете нажать кнопку «получить». Вы получите адрес своего кошелька Aleo. Его вы можете отослать человеку, который будет отправлять вам токены.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB61wTseTMyhrZsBBZxceA.png" /></figure><p>Чтобы отправить токены Leo вы можете нажать кнопку «отправить». Ввести адрес получателя и количество токенов.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwKdcMG_E2ABMHttt_asKA.png" /></figure><p>Это были основные функции кошелька. Вы можете увидеть дополнительные возможности, если откроете настройки.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN0H4rE8EkiCAdJg-AdERw.png" /></figure><p>Например, здесь вы можете узнать свой ключ просмотра и приватный ключ. Кнопка удаления учетной записи есть, но использовать его невозможно.</p><p><strong>Материалы:</strong></p><p>Мой youtube канал: <a href="https://www.youtube.com/@romacll/videos">https://www.youtube.com/@romacll/videos</a></p><p>Видео про кошелек: <a href="https://youtu.be/GiFfBebsEYk">https://youtu.be/GiFfBebsEYk</a></p><p>Плейлист про язык программирования Leo: <a href="https://www.youtube.com/playlist?list=PLsvDEBW3znFLuMxMyN7VyUIIj343H1_T2">https://www.youtube.com/playlist?list=PLsvDEBW3znFLuMxMyN7VyUIIj343H1_T2</a></p><p>Ссылка на расширение: <a href="https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm/related">https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm/related</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9284b6b7784" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aleo Wallet]]></title>
            <link>https://romualds-bahvalovs1.medium.com/aleo-wallet-d5cc93f945f9?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5cc93f945f9</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 16:01:12 GMT</pubDate>
            <atom:updated>2023-04-21T16:01:12.659Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi! Today I will tell you about the functionality of the Aleo Wallet. In this article I will answer such questions as: “How to create an Aleo wallet?”, “How to send and receive tokens?”, “What functionality is available in the wallet?”. There will be a detailed instruction with screenshots. Here we go!</p><p><strong>Introduction.</strong></p><p>Creating a wallet is a significant step in the life of a project. We, since we are simple users, are interested in “touching” an understandable graphical interface. Aleo team has already developed a lot of tools, one programming language Leo is already a colossal work. There’s even a special IDE program for it — Aleo Studio. By the way, if you are interested in programming private and decentralized applications, you can watch my video course on Leo programming language. The link will be in the additional materials to this video. Using Leo Wallet, you can hold, transfer and receive Leo tokens. The functionality is similar to other wallets such as MetaMask (used to hold tokens in eth, bnb and so etc) or Martian Wallet (used to hold tokens in Aptos and Sui networks). Later in the article I will describe the functionality in detail.</p><p><strong>Installing the extension.</strong></p><p>You can install the wallet in your browser Google Chrome. To do this, click on the link and install the extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91mfpUPexY-mlrq74hP17g.png" /></figure><p><a href="https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm">https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm</a></p><p>No additional settings are required here. Everything is very simple.</p><p>After downloading the necessary data to your computer and installing the extension, you can open it. You will see the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ck2ox8t1FRqrrAY0Bo7qZQ.png" /></figure><p>You can either import an already existing wallet or create a new one. Since we are just discovering Leo Wallet, we are creating a new wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Mb9GsEGiJzTRs2pBOqm0A.png" /></figure><p>We need to write down this phrase. If we need to recover the wallet or open it on a new computer, that’s what we’ll need. When recovering, we would choose the “Import Existing Wallet” button.</p><p>It is desirable to write down this phrase on a paper carrier and keep it in a safe place. As a last resort, you can create an encrypted text document and store the phrase there. It gives you access to the ownership of your account, so take care of its security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDl9EIxlb7A3qaswbXlKaw.png" /></figure><p>Next, we need to enter some words from this phrase to make sure we got it right.</p><p>The next step is to create a password, which we will use every time we log into the wallet. It is easy enough to reset, but we will have to use it very often.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4RYEIQ6ryk_8EGoaD7StA.png" /></figure><p>You will also need to check the “accept terms and conditions” and click “next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKI2XGPYawyGY7UmFZZzLg.png" /></figure><p>So, you are logged into your account. To get the tokens, you can click the “get” button. You will get the address of your Aleo wallet. You can send it to the person who will send you the tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_81q7IexyUXdHXR3g2ItXg.png" /></figure><p>To send Leo tokens, you can click the “send” button. Enter the recipient’s address and the number of tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWFT2flngQptUYX4EUOBdA.png" /></figure><p>These were the basic features of the wallet. You can see additional features if you open the settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0_ovrmTeNUY8-Ry9qyMOg.png" /></figure><p>For example, here you can find out your view key and private key. There is a delete account button, but you cannot use it.</p><p><strong>Materials:</strong></p><p>My youtube channel: <a href="https://www.youtube.com/@romacll/videos">https://www.youtube.com/@romacll/videos</a></p><p>Playlist about Leo programming language: <a href="https://www.youtube.com/playlist?list=PLsvDEBW3znFLuMxMyN7VyUIIj343H1_T2">https://www.youtube.com/playlist?list=PLsvDEBW3znFLuMxMyN7VyUIIj343H1_T2</a></p><p>Extension link: <a href="https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm/related">https://chrome.google.com/webstore/detail/leo-wallet/nebnhfamliijlghikdgcigoebonmoibm/related</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5cc93f945f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Развертывание приложений в блокчейне Aleo.]]></title>
            <link>https://romualds-bahvalovs1.medium.com/%D1%80%D0%B0%D0%B7%D0%B2%D0%B5%D1%80%D1%82%D1%8B%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D0%B2-%D0%B1%D0%BB%D0%BE%D0%BA%D1%87%D0%B5%D0%B9%D0%BD%D0%B5-aleo-1915cfce297?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1915cfce297</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 14:41:14 GMT</pubDate>
            <atom:updated>2023-03-11T14:41:14.432Z</atom:updated>
            <content:encoded><![CDATA[<p>Привет! В данной статье я подробно расскажу тебе, как запустить приложение в Aleo. Данная статья есть в видео-формате, ссылку приложу в конце статьи. Статья будет состоять из двух разделов: подготовка к запуску и настройка сервера.</p><p>Сразу возникает вопрос, для чего нужен сервер? Я перепробовал множество вариантов по установке, но на Windows лично у меня не получилось установить SnarkOS. Дошло до того, что я создал виртуальную машину на Ubuntu, но и там не достиг успеха. Ниже я покажу тебе, как у меня получилось развернуть приложение.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3sLdTB7rsJMRIvS9uXhWQ.png" /></figure><p><strong>Подготовка.</strong></p><p>Следует начать с генерации аккаунта Aleo. Для этого требуется перейти на сайт <a href="https://aleo.tools/">https://aleo.tools/</a> и нажать кнопку Generate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6Bb_KcoLHxDX-Tf5nb-ZA.png" /></figure><p>Эти данные следует сохранить, можете создать отдельный текстовый файл в блокноте.</p><p>Следующий шаг — получить по этому адресу токены от бота. Для этого мы переходим в Twittet</p><p>twitter.com/AleoFaucet</p><p>Здесь мы пишем твит следующего формата, отметив данный аккаунт. У тебя получится примерно такое сообщение.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*D0vL9NS8RsPrWqNbXZFq6w.png" /></figure><p>Спустя некоторое время (от нескольких минут до нескольких часов ты получишь ответ от бота).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*tDMjG_JzRH5xLr4pGAH_SA.png" /></figure><p>Далее нам надобится ссылка, которую нам прислал данный бот. Чтобы было удобнее прочитать данные по этой ссылке, мы скачиваем плагин: <a href="https://chrome.google.com/webstore/detail/json-beautifier-editor/lpopeocbeepakdnipejhlpcmifheolpl">https://chrome.google.com/webstore/detail/json-beautifier-editor/lpopeocbeepakdnipejhlpcmifheolpl</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xMY1s41bj18aVahLFKSxw.png" /></figure><p>Теперь нам нужно арендовать сервер. Я использую данный сервис: <a href="https://www.hetzner.com/">https://www.hetzner.com/</a> . Нам нужно арендовать сервер с конфигурацией CPX31 или выше. Это обойдется нам примерно в 16 евро в месяц.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7Zs8-SMDZDwnyusVCY14Q.png" /></figure><p>Для того чтобы подключиться к серверу, нам потребуется программа, которую ты можешь скачать по этой ссылке: <a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html">https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYrXZ9WVufWcbC7RP0P7fA.png" /></figure><p>Я установил себе версию 64-bit x86. После загрузки мы открываем данный файл и устанавливаем программу с настройками по умолчанию.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*i8Krj89yvzAM1vPj6eMr-w.png" /></figure><p>В программу мы вводим адрес сервера, который мы получили в письме. В поле Saved Sessions мы вводим любое название и нажимаем кнопку Save.</p><p>Теперь для того, чтобы подключиться к серверу мы дважды кликаем по названию сохраненной сессии.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*uOsfnPdDkZqzQbLHFSep9Q.png" /></figure><p>Далее мы авторизуемся по данным от сервера и вводим новый пароль.</p><p><em>Для того чтобы вставить скопированный текст в терминал, нам нужно нажать правую кнопку мыши.</em></p><p><strong>Настройка сервера.</strong></p><p>Теперь мы вводим по очереди команды в терминал.</p><p><em>screen -S aleo</em></p><p>*если в процессе установки Вас выбросит с сервера, то вы можете вернуться командой screen -R aleo</p><p>Обновляемся:</p><p>sudo apt update &amp;&amp; sudo apt upgrade -y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*qBNiB0ZnvhO7JlaeWgoAWg.png" /></figure><p>Устанавливаем Rust:</p><p>curl — proto ‘=https’ — tlsv1.2 -sSf <a href="https://sh.rustup.rs/">https://sh.rustup.rs</a> | sh</p><p>apt install cargo -y</p><p>sudo apt-get install pkg-config libssl-dev -y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*7BI_lciSEVMmjbG87ONo7w.png" /></figure><p>Устанавливаем Leo:</p><p>git clone <a href="https://github.com/AleoHQ/leo">https://github.com/AleoHQ/leo</a></p><p>cd leo</p><p>cargo install — path .</p><p>cd</p><p>export PATH=/root/.cargo/bin:$PATH</p><p>Проверяем установилось ли “Leo”:</p><p>leo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*0-g2qwx0xsLOSp3pDvCTLA.png" /></figure><p>Если ты видишь такой текст после ввода данной команды, то всё установилось корректно.</p><p>Устанавливаем snarkOS:</p><p>git clone <a href="https://github.com/AleoHQ/snarkOS.git">https://github.com/AleoHQ/snarkOS.git</a> — depth 1</p><p>cd snarkOS</p><p>./build_ubuntu.sh</p><p>cd</p><p>Проверяем установилось ли “snarkOS”:</p><p>snarkos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*pNavITsLjgUxT4Xv9N0LAA.png" /></figure><p>Если ты видишь такой текст после ввода данной команды, то всё установилось корректно.</p><p>Создаем папку для тестового приложения и переходим в нее:</p><p>mkdir demo_deploy_Leo_app &amp;&amp; cd demo_deploy_Leo_app</p><p>WALLETADDRESS=”aleo1xxxxxxx”</p><p><em>* “aleo1xxxxxxx” заменяем на свой адрес</em></p><p>APPNAME=helloworld_”${WALLETADDRESS:4:6}”</p><p>leo new “${APPNAME}”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*qlfuBzis58LTSBWj95KQIA.png" /></figure><p>Запускаем приложение:</p><p>cd “${APPNAME}” &amp;&amp; leo run &amp;&amp; cd –</p><p>Сохраняем путь приложения:</p><p>PATHTOAPP=$(realpath -q $APPNAME)</p><p>Переходим к пути Вашего приложения:</p><p>cd $PATHTOAPP &amp;&amp; cd ..</p><p>PRIVATEKEY=”APrivateKeyXXXXX”</p><p><em>* “APrivateKeyXXXXX” заменяем на свой PrivateKey</em></p><p>Далее нам требуется та ссылка от бота, мы по ней переходим и ищем следующее значение.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8dDfQKZx6yg_9FlrQ38PQ.png" /></figure><p>Вводим это значение на сайте <a href="https://aleo.tools/">https://aleo.tools/</a> и вставляем её в команду.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0njwoVUbtUlb1uxcHVEUlQ.png" /></figure><p>RECORD=”{ owner: aleo1xxxxx.private, gates: xxxxx.private, _nonce: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxgroup.public }”</p><p>Разворачиваем приложение:</p><p>snarkos developer deploy “${APPNAME}.aleo” — private-key “${PRIVATEKEY}” — query “<a href="https://vm.aleo.org/api">https://vm.aleo.org/api</a>&quot; — path “./${APPNAME}/build/” — broadcast “<a href="https://vm.aleo.org/api/testnet3/transaction/broadcast">https://vm.aleo.org/api/testnet3/transaction/broadcast</a>&quot; — fee 600000 — record “${RECORD}”</p><p>И получаем следующий результат:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*dNYPNeEYit6VTauU3Fehwg.png" /></figure><p>Приложение успешно развернуто.</p><p>Ссылка на 1 часть видео: <a href="https://youtu.be/D1uiup0jGsM">https://youtu.be/D1uiup0jGsM</a></p><p>Ссылка на 2 часть видео: <a href="https://youtu.be/qGxgyF3DN84">https://youtu.be/qGxgyF3DN84</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1915cfce297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Как работает технология ZKP.]]></title>
            <link>https://romualds-bahvalovs1.medium.com/%D0%BA%D0%B0%D0%BA-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82-%D1%82%D0%B5%D1%85%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D0%B8%D1%8F-zkp-aa1b67783378?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1b67783378</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 20:34:52 GMT</pubDate>
            <atom:updated>2023-02-28T20:34:52.595Z</atom:updated>
            <content:encoded><![CDATA[<p>Всем привет! Сегодня мы поговорим про технологию zero-knowledge proof (доказательство с нулевым знанием). Эта тема очень популярна сейчас, поэтому я решил рассказать вам о ней в данной статье. Если вы предпочитаете видео-формат, вы можете посмотреть мое видео на эту тему по ссылке: <a href="https://youtu.be/Oyj-tr0Z1lQ">https://youtu.be/Oyj-tr0Z1lQ</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*UiU0AaVFdMMf7zY4.png" /></figure><p><strong>Что же такое Zero-knowledge proof?</strong></p><p>Доказательство с нулевым знанием — это криптографический протокол, в котором одна сторона (проверяющий) доказывает другой стороне (верификатору), что что-то истинно, не раскрывая, как это истинно. Эта технология используется в таких проектах как Zcash и Aleo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*sYJ0imwkLb7pz9xb.png" /></figure><p>Кстати, если вы не смотрели мой видеокурс про Aleo, то ссылку я предоставлю в конце статьи.</p><p>Данная технология впервые была предложена исследователями из Массачусетского технологического института в 1985 году. Статья называлась «Сложность знаний интерактивных доказательных систем».</p><p>Так что это не новая разработка, но она стала реализуема только в наше время.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*Wp7r4vxy3TM_NEuu.png" /></figure><p><strong>Как работает данная технология?</strong></p><p>Представьте, что вы находитесь в комнате с человеком, которому завязали глаза. На столе перед вами лежат два шарика — белый и черный. Вам необходимо доказать второму человеку (верификатору), что шарики действительно разных цветов, при этом не раскрывая каких именно. Для этого вы должны попросить его спрятать оба шарика под стол.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_w3Jso3M9Pqg5xpq.png" /></figure><p>После этого попросите достать только один, чтобы вы могли его увидеть. Далее шарик снова прячется и в следующий раз верификатор снова может показать либо белый, либо черный. Однако вы сможете доказать утверждение, поскольку точно знаете, менял ли он их под столом.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*rquB3DMnk5aQxuKd.png" /></figure><p>Тем не менее полностью верификатор в истинности факта не будет уверен, ведь могли иметь место удача или обман. Эта проблема решается путем повторения эксперимента какое-то количество раз. С каждым раундом шанс случайно оказаться правым будет уменьшаться вдвое: после пяти повторений вероятность обмана составит 1 к 32, после 10 раундов — 1 к 1024, а после 20 раундов — примерно 1 к 1 000 000. Благодаря повторениям можно добиться желаемого уровня надежности доказательства, однако абсолютной уверенности достичь при этом невозможно.</p><p><strong>Для чего используют доказательство с нулевым знанием?</strong></p><p>Одним из очевидных применений доказательства с нулевым знанием в криптовалютах можно назвать проверку наличия у пользователя средств для транзакции, при этом не раскрывая участникам сети, кто этот пользователь и сколько денег у него на счету.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*FDlPsWZxwzcpld65.png" /></figure><p>Корпорации собирают большое количество информации о каждом из нас: личные данные, привычки и желания. Используя эти данные, они продают рекламу и эффективнее удерживают наше внимание. Из этой ситуации есть лишь один выход — удалить аккаунты. Нет другой возможности сохранить ваши данные в тайне. Но, что, если вы хотите, например, взять кредит? Вы вынуждены дать банку точную информацию о Ваших доходах. Используя технологию ZKP, вы могли бы предоставить банку информацию, что Ваш доход больше определенной суммы.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*2FRRCYNGpMR4l9pQ.png" /></figure><p>Важно соблюдать одно условие. Этот диапазон должен быть значительным, иначе это будет не иметь смысла. Подобные методы могли бы помочь использовать финансовому миру технологию блокчейн. Но в данный момент это сложно из-за отсутствия законодательной возможности сделать это.</p><p><strong>Какие существуют виды доказательств с нулевым разглашением?</strong></p><p>Существует 2 вида доказательств: <em>интерактивный </em>и <em>неинтерактивный</em>. В примере с мячами использовался интерактивный вид доказательств. Так как верификатор самостоятельно опрашивает доказывающего в режиме реального времени. У этого способа есть один большой недостаток это ограниченная пропускная способность. Мы доказали одному человеку, что мячи разного цвета, но если мы хотим доказать это еще одному человеку, то мы должны снова проделать все эти действия.</p><p>Другая форма это <em>неинтерактивные</em> доказательства. Используя этот вариант, мы можем предоставить доказательство, которое каждый может проверить самостоятельно.</p><p>Как вы знаете, в сети биткоин видны все транзакции.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*eRAgOhIbDp9fytnS.png" /></figure><p>Таким образом, можно узнать, сколько каждый пользователь имеет монет и куда он тратит их. Как минимум, это небезопасно. Есть проекты, которые используют <em>неинтерактивные</em> доказательства с нулевым знанием чтобы защитить ваши транзакции.</p><p>Например, это реализовано в проекте Aleo. Никто не увидит сколько монет и кому вы перевели.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ECwdHkOft1w3R2X7.png" /></figure><p>Для блокчейна мы должны использовать <em>неинтерактивные</em> доказательства, так как доказательства должны быть проверены каждой нодой в сети. Именно так блокчейн достигает консенсуса. Было бы слишком трудоемко доказывать наши транзакции каждому узлу сети.</p><p>Помимо множества преимуществ, технология имеет некоторые недостатки. Первое, технология не может на 100% гарантировать правильность доказательства. Мы можем лишь снизить вероятность ошибки, увеличив количество проверок. Таким образом, можно бесконечно снизить вероятность того, что кто-то подделает доказательство. Второе, алгоритм требует большого количества вычислений, что создает дополнительные сложности. Например, раньше невозможно было запускать алгоритм на слабых устройствах. Сейчас разработчики значительно продвинулись в решении этой проблемы.</p><p><strong>Реализация технологии ZKP в криптопроектах.</strong></p><p>Я расскажу об этом на примере моего любимого проекта — Aleo. Aleo позволяет создавать приватные приложения, используя технологию ZKP. Вы можете перейти на сайт Aleo.org и узнать все детали работы проекта.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*XmEL5EEawVHV-IsW.png" /></figure><p>Я говорил ранее, что для работы с ZKP требуется много вычислений. Разработчики оптимизировали этот процесс, что позволяет достаточно комфортно использовать данную технологию. Большим преимуществом является то, что команда Aleo создала язык программирования Leo и IDE под названием Aleo Studio, которые позволяют максимально упростить процесс создания приватного приложения.</p><p>До сих пор пользователям приходилось выбирать одно из двух: конфиденциальность или программируемость. Например, Zcash предоставляет пользователям полную конфиденциальность, но ограниченную программируемость. Ethereum обеспечивает мощную программируемость, но ограниченную конфиденциальность.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*sC4pVCGaDoWMKVPF.png" /></figure><p>Aleo использует криптографию нулевых знаний для достижения как конфиденциальности, так и программируемости. Как и Zcash, эта система дает нам сильные гарантии конфиденциальности, поскольку транзакции содержат только доказательство, а не входные данные, которые его генерируют. И как Ethereum, ZEXE может поддерживать смарт-контракты, которые позволяют пользователям взаимодействовать или передавать ценность заранее определенным образом.</p><p><strong>Как перевести токен, используя технологию ZKP?</strong></p><p>Для этого мы можем использовать децентрализованную биржу — DEX. DEX — это децентрализованное приложение, которое позволяет пользователям покупать или продавать токены на цепочке без необходимости искать конкретного покупателя или продавца.</p><p>Допустим, вы хотите обменять токен A на токен B на DEX, основанном на Aleo. Сначала вам нужно будет доказать DEX, что у вас есть достаточное количество токена А для совершения сделки. Но поскольку эту информацию можно показать с помощью доказательства нулевого знания, это не означает раскрытия баланса вашего кошелька или истории торговли. Вместо этого вы можете сослаться на доказательство на цепочке предыдущей транзакции, чтобы показать, что у вас есть достаточный баланс для совершения сделки.</p><p>Когда вы совершаете сделку на DEX в Aleo, вы рассчитываете обновленные балансы счетов вне цепочки на основе обменного курса. Эта сделка завершается передачей в сеть Aleo доказательства нулевого знания в качестве транзакции, что указывает на то, что действие произошло. Само по себе доказательство не содержит никакой информации о том, что это было за действие, на какой бирже оно было выполнено или кто в нем участвовал.</p><p>Ссылка на мой видео-курс про Aleo: <a href="https://youtube.com/playlist?list=PLsvDEBW3znFLVfqESTNaENAgnyA362PVe">https://youtube.com/playlist?list=PLsvDEBW3znFLVfqESTNaENAgnyA362PVe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1b67783378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How ZKP technology works.]]></title>
            <link>https://romualds-bahvalovs1.medium.com/how-zkp-technology-works-c3d8b38dfb5d?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d8b38dfb5d</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 20:21:16 GMT</pubDate>
            <atom:updated>2023-02-26T20:21:16.963Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Today we are going to talk about zero-knowledge proof technology. This topic is very popular now, so I decided to tell you about it in this article. If you prefer video format, you can watch my video on this topic at the link: <a href="https://youtu.be/Oyj-tr0Z1lQ">https://youtu.be/Oyj-tr0Z1lQ</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gR6GMCv0Yp7KwTA4DOFJQ.png" /></figure><p><strong>What is a Zero-knowledge proof?</strong></p><p>Zero-knowledge proof is a cryptographic protocol in which one party (the verifier) proves to the other party (the verifier) that something is true without revealing how it is true. This technology is used in projects like Zcash and Aleo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUwCYK9ofl2Ybvx1avsCdA.png" /></figure><p>By the way, if you haven’t seen my video course about Aleo, I’ll provide the link at the end of the article.</p><p>This technology was first proposed by scientists at the Massachusetts Institute of Technology in 1985. The article was called «The knowledge complexity of interactive proof-systems». So it is not a new development, but it has only become realizable in our time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*0gO4TFENdluH6hPp4KyltA.png" /></figure><p><strong>How does this technology work?</strong></p><p>Imagine that you are in a room with a person who is blindfolded. There are two balls on the table in front of you, one white and one black. You need to prove to the second person (the verifier) that the balls are really different colors, without revealing which ones. To do this, you must ask him to hide both balls under the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVmKoHIGwIsGQI5go6ppfg.png" /></figure><p>After that, ask to take out only one so that you can see it. Next, the ball is hidden again and the next time the verifier may again show either white or black. However, you will be able to prove the claim, since you know exactly whether he changed them under the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*se1xET7xUBuoRT1Blg1Mog.png" /></figure><p>Nevertheless, the verifier will not be completely sure of the truth of the fact, because luck or deception could have taken place. This problem is solved by repeating the experiment a number of times. With every round the chance to be right by chance will halve: after five repetitions the probability of being wrong is 1 in 32, after 10 rounds it is 1 in 1024, and after 20 rounds — about 1 in 1 000 000. With repeats it is possible to achieve the desired level of proof reliability, but it is impossible to achieve absolute certainty.</p><p><strong>What is zero-knowledge proof used for?</strong></p><p>One obvious application of zero-knowledge proof in cryptocurrencies is to check if a user has funds for a transaction, without revealing to network participants who the user is and how much money they have in their account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAH-CXiTxyepChdOizCYLw.png" /></figure><p>Corporations collect a lot of information about each of us: personal data, habits, and desires. Using this data, they sell advertising and hold our attention more effectively. There is only one way out of this situation: delete accounts. There is no other way to keep your data private. But what if you want to take out a loan, for example? You are forced to give the bank accurate information about your income. Using ZKP technology, you could give the bank information that your income is more than a certain amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XC40kKsgDvao2o4PHCXyxw.png" /></figure><p>One condition is important. This range must be significant, otherwise it will not make sense. Such methods could help the financial world use blockchain technology. But at the moment it is difficult because of the lack of legislative ability to do so.</p><p><strong>What types of zero-knowledge proofs are there?</strong></p><p>There are two types of proofs: interactive and non-interactive. In the ball example, the interactive type of proof was used. Because the verifier himself interrogates the proving person in real time. This method has one major disadvantage, which is limited transferability. We proved to one person that the balls are different colors, but if we want to prove it to another person, we have to do it all over again.</p><p>The other form is non-interactive proof. Using this option, we can provide proof that everyone can check for themselves.</p><p>As you know, all transactions are visible on the bitcoin network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ccoea4aY5dNBW8q-b9Th5A.png" /></figure><p>In this way, you can find out how many coins each user has and where he spends them. At the very least, this is insecure. There are projects that use zero-knowledge non-interactive proofs to protect your transactions.</p><p>For example, this is implemented in the project Aleo. No one will see how many coins and to whom you transferred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd4OWafN90g2F7DTmr8ACg.png" /></figure><p>For blockchain, we must use non-interactive proofs because proofs must be verified by every node in the network. That is how blockchains reach consensus. It would be too time consuming to prove our transactions to every node in the network.<br>In addition to its many advantages, the technology has some disadvantages. First, the technology cannot 100% guarantee the correctness of the proof. We can only reduce the probability of error by increasing the number of checks. In this way, we can infinitely reduce the probability that someone will fake the proof. Second, the algorithm requires a large number of calculations, which creates additional complexity. For example, previously it was impossible to run the algorithm on weak devices. Now the developers have made significant progress in solving this problem.<br>Implementation of ZKP technology in crypto projects.<br>I will tell you about it on the example of my favorite project — Aleo. Aleo allows you to create private applications using ZKP technology. You can go to Aleo.org and see all the details of how the project works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eGdVQ1aScbD3QNmZ5eMJA.png" /></figure><p>I said earlier that ZKP requires a lot of computation to work with. The developers have optimized this process, which allows to use this technology quite comfortably. The big advantage is that Aleo team created Leo programming language and IDE called Aleo Studio, which make the process of creating a private application as easy as possible.</p><p>Until now, users have had to choose one of two things: privacy or programmability. For example, Zcash provides users with full privacy but limited programmability. Ethereum provides powerful programmability, but limited privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ogng3XOSnoD-5abFtLHdXg.png" /></figure><p>Aleo uses zero-knowledge cryptography to achieve both privacy and programmability. Like Zcash, this system gives us strong privacy guarantees because transactions only contain proof, not the input that generates it. And like Ethereum, ZEXE can support smart contracts that allow users to interact or transfer value in a pre-defined way.</p><p><strong>How to transfer token using ZKP technology?</strong></p><p>To do this, we can use a decentralized exchange — DEX. DEX is a decentralized application that allows users to buy or sell tokens on the chain without having to search for a specific buyer or seller.</p><p>Let’s say you want to exchange token A for token B on an Aleo-based DEX. First you will need to prove to DEX that you have enough token A to make the transaction. But since this information can be shown with a zero-knowledge proof, this does not mean revealing your wallet balance or trading history. Instead, you can refer to the proof on the previous transaction chain to show that you have enough balance to make a trade.</p><p>When you make a DEX transaction in Aleo, you calculate updated off-chain account balances based on the exchange rate. This transaction is completed by submitting a zero-knowledge proof to the Aleo network as a transaction, indicating that the action occurred. The proof itself contains no information about what the action was, what exchange it was executed on, or who was involved.</p><p>Link to my video course about Aleo: <a href="https://youtube.com/playlist?list=PLsvDEBW3znFKjDFilUiE10lQi7zacQrer">https://youtube.com/playlist?list=PLsvDEBW3znFKjDFilUiE10lQi7zacQrer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d8b38dfb5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developer Way #5. Learn Leo together.]]></title>
            <link>https://romualds-bahvalovs1.medium.com/developer-way-5-learn-leo-together-215b9faabfba?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/215b9faabfba</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 22:23:57 GMT</pubDate>
            <atom:updated>2023-01-29T22:23:57.240Z</atom:updated>
            <content:encoded><![CDATA[<p>Step five. The practical lesson. We created two programs using ZKP.</p><p>Hi everyone, I continue to learn the Leo programming language. Today we are going to have a practical lesson. Now we are going to create 2 programs. If you haven’t read the previous 4 articles, I suggest you do it to understand how the Leo programming language works.</p><p><strong>Bank.</strong></p><p>To do this, we open Aleo Studio and create a new project. The first project is a bank. The concept is this. We invest money in the bank for 10 years. The interest rate is 5% a year. We use the program to calculate how much money we will get. We will need 2 variables: ‘capital’ and ‘rate’. The variable ‘rate’ will be public. They will be of type u32. The output will also contain a variable of type u32.</p><p>The variable ‘capital’ stores the amount of investment.</p><p>The variable “rate” stores the interest rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QM7uaCIAk6_Tios71VL2kg.png" /></figure><p>Let’s create a variable with the value “amount”. We will return it as a result of the program. At the beginning it will have the value of the variable capital. This variable is also of type u32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJfLOSC2FyKf0W1_uE4ouQ.png" /></figure><p>Now we will create a loop that will add 5% per year 10 times. To do this we enter the following text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpx7dt11gq2Yo7psqy6BMA.png" /></figure><p>If we want it to be less than 10 years, we can change that number, for example 5 years. Now we have to calculate the income for one year. To do this, we can do the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4L2qvdBrsiTPEs5KnXtwg.png" /></figure><p>Thus, we add the annual income to the variable. Using the “for” loop, we do this as many times as necessary. Now, after executing the loop, we return the variable amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SniuCSpH4KyPBWuQBzP-ow.png" /></figure><p>We need to add the inputs. To do this, we open the inputs folder. We need to enter data for two variables: rate and capital.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziPimlajYmmrIQixCfbLew.png" /></figure><p>Let’s save the program and run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f5ZZZxpkqSNmYN4Qf0NGw.png" /></figure><p>Everything works, we got the right result.</p><p><strong>Simple token.</strong></p><p>Let’s create a new project. Let’s call it simple_token. In this project we will make a transaction from one wallet to another. First we will create a new record. Let’s call it “token”. The record will contain these data: owner, gates and amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFmSE7YD_06YABkviS5bkQ.png" /></figure><p>Now we need to create a Transition Function. It gets these inputs: a record with information about the token, the address where the token will arrive and the number of tokens. The output from the function is 2 “token” records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70ANIwhbGsmUEepJgiOHzA.png" /></figure><p>Now we need to create a variable that will store information about how many tokens are left in this wallet. To do this, we subtract the transfer amount from the number of tokens in the wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70ANIwhbGsmUEepJgiOHzA.png" /></figure><p>All we need to do is to create two variables and return them. The first variable counts the remainder. We create a variable called ‘remaining’, which is of type “token”. It has the following information: the owner and gates we get from the input data. The number of tokens is the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guNciKDPc8jEJSZvRzqW2Q.png" /></figure><p>And the second variable, it shows the recipient and the number of tokens that have arrived at that address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVpa6xNu6wq_gLKdDoZQew.png" /></figure><p>Now we need to return these two variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUOMJhJ-PTcFw_Dxh2l3rA.png" /></figure><p>Let’s type in the inputs. To do this, go to the inputs folder. Here we specify the data. We write the name of the function and specify the data that entered into it. For example, here the sender’s address is 100 tokens. The transfer amount is 30 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehvBpv8AwDNS1WoPdXOnHg.png" /></figure><p>Addresses are a very important point with which I had problems. The address must be added to the input data, as well as to the program.json file. In order to generate an address we go to aleo.tools. Here we click the “generate” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0JRcj6UK55qKeK6N-Z7jA.png" /></figure><p>We need an address and a private key. In the input we enter the address. In the program.json file we enter the address and the private key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uq6xuyd6iXdu7V_iN0wS-g.png" /></figure><p>For the second address, we press the generate button again. As a result, we get the following input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQQwWu17x2fjwHm6A1Hwjg.png" /></figure><p>Let’s save the file and run our program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLFzllTfH1dr2eUdmA9elQ.png" /></figure><p>Everything is working correctly. There are 70 tokens left at the sender’s address, and 30 tokens were sent.</p><p>That’s all for today. If you like this article, subscribe to me to get a lot of useful and interesting content.</p><p><em>Resources.</em></p><p><em>My video on this topic: </em><a href="https://youtu.be/wGKI2NT35kY"><em>https://youtu.be/wGKI2NT35kY</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215b9faabfba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developer Way #4. Learn Leo together]]></title>
            <link>https://romualds-bahvalovs1.medium.com/developer-way-4-learn-leo-together-faf3a04f2bc6?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf3a04f2bc6</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 22:16:16 GMT</pubDate>
            <atom:updated>2023-01-29T22:16:16.314Z</atom:updated>
            <content:encoded><![CDATA[<p>Step four. Functions in the Leo programming language.</p><p>Hi everyone, I’m continuing to learn the Leo programming language. Today we will talk about functions. This article will contain a lot of theory. But the next article will be focused on practice, we will create 2 programs.</p><p><strong>The import tool.</strong></p><p>First, I wanted to test the import tool. And it didn’t work for me. Maybe I didn’t understand the documentation on the website correctly. I tried creating a folder in the project called imports and creating a file foo.leo there. When importing into the main file, the program could not find the file to be imported. I tried solving this error. For example, moving the imports folder to the src folder. In the end, I never solved the problem.</p><p>Didn’t solve it on the first try.</p><p>Maybe I’m making a silly mistake somewhere. Although the site says: Leo’s imports are unstable and currently provide only minimal functionality. It is expected that their syntax will be changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaMA2KalTKXygHoQfhXivg.png" /></figure><p>And yes…I did make a silly mistake. The name of the folder is… Imporst. I only figured it out when I started recording the video. To my surprise, it worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3e8-M5M0gDiQKmumH9yvg.png" /></figure><p>So the above algorithm is relevant for importing into leo.</p><p><strong>Structs.</strong></p><p>Let’s move on to the next topic. The structs. The struct data type is declared as: struct {name} {}.</p><p>Structures contain component declarations of the form {name}: {type}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNjlGP6L2MOp4w0DDtTy5Q.png" /></figure><p>At this point, I don’t know exactly how the application for this type is found.</p><p><strong>Records.</strong></p><p>The record data type is declared as: record {name} {}. Records contain component declarations in the form: {name}: {type},.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPKQ4t93HlaEI32mseVurw.png" /></figure><p>The record data structures must contain the owner and gates components, as shown in the screenshot. When passing a record as input to a program function, the _nonce: group component is also required. Each account record contains information defining the owner of the record, its stored value, and the state of the application. An Aleo account can create a transaction in order to use the record and create a new one in its place.</p><p><strong>Mapping.</strong></p><p>The mapping is declared as mapping {name}: {key-type} =&gt; {value-type} Mappings contain key-value pairs. The mappings are stored in a chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBA8SwX8T0WzEzGTwQe6pw.png" /></figure><p><strong>Input and output functions.</strong></p><p>The input function is declared as: {visibility} {name}: {type}, Function inputs must be declared immediately after the function name is declared, in parentheses. In the example transition function `foo` takes a single input `a` with type `field` and visibility `public`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyCT6PSSuXNu3pNcu4f6fg.png" /></figure><p>The output of the function is calculated as return {expression};. The return of the output completes the execution of the function. The type of return in the function declaration must match the type of the return {expression}. Here the addition of the public input A and the value `1field` is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ce9h8JmvCECRrHRthzCNMA.png" /></figure><p><strong>Helper Functions.</strong></p><p>Helper functions are declared as: function {name}() {}. They contain expressions and operators that can compute values. Helper functions cannot be executed directly. They must be called by other functions. Helper function inputs cannot have {visibility} modifiers, like transition functions, because they are only used inside the program, not as part of its external interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mGG1CeTZ9yiubsvW3cjGw.png" /></figure><p><strong>Increment and Decrement.</strong></p><p>The increment operator has the form increment(mapping, key, value);. The decrement operator has the form decrement(mapping, key, value);. Increment and decrement operators can only be used in finalization functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R74YA8e8H_inkODOmsLKkw.png" /></figure><p><strong>Finalize function.</strong></p><p>The finalize function is declared as finalize {name}:. The finalize function must immediately follow the transition function and have the same name; it is associated with the transition function and executed along the chain, after checking for proof of null knowledge of the associated transition execution; the finalize function completes the transition function along the chain. If the finalize function succeeds, program logic is executed. If the finalize function fails, the program logic is cancelled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuilR8mT6grmZpgorH7s6w.png" /></figure><p><strong>Operators.</strong></p><p>In this video, let’s study the theory some more, and in the next article, let’s practice. Let’s talk about operators. Operators in Leo calculate a value based on one or more expressions. Leo tries to detect errors in arithmetic operations as early as possible. If an integer overflow or division by zero can be detected at compile time, Leo will quickly inform the programmer. Otherwise, the error will be detected during the proof, when the transition function inputs are being processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*354MBlSFCF5Oozm9vnX7eg.png" /></figure><p>For example, there are several ways to apply addition to a variable. You can see them in the screenshot. In the first line, we create a variable where we add 1+1. Then we add 1 to 2. Then we add another 1 by using the “add” construction. Thus, the A variable has a value of 4. The same principle works for subtraction. You can see all operators on the Aleo website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WY-B15Dd1YLcx5KvgFCLfw.png" /></figure><p>That’s all for today. If you like this article, subscribe to me to get lots of useful and interesting content.</p><p>Resources.</p><p>Aleo’s article on this topic: <a href="https://developer.aleo.org/leo/language">https://developer.aleo.org/leo/language</a></p><p>My video on this topic: <a href="https://youtu.be/n0Y7SdyKfps">https://youtu.be/n0Y7SdyKfps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf3a04f2bc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developer Way #3. Learn Leo together]]></title>
            <link>https://romualds-bahvalovs1.medium.com/developer-way-3-learn-leo-together-781500ee7689?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/781500ee7689</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 22:06:31 GMT</pubDate>
            <atom:updated>2023-01-29T22:06:31.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Step three. Variables in the Leo programming language.</p><p>Hi everyone, I’m continuing to learn the Leo programming language. Today we will talk about variables. Now the material is more complicated, but I will try to tell you as much as possible.</p><p><strong>Aleo studio.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Sxk0XepiEATT55IPJa09Q.png" /></figure><p>I found out that there is an IDE Aleo Studio. We can conveniently edit and run code in it. You can download the application from the official website. The installation is very simple, so let’s skip this step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8gll1NpDomn475ScI5Q9g.png" /></figure><p>We open the application and write the name of our project. There are no additional settings here. We press the “Create” button. We create an Aleo project with all the necessary files. Its location you can see on the screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNsGVbeWcYBSby9hUc5Bjg.png" /></figure><p>If you don’t know what these folders contain, you can read my previous article or watch my video on the subject. I will provide all the links to sources at the end of the article.</p><p><strong>Variables.</strong></p><p>So… let’s move on to the main topic. To create a variable, you need to type “Let”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uM9tXe3lRwuDbvgCLlYdew.png" /></figure><p>Next, “A” is the name of the variable. The letter “u” or “i” indicates whether it is a signed (i) or unsigned (u) integer, and the number indicates the size of the integer. For example, the type i8 is an 8-bit integer, and u32 is an unsigned 32-bit integer. 8 is the value of the variable. We also write u32 after 8. Leo will not use an integer type by default. The definition of an integer must include an explicit type. Type casting is not supported yet.</p><p>Let’s talk about another data type. Leo supports the traditional boolean values true or false. Boolean values in statements also require an explicit bool type. In this article we will make a small program where we will use these 2 types of variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kW4mJC3POdUR-FT7Au6hfg.png" /></figure><p>There are also more complex types of variables in leo.</p><p><em>Field Elements.</em> Leo supports the field type for the base field elements of the elliptic curve. These are unsigned integers below the modulus of the base field. They are created this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fHk44cjMu-8b4kJkTIJAg.png" /></figure><p>We also specify the data type after the variable value. In this case it is “field”.</p><p><em>Group Elements.</em> At this point, I don’t quite understand how they work. In the documentation you can read the following explanation: « The set of affine points on the elliptic curve passed into the Leo compiler forms a group. Leo supports a subgroup of this group, generated by a generator point, as a primitive data type. Group elements are special since their values can be defined from the x-coordinate of a coordinate pair, such as 1group. The group type keyword group must be used when specifying a group value. »</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DZbbi-I2mtWZcVExz5kFg.png" /></figure><p><em>Scalar Elements</em>. Leo supports the scalar type for scalar field elements of the elliptic curve subgroup. These are unsigned integers below the modulus of the scalar field.</p><p>They are created on the same principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28wNdcuC1KZHHoLCZDRaVA.png" /></figure><p>To add an address, we can create a variable this way. You can use aleo.tools to generate the address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y60zDFG7UMseiWK2EaX0HA.png" /></figure><p><strong>Program Creation.</strong></p><p>We’ve taken apart the basic types of variables. Now I don’t quite understand how groups and scalar elements work. Let’s get down to practice. We will now create a program that will check if the balance is sufficient to make a transaction. That is, we will need to create 3 variables. The first variable is the balance of the wallet. The second variable is the amount we want to transfer. The third variable will be of Boolean type and will tell if the transaction is possible or not.</p><p>Create a new project in Aleo Studio. File — New leo project. Enter the name of the program. Actually we don’t need to modify the program, which is already in leo by default. Let’s change it step by step. First, let’s change the name and type of variables. The first variable is called “balance” and is private, so we will remove the word public. The second variable is called “transaction_amount”. It will also be private and of type u32. We will return a variable of type Boolean, so we make changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4G1P0Paf9j5VqdI4P2l5JA.png" /></figure><p>Now we need to create a Boolean variable. Let’s call this variable “solution”. We can assign any value to it. I will set it to false. This will help make the code a little bit shorter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FuQSysrOmsfYdFKmlDyFg.png" /></figure><p>Now we need to use an if-else construct. If the balance is higher than the transaction amount, then the value of the “solution” variable is “true” and we return the “solution” variable. Otherwise, we return the “decision” variable, which has a value of false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hz2gg9y_a5hgFwbj9zwb5Q.png" /></figure><p>Now we need to change the input data. For example, the balance is 10. And the transaction amount is 3. So, we must get the value “true”, that is, the transaction is possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyQzxV6G26WJ5FS3sg2lSw.png" /></figure><p>Let’s keep our project and get our program running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qh98goYRvl5c_aqr6VPI3g.png" /></figure><p>Yes, everything works. The transaction is possible. If we change the value and the transaction amount is higher than the balance, then we get “false”.</p><p>I hope you enjoyed this article. If so, subscribe to my page. I release a lot of useful and interesting content here.</p><p><em>Resources:</em></p><p><em>Link to Aleo’s article on this topic: </em><a href="https://developer.aleo.org/leo/language/"><em>https://developer.aleo.org/leo/language/</em></a></p><p><em>My second video about leo: </em><a href="https://youtu.be/7fA-PpwFMio"><em>https://youtu.be/7fA-PpwFMio</em></a></p><p><em>This article in video format: </em><a href="https://youtu.be/LmIiVB6aYb8"><em>https://youtu.be/LmIiVB6aYb8</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=781500ee7689" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Путь разработчика н5. Изучаем LEO вместе.]]></title>
            <link>https://romualds-bahvalovs1.medium.com/%D0%BF%D1%83%D1%82%D1%8C-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B0-%D0%BD5-%D0%B8%D0%B7%D1%83%D1%87%D0%B0%D0%B5%D0%BC-leo-%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%B5-9e74116edfee?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e74116edfee</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 21:55:59 GMT</pubDate>
            <atom:updated>2023-01-29T22:01:40.455Z</atom:updated>
            <content:encoded><![CDATA[<p>Шаг пятый. Практика. Сделаем 2 программы используя ZKP(Доказательство с нулевым разглашением).</p><p>Всем привет! Я продолжаю изучать язык программирования Leo. Сегодня у нас будет практический урок. Сейчас мы создадим 2 программы. Если вы не прочитали предыдущие 4 статьи, то советую сделать это для понимания, как работает язык программирования Leo.</p><p><strong>Банк.</strong></p><p>Для этого мы открываем Aleo Studio и создаем новый проект. Первый проект — это банк. Концепция такова. Мы вкладываем деньги в банк на 10 лет. Процентная ставка составляет 5% в год. С помощью программы мы посчитаем, какую сумму мы получим. Нам потребуется 2 переменные: «capital» и ‘rate’. Переменная “rate” будет публичная. Они будут иметь тип u32. На выходе мы получим также переменную с типом u32.</p><p>Переменная «capital» хранит сумму вложения.</p><p>Переменная «rate» хранит процентную ставку.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QM7uaCIAk6_Tios71VL2kg.png" /></figure><p>Давайте создадим переменную со значением amount. Ее мы будем возвращать в результате работы программы. В начале она будет иметь значение переменной capital. Тип этой переменной также u32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJfLOSC2FyKf0W1_uE4ouQ.png" /></figure><p>Теперь мы создадим цикл, который 10 раз прибавит 5% годовых. Для этого мы вводим такой текст.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpx7dt11gq2Yo7psqy6BMA.png" /></figure><p>Если мы хотим, чтобы было не 10 лет, то можем поменять это число, например, 5 лет. Теперь мы должны посчитать доход за один год. Для этого мы можем произвести следующие действия.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4L2qvdBrsiTPEs5KnXtwg.png" /></figure><p>Таким образом, мы к переменной добавляем годовой доход. Используя цикл for, мы делаем это нужное количество раз. Теперь после выполнения цикла, мы возвращаем переменную amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SniuCSpH4KyPBWuQBzP-ow.png" /></figure><p>Нам нужно добавить входные данные. Для этого открываем папку inputs. Мы должны ввести данные для двух переменных: rate и capital.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziPimlajYmmrIQixCfbLew.png" /></figure><p>Давайте сохраним программу и запустим ее.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f5ZZZxpkqSNmYN4Qf0NGw.png" /></figure><p>Всё работает, мы получили правильный результат.</p><p><strong>Простой токен.</strong></p><p>Давайте создадим новый проект. Назовем его simple_token. В этом проекте мы совершим транзакцию с одного кошелька на другой. Для начала создаем новую запись. Назовем ее «токен». В записи будут содержаться эти данные: owner, gates и amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFmSE7YD_06YABkviS5bkQ.png" /></figure><p>Сейчас мы должны создать Transition Function (функция перехода). Она получает эти входные данные: запись с информацией о токене, адрес на который поступит токен и количество токенов. Выходные данные из функции это 2 записи «token».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70ANIwhbGsmUEepJgiOHzA.png" /></figure><p>Теперь нам нужно создать переменную, которая будет хранить информацию, сколько токенов останется на этом кошельке. Для этого мы вычитаем сумму перевода из количества токенов на кошельке.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70ANIwhbGsmUEepJgiOHzA.png" /></figure><p>Нам осталось создать 2 переменные и вернуть их. Первая переменная считает остаток. Мы создаем переменную ‘remaining”, которая имеет тип “token”. Она имеет в себе следующую информацию: owner and gates мы получаем из входных данных. Количество токенов это разница.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guNciKDPc8jEJSZvRzqW2Q.png" /></figure><p>И вторая переменная, она показывает получателя и количество токенов, которые поступили на этот адрес.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVpa6xNu6wq_gLKdDoZQew.png" /></figure><p>Теперь нам нужно вернуть две этих переменные.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUOMJhJ-PTcFw_Dxh2l3rA.png" /></figure><p>Давайте заполним входные данные. Для этого переходим в папку inputs. Здесь мы указываем данные. Пишем название функции и указываем, какие данные в нее поступили. Например, здесь на адресе отправителя 100 токенов. Сумма перевода это 30 токенов.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehvBpv8AwDNS1WoPdXOnHg.png" /></figure><p>Адреса — это очень важный момент с которыми у меня возникли проблемы. Адрес нужно добавить во входные данные, а также в файл program.json. Для того чтобы сгенерировать адрес мы заходим на сайт aleo.tools. Здесь мы нажимаем кнопку «generate».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0JRcj6UK55qKeK6N-Z7jA.png" /></figure><p>Нам нужен адрес и приватный ключ. Во входных данных мы указываем адрес. В файле program.json вводим адрес и приватный ключ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uq6xuyd6iXdu7V_iN0wS-g.png" /></figure><p>Для второго адреса мы нажимаем кнопку сгенерировать снова. В итоге, мы получаем такие входные данные.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQQwWu17x2fjwHm6A1Hwjg.png" /></figure><p>Давайте сохраним файл и запустим нашу программу.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLFzllTfH1dr2eUdmA9elQ.png" /></figure><p>Всё работает правильно. На адресе отправителя осталось 70 токенов, отправилось 30 токенов.</p><p>На этом сегодня всё. Если тебе нравится эта статья, то подпишись на меня чтобы получать много полезного и интересного контента.</p><p><em>Ресурсы.</em></p><p>Моё видео по этой теме: <a href="https://youtu.be/wGKI2NT35kY">https://youtu.be/wGKI2NT35kY</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e74116edfee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Путь разработчика н4. Изучаем LEO вместе.]]></title>
            <link>https://romualds-bahvalovs1.medium.com/%D0%BF%D1%83%D1%82%D1%8C-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B0-%D0%BD4-%D0%B8%D0%B7%D1%83%D1%87%D0%B0%D0%B5%D0%BC-leo-%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%B5-8739ea6c6ea5?source=rss-43139b0c815c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8739ea6c6ea5</guid>
            <dc:creator><![CDATA[Romualds Bahvalovs]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 21:44:19 GMT</pubDate>
            <atom:updated>2023-01-29T21:44:19.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Шаг четвёртый. Функции в языке программирования LEO.</p><p>Всем привет! Я продолжаю изучать язык программирования Leo. Сегодня мы будем говорить о функциях. Данная статья будет содержать достаточно много теории. Зато, следующая статья будет заточена на практику, мы создадим 2 программы.</p><p><strong>Средство импорта.</strong></p><p>Для начала, я хотел протестировать средство импорта. И у меня ничего не получилось. Может быть, я не совсем правильно понял документацию на сайте. Я пробовал создать в проекте папку под названием imports и создать там файл foo.leo. При импорте в главный файл, программа не могла найти импортируемый файл. Я пробовал решить эту ошибку. Например, переместить папку imports в папку src. В итоге, проблему я так и не решил.</p><p>Не решил с первой попытки.</p><p>Может быть, я где делаю глупую ошибку. Хотя на сайте написано: Импорты Leo нестабильны и в настоящее время и обеспечивают лишь минимальную функциональность. Ожидается, что их синтаксис будет изменен.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaMA2KalTKXygHoQfhXivg.png" /></figure><p>И да…Я действительно делал глупую ошибку. Название папки… Imporst. Я выяснил это, лишь когда стал записывать видео. На моё удивление, всё заработало.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3e8-M5M0gDiQKmumH9yvg.png" /></figure><p>Так что приведенный выше алгоритм, актуален для импорта в leo.</p><p><strong>Структуры.</strong></p><p>Давайте перейдем к следующей теме. Структуры. Тип данных struct объявляется как: struct {name} {}.</p><p>Структуры содержат объявления компонентов по форме {name}: {type}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNjlGP6L2MOp4w0DDtTy5Q.png" /></figure><p>В данный момент, я не знаю точно, как находится применение для этого типа.</p><p><strong>Записи.</strong></p><p>Тип данных записи объявляется как: record {name} {}. Записи содержат декларации компонентов в форме: {name}: {type},.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPKQ4t93HlaEI32mseVurw.png" /></figure><p>Структуры данных записи должны содержать компоненты owner и gates, как показано на скрине. При передаче записи в качестве входных данных в программную функцию также требуется компонент _nonce: group,. Каждая запись счета содержит информацию, определяющую владельца записи, ее хранимое значение и состояние приложения. Учетная запись Aleo может создать транзакцию для того, чтобы использовать запись и создать на ее месте новую.</p><p><strong>Отображение (mapping).</strong></p><p>Отображение объявляется как mapping {name}: {key-type} =&gt; {value-type}. Отображения содержат пары ключ-значение. Отображения хранятся в цепочке.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBA8SwX8T0WzEzGTwQe6pw.png" /></figure><p><strong>Функции входа и выхода.</strong></p><p>Входная функция объявляется как: {visibility} {name}: {type}, Входы функций должны быть объявлены сразу после объявления имени функции, в круглых скобках. В примере функция перехода `foo` принимает единственный вход `a` с типом `field` и видимостью `public`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyCT6PSSuXNu3pNcu4f6fg.png" /></figure><p>Выход функции вычисляется как return {expression};. Возвращение вывода завершает выполнение функции. Тип return в объявлении функции должен совпадать с типом возвращаемого {expression}. Здесь возвращается сложение публичного входа A и значения `1field`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ce9h8JmvCECRrHRthzCNMA.png" /></figure><p><strong>Вспомогательные функции.</strong></p><p>Вспомогательная функция объявляется как: function {name}() {}. Они содержат выражения и операторы, которые могут вычислять значения. Вспомогательные функции не могут выполняться напрямую. Они должны вызываться другими функциями. Входы вспомогательных функций не могут иметь модификаторов {visibility}, как функции перехода, поскольку они используются только внутри программы, а не как часть ее внешнего интерфейса.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mGG1CeTZ9yiubsvW3cjGw.png" /></figure><p><strong>Инкремент и Декремент.</strong></p><p>Оператор инкремента имеет форму increment(mapping, key, value);. Оператор декремента имеет форму decrement(mapping, key, value);. Операторы инкремента и декремента могут использоваться только в функциях финализации.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R74YA8e8H_inkODOmsLKkw.png" /></figure><p><strong>Функция финализации.</strong></p><p>Функция финализации объявляется как finalize {name}:. Функция finalize должна непосредственно следовать за функцией перехода и иметь такое же имя; она ассоциируется с функцией перехода и выполняется по цепочке, после проверки доказательства нулевого знания о выполнении ассоциированного перехода; функция finalize завершает функцию перехода по цепочке. При успешном завершении функции finalize выполняется программная логика. При неудаче функции finalize программная логика отменяется.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuilR8mT6grmZpgorH7s6w.png" /></figure><p><strong>Операторы.</strong></p><p>Давайте в этом видео мы еще немного изучим теорию, а в следующей статье, будем практиковаться. Давайте поговорим про операторы. Операторы в Leo вычисляют значение на основе одного или нескольких выражений. Leo старается обнаружить ошибки арифметических операций как можно раньше. Если целочисленное переполнение или деление на ноль можно определить во время компиляции, Leo быстро сообщит об этом программисту. В противном случае ошибка будет обнаружена во время доказательства, когда обрабатываются входы функции перехода.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*354MBlSFCF5Oozm9vnX7eg.png" /></figure><p>Например, чтобы применить сложение к переменной есть несколько путей. Вы их видите на скриншоте. В первой строке мы создаем переменную, где складывается 1+1. Далее к 2 мы прибавляем 1. После, с применением конструкции «add», добавляем еще 1. Таким образом, переменная A имеет значение 4. По такому же принципу работает вычитание. Все операторы вы можете посмотреть на сайте Aleo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WY-B15Dd1YLcx5KvgFCLfw.png" /></figure><p>На этом сегодня всё. Если тебе нравится эта статья, то подпишись на меня чтобы получать много полезного и интересного контента.</p><p><em>Ресурсы.</em></p><p>Статья Aleo по этой теме: <a href="https://developer.aleo.org/leo/language">https://developer.aleo.org/leo/language</a></p><p>Моё видео по этой теме: <a href="https://youtu.be/n0Y7SdyKfps">https://youtu.be/n0Y7SdyKfps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8739ea6c6ea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>