diff --git a/codex/about.md b/codex/about.md index fc32f39..ada456d 100644 --- a/codex/about.md +++ b/codex/about.md @@ -1,3 +1,3 @@ -# About Codex +# О Codex - Work in progress :construction: + В процессе разработки :construction: diff --git a/codex/disclaimer.md b/codex/disclaimer.md index dba0977..0aa6354 100644 --- a/codex/disclaimer.md +++ b/codex/disclaimer.md @@ -1,5 +1,5 @@ -# Disclaimer +# Отказ от ответственности -The code and instructions provided within this repository and related repositories are provided “as-is”, without warranty of any kind, express or implied, including but not limited to the safety or correctness, or performance of the code or instructions provided. We make no assurance that the code will work as intended, and users may experience delays, failures, errors, omissions or loss of transmitted information whilst using or running Codex. +Код и инструкции, предоставленные в этом репозитории и связанных репозиториях, предоставляются "как есть", без каких-либо гарантий, явных или подразумеваемых, включая, но не ограничиваясь, безопасностью, корректностью или производительностью предоставленного кода или инструкций. Мы не гарантируем, что код будет работать как задумано, и пользователи могут столкнуться с задержками, сбоями, ошибками, пропусками или потерей передаваемой информации при использовании или запуске Codex. -Running Codex is done at your own risk. As such, we are not responsible nor liable for any damage that may occur to your hardware, software, data, or network, or for any loss, claim, damage of whatever nature, or other liability arising from or in connection with the use of the provided code and instructions. +Запуск Codex осуществляется на ваш собственный риск. Таким образом, мы не несем ответственности и не обязаны возмещать любой ущерб, который может быть нанесен вашему оборудованию, программному обеспечению, данным или сети, или за любые потери, претензии, ущерб любого характера или другие обязательства, возникающие в связи с использованием предоставленного кода и инструкций. diff --git a/codex/privacy-policy.md b/codex/privacy-policy.md index 256025f..5cad07d 100644 --- a/codex/privacy-policy.md +++ b/codex/privacy-policy.md @@ -1,15 +1,15 @@ --- lastUpdated: false --- -# Privacy Policy +# Политика конфиденциальности -Last updated: 9 February 2024 +Последнее обновление: 9 февраля 2024 года -This Privacy Policy is intended to inform users of our approach to privacy in respect of this website (**"Website"**). In this regard, if you are visiting our Website, this Privacy Policy applies to you. +Настоящая Политика конфиденциальности предназначена для информирования пользователей о нашем подходе к конфиденциальности в отношении данного веб-сайта (**"Веб-сайт"**). В этом отношении, если вы посещаете наш Веб-сайт, настоящая Политика конфиденциальности применяется к вам. -### 1) Who we are +### 1) Кто мы -For the purposes of this Privacy Policy and the collection and processing of personal data as a controller, the relevant entity is the Logos Collective Association, which has its registered office in Zug and its legal domicile address at +Для целей настоящей Политики конфиденциальности и сбора и обработки персональных данных в качестве контролера соответствующей организацией является Logos Collective Association, которая имеет зарегистрированный офис в Цуге и юридический адрес: ``` Logos Collective Association @@ -19,54 +19,54 @@ Baarerstrasse 10 Switzerland ``` -Whenever we refer to “Logos”, “we” or other similar references, we are referring to the Logos Collective Association. +Всякий раз, когда мы ссылаемся на "Logos", "мы" или другие подобные ссылки, мы имеем в виду Logos Collective Association. -### 2) We limit the collection and processing of personal data from your use of the Website +### 2) Мы ограничиваем сбор и обработку персональных данных при использовании вами Веб-сайта -We aim to limit the collection and collection and processing of personal data from users of the Website. We only collect and process certain personal data for specific purposes and where we have the legal basis to do so under applicable privacy legislation. We will not collect or process any personal data that we don’t need and where we do store any personal data, we will only store it for the least amount of time needed for the indicated purpose. +Мы стремимся ограничить сбор и обработку персональных данных от пользователей Веб-сайта. Мы собираем и обрабатываем только определенные персональные данные для конкретных целей и только в тех случаях, когда у нас есть правовое основание для этого в соответствии с применимым законодательством о конфиденциальности. Мы не будем собирать или обрабатывать какие-либо персональные данные, которые нам не нужны, и там, где мы храним какие-либо персональные данные, мы будем хранить их только в течение минимального времени, необходимого для указанной цели. -In this regard, we collect and process the following personal data from your use of the Website: +В этом отношении мы собираем и обрабатываем следующие персональные данные при использовании вами Веб-сайта: -* **IP address**: As part of such use of the Website, we briefly process your IP address but we have no way of identifying you. We however have a legitimate interest in processing such IP addresses to ensure the technical functionality and enhance the security measures of the Website. This IP address is not stored by us over time. +* **IP-адрес**: В рамках такого использования Веб-сайта мы кратковременно обрабатываем ваш IP-адрес, но у нас нет возможности идентифицировать вас. Однако у нас есть законный интерес в обработке таких IP-адресов для обеспечения технической функциональности и усиления мер безопасности Веб-сайта. Этот IP-адрес не хранится нами с течением времени. -### 3) Third party processing of personal data +### 3) Обработка персональных данных третьими сторонами -In addition to our limited and collection of personal data, third parties may collect or process personal data as a result of the Website making use of certain features or to provide certain content. To the extent you interact with such third party content or features, their respective privacy policies will apply. +В дополнение к нашему ограниченному сбору персональных данных, третьи стороны могут собирать или обрабатывать персональные данные в результате использования Веб-сайтом определенных функций или для предоставления определенного контента. В той степени, в которой вы взаимодействуете с таким контентом или функциями третьих сторон, будут применяться их соответствующие политики конфиденциальности. -### 4) Security measures we take in respect of the Website +### 4) Меры безопасности, которые мы принимаем в отношении Веб-сайта -As a general approach, we take data security seriously and we have implemented a variety of security measures on the Website to maintain the safety of your personal data when you submit such information to us. +В качестве общего подхода мы серьезно относимся к безопасности данных и внедрили различные меры безопасности на Веб-сайте для поддержания безопасности ваших персональных данных, когда вы отправляете такую информацию нам. -### 5) Exporting data outside the European Union and Switzerland +### 5) Экспорт данных за пределы Европейского Союза и Швейцарии -We are obliged to protect the privacy of personal data that you may have submitted in the unlikely event that we export your personal data to places outside the European Union or Switzerland. This means that personal data will only be processed in countries or by parties that provide an adequate level of protection as deemed by Switzerland or the European Commission. Otherwise, we will use other forms of protections, such as specific forms of contractual clauses to ensure such personal data is provided the same protection as required in Switzerland or Europe. In any event, the transmission of personal data outside the European Union and Switzerland will always occur in conformity with applicable privacy legislation. +Мы обязаны защищать конфиденциальность персональных данных, которые вы могли предоставить в маловероятном случае, если мы экспортируем ваши персональные данные в места за пределами Европейского Союза или Швейцарии. Это означает, что персональные данные будут обрабатываться только в странах или сторонами, которые обеспечивают адекватный уровень защиты, признанный Швейцарией или Европейской комиссией. В противном случае мы будем использовать другие формы защиты, такие как специальные формы договорных положений, чтобы обеспечить таким персональным данным такую же защиту, как требуется в Швейцарии или Европе. В любом случае передача персональных данных за пределы Европейского Союза и Швейцарии всегда будет происходить в соответствии с применимым законодательством о конфиденциальности. -### 6) Your choices and rights +### 6) Ваши выбор и права -As explained in this Privacy Policy, we limit our collection and processing of your personal data wherever possible. Nonetheless, you still have certain choices and rights in respect of the personal data which we do collect and process. As laid out in relevant privacy legislation, you have the right to: +Как объяснено в настоящей Политике конфиденциальности, мы ограничиваем сбор и обработку ваших персональных данных везде, где это возможно. Тем не менее, у вас все еще есть определенные выбор и права в отношении персональных данных, которые мы собираем и обрабатываем. Как изложено в соответствующем законодательстве о конфиденциальности, вы имеете право: -* Ask us to correct or update your personal data (where reasonably possible); +* Попросить нас исправить или обновить ваши персональные данные (где это разумно возможно); -* Ask us to remove your personal data from our systems; +* Попросить нас удалить ваши персональные данные из наших систем; -* Ask us for a copy of your personal data, which may also be transferred to another data controller at your request; +* Попросить нас предоставить копию ваших персональных данных, которая также может быть передана другому контролеру данных по вашему запросу; -* Withdraw your consent to process your personal data (only if consent was asked for a processing activity), which only affects processing activities that are based on your consent and doesn’t affect the validity of such processing activities before you have withdrawn your consent; +* Отозвать свое согласие на обработку ваших персональных данных (только если согласие было запрошено для деятельности по обработке), что влияет только на действия по обработке, основанные на вашем согласии, и не влияет на действительность таких действий по обработке до того, как вы отозвали свое согласие; -* Object to the processing of your personal data; and +* Возражать против обработки ваших персональных данных; и -* File a complaint with the Federal Data Protection and Information Commissioner (FDPIC), if you believe that your personal data has been processed unlawfully. +* Подать жалобу в Федерального комиссара по защите данных и информации (FDPIC), если вы считаете, что ваши персональные данные были обработаны незаконно. -### 7) Third party links +### 7) Ссылки на сторонние сайты -On this Website, you may come across links to third party websites. These third party sites have separate and independent privacy policies. We therefore have no responsibility or liability for the content and activities of these third party websites. +На этом Веб-сайте вы можете встретить ссылки на сторонние веб-сайты. У этих сторонних сайтов есть отдельные и независимые политики конфиденциальности. Поэтому мы не несем ответственности за содержание и деятельность этих сторонних веб-сайтов. -### 8) This Privacy Policy might change +### 8) Настоящая Политика конфиденциальности может измениться -We may modify or replace any part of this Privacy Policy at any time and without notice. Please check the Website periodically for any changes. The new Privacy Policy will be effective immediately upon its posting on our Website. +Мы можем изменить или заменить любую часть настоящей Политики конфиденциальности в любое время и без уведомления. Пожалуйста, периодически проверяйте Веб-сайт на наличие изменений. Новая Политика конфиденциальности вступает в силу немедленно после ее размещения на нашем Веб-сайте. -### 9) Contact information +### 9) Контактная информация -To the extent that you have any questions about the Privacy Policy, please contact us at legal@free.technology. +Если у вас есть какие-либо вопросы о Политике конфиденциальности, пожалуйста, свяжитесь с нами по адресу legal@free.technology. -This document is licensed under CC-BY-SA. +Этот документ лицензирован под CC-BY-SA. diff --git a/codex/security.md b/codex/security.md index 4da6ab5..b00ff03 100644 --- a/codex/security.md +++ b/codex/security.md @@ -1,7 +1,7 @@ -# Security +# Безопасность -We take security seriously at Codex and across the Institute of Free Technology and its affiliates. +Мы серьезно относимся к безопасности в Codex и в Институте свободных технологий и его филиалах. -Please report any security incidents via security@free.technology. +Пожалуйста, сообщайте о любых инцидентах безопасности по адресу security@free.technology. -Please report any discovered vulnerabilities in our bounty programme at HackenProof to help ensure our protocols and software remain secure. +Пожалуйста, сообщайте о любых обнаруженных уязвимостях в нашей программе вознаграждений на HackenProof, чтобы помочь обеспечить безопасность наших протоколов и программного обеспечения. diff --git a/codex/terms-of-use.md b/codex/terms-of-use.md index bf8472b..c4455a6 100644 --- a/codex/terms-of-use.md +++ b/codex/terms-of-use.md @@ -1,19 +1,19 @@ --- lastUpdated: false --- -# Terms of Use +# Условия использования -Last updated: 14 February 2024 +Последнее обновление: 14 февраля 2024 года -These website terms of use ("**Website Terms of Use**") are entered into by you and us, and they govern your access and use of this Website, including any content and functionality contained in the Website. +Настоящие условия использования веб-сайта ("**Условия использования веб-сайта**") заключены между вами и нами и регулируют ваш доступ и использование данного веб-сайта, включая любой контент и функциональность, содержащиеся на веб-сайте. -It is your responsibility to read the Website Terms of Use carefully before your use of the Website and your use of the Website means you have agreed to be bound and comply with these Website Terms of Use. +Вы несете ответственность за тщательное ознакомление с Условиями использования веб-сайта перед использованием веб-сайта, и ваше использование веб-сайта означает ваше согласие соблюдать настоящие Условия использования веб-сайта. -If you do not agree with these Website Terms of Use, you must not access or use the Website. +Если вы не согласны с настоящими Условиями использования веб-сайта, вы не должны получать доступ к веб-сайту или использовать его. -### 1) Who we are +### 1) Кто мы -For the purposes of these Website Terms of Use, the relevant entity is the Logos Collective Association, which has its registered office in Zug and its legal domicile address at: +Для целей настоящих Условий использования веб-сайта соответствующей организацией является Logos Collective Association, которая имеет зарегистрированный офис в Цуге и юридический адрес: ``` Logos Collective Association @@ -23,74 +23,74 @@ Baarerstrasse 10 Switzerland ``` -Whenever we refer to "Logos", "we", "us" or any other similar references, we are referring to the Logos Collective Association. +Всякий раз, когда мы ссылаемся на "Logos", "мы", "нас" или любые другие подобные ссылки, мы имеем в виду Logos Collective Association. -### 2) Disclaimers +### 2) Отказ от ответственности -The Website is provided by us on an ‘as is’ basis and you use the Website at your own sole discretion and risk. +Веб-сайт предоставляется нами на условиях "как есть", и вы используете веб-сайт на свой собственный риск. -We disclaim all warranties of any kind, express or implied, including without limitation the warranties of merchantability, fitness for a particular purpose, and non-infringement of intellectual property or other violation of rights. We do not warrant or make any representations concerning the completeness, accuracy, legality, utility, reliability, suitability or availability of the use of the Website, the content on this Website or otherwise relating to the Website, such content or on any sites linked to this site.These disclaimers will apply to the maximum extent permitted by applicable law. +Мы отказываемся от всех гарантий любого рода, явных или подразумеваемых, включая, помимо прочего, гарантии товарности, пригодности для определенной цели и ненарушения прав интеллектуальной собственности или других прав. Мы не гарантируем и не делаем никаких заявлений относительно полноты, точности, законности, полезности, надежности, пригодности или доступности использования веб-сайта, контента на этом веб-сайте или иным образом связанного с веб-сайтом, такого контента или любых сайтов, связанных с этим сайтом. Эти отказы от ответственности применяются в максимальной степени, разрешенной применимым законодательством. -We make no claims that the Website or any of its content is accessible, legally compliant or appropriate in your jurisdiction. Your access or use of the Website is at your own sole discretion and you are solely responsible for complying with any applicable local laws. +Мы не заявляем, что веб-сайт или любой его контент доступен, соответствует законодательству или подходит в вашей юрисдикции. Ваш доступ или использование веб-сайта осуществляется на ваш собственный риск, и вы несете единоличную ответственность за соблюдение любых применимых местных законов. -The content herein or as accessible through this website is intended to be made available for informational purposes only and should not be considered as creating any expectations or forming the basis of any contract, commitment or binding obligation with us. No information herein shall be considered to contain or be relied upon as a promise, representation, warranty or guarantee, whether express or implied and whether as to the past, present or the future in relation to the projects and matters described herein. +Контент, содержащийся здесь или доступный через этот веб-сайт, предназначен только для информационных целей и не должен рассматриваться как создающий какие-либо ожидания или формирующий основу любого контракта, обязательства или обязательного обязательства с нами. Никакая информация здесь не должна рассматриваться как содержащая или на которую можно полагаться как на обещание, заявление, гарантию или гарантию, будь то явная или подразумеваемая, и будь то в отношении прошлого, настоящего или будущего в отношении проектов и вопросов, описанных здесь. -The information contained herein does not constitute financial, legal, tax, or other advice and should not be treated as such. +Информация, содержащаяся здесь, не является финансовой, юридической, налоговой или иной консультацией и не должна рассматриваться как таковая. -Nothing in this Website should be construed by you as an offer to buy or sell, or soliciting any offer to buy or sell any tokens or any security. +Ничто на этом веб-сайте не должно толковаться вами как предложение купить или продать, или призыв к предложению купить или продать какие-либо токены или ценные бумаги. -### 3) Forward looking statements +### 3) Прогнозные заявления -The Website may also contain forward-looking statements that are based on current expectations, estimates, forecasts, assumptions and projections about the technology, industry and markets in general. +Веб-сайт также может содержать прогнозные заявления, основанные на текущих ожиданиях, оценках, прогнозах, предположениях и проекциях о технологии, отрасли и рынках в целом. -The forward looking statements, which may include statements about the roadmap, project descriptions, technical details, functionalities, features, the development and use of tokens by projects, and any other statements related to such matters or as accessible through this website are subject to a high degree of risk and uncertainty. The forward looking statements are subject to change based on, among other things, market conditions, technical developments, and regulatory environment. The actual development and results, including the order and the timeline, might vary from what’s presented. The information contained herein is a summary and does not purport to be accurate, reliable or complete and we bear no responsibility for the accuracy, reliability or completeness of information contained herein. Because of the high degree of risk and uncertainty described above, you should not place undue reliance on any matters described in this website or as accessible through this website. +Прогнозные заявления, которые могут включать заявления о дорожной карте, описаниях проектов, технических деталях, функциональности, функциях, разработке и использовании токенов проектами, и любые другие заявления, связанные с такими вопросами или доступные через этот веб-сайт, подвержены высокой степени риска и неопределенности. Прогнозные заявления могут изменяться в зависимости от, среди прочего, рыночных условий, технических разработок и нормативной среды. Фактическая разработка и результаты, включая порядок и сроки, могут отличаться от представленных. Информация, содержащаяся здесь, является кратким изложением и не претендует на точность, надежность или полноту, и мы не несем ответственности за точность, надежность или полноту информации, содержащейся здесь. Из-за высокой степени риска и неопределенности, описанных выше, вы не должны чрезмерно полагаться на любые вопросы, описанные на этом веб-сайте или доступные через этот веб-сайт. -While we aim to update our website regularly, all information, including the timeline and the specifics of each stage, is subject to change and may be amended or supplemented at any time, without notice and at our sole discretion. +Хотя мы стремимся регулярно обновлять наш веб-сайт, вся информация, включая сроки и детали каждого этапа, может быть изменена и может быть изменена или дополнена в любое время без уведомления и по нашему собственному усмотрению. -### 4) Intellectual property rights +### 4) Права интеллектуальной собственности -The Website and its contents are made available under Creative Commons Attribution 4.0 International license (CC-BY 4.0). In essence this licence allows users to copy, modify and distribute the content in any format for any purpose, including commercial use, subject to certain requirements such as attributing us. For the full terms of this licence, please refer to the following website: https://creativecommons.org/licenses/by/4.0/. +Веб-сайт и его содержимое доступны под лицензией Creative Commons Attribution 4.0 International (CC-BY 4.0). По сути, эта лицензия позволяет пользователям копировать, изменять и распространять контент в любом формате для любых целей, включая коммерческое использование, при условии соблюдения определенных требований, таких как указание авторства. Для полных условий этой лицензии, пожалуйста, обратитесь к следующему веб-сайту: https://creativecommons.org/licenses/by/4.0/. -### 5) Third party website links +### 5) Ссылки на сторонние веб-сайты -To the extent the Website provides any links to a third party website, then their terms and conditions, including privacy policies, govern your use of those third party websites. By linking such third party websites, Status does not represent or imply that it endorses or supports such third party websites or content therein, or that it believes such third party websites and content therein to be accurate, useful or non-harmful. We have no control over such third party websites and will not be liable for your use of or activities on any third party websites accessed through the Website. If you access such third party websites through the Website, it is at your own risk and you are solely responsible for your activities on such third party websites. +В той степени, в которой веб-сайт предоставляет какие-либо ссылки на сторонний веб-сайт, их условия и положения, включая политики конфиденциальности, регулируют ваше использование этих сторонних веб-сайтов. Ссылаясь на такие сторонние веб-сайты, Status не представляет и не подразумевает, что он поддерживает такие сторонние веб-сайты или контент на них, или что он считает такие сторонние веб-сайты и контент на них точными, полезными или безвредными. Мы не контролируем такие сторонние веб-сайты и не несем ответственности за ваше использование или действия на любых сторонних веб-сайтах, доступ к которым осуществляется через веб-сайт. Если вы получаете доступ к таким сторонним веб-сайтам через веб-сайт, это происходит на ваш собственный риск, и вы несете единоличную ответственность за свои действия на таких сторонних веб-сайтах. -### 6) Limitation of liability +### 6) Ограничение ответственности -We will not be held liable to you under any contract, negligence, strict liability, or other legal or equitable theory for any lost profits, cost of procurement for substitute services, or any special, incidental, or consequential damages related to, arising from, or in any way connected with these Website Terms of Use, the Website, the content on the Website, or your use of the Website, even if we have been advised of the possibility of such damages. In any event, our aggregate liability for such claims is limited to EUR 100 (one hundred Euros). This limitation of liability will apply to the maximum extent permitted by applicable law. +Мы не несем ответственности перед вами по любому контракту, небрежности, строгой ответственности или любой другой правовой или справедливой теории за любые упущенные выгоды, стоимость приобретения замещающих услуг или любые специальные, случайные или косвенные убытки, связанные с, возникающие из или каким-либо образом связанные с настоящими Условиями использования веб-сайта, веб-сайтом, контентом на веб-сайте или вашим использованием веб-сайта, даже если мы были уведомлены о возможности таких убытков. В любом случае наша совокупная ответственность за такие претензии ограничена 100 евро (сто евро). Это ограничение ответственности применяется в максимальной степени, разрешенной применимым законодательством. -### 7) Indemnity +### 7) Возмещение убытков -You shall indemnify us and hold us harmless from and against any and all claims, damages and expenses, including attorneys’ fees, arising from or related to your use of the Website, the content on the Website, including without limitation your violation of these Website Terms of Use. +Вы должны возместить нам убытки и защитить нас от любых и всех претензий, убытков и расходов, включая гонорары адвокатов, возникающих в связи с или связанных с вашим использованием веб-сайта, контентом на веб-сайте, включая, помимо прочего, ваше нарушение настоящих Условий использования веб-сайта. -### 8) Modifications +### 8) Изменения -We may modify or replace any part of this Website Terms of Use at any time and without notice. You are responsible for checking the Website periodically for any changes. The new Website Terms of Use will be effective immediately upon its posting on the Website. +Мы можем изменить или заменить любую часть настоящих Условий использования веб-сайта в любое время и без уведомления. Вы несете ответственность за периодическую проверку веб-сайта на наличие изменений. Новые Условия использования веб-сайта вступают в силу немедленно после их размещения на веб-сайте. -### 9) Governing law +### 9) Применимое право -Swiss law governs these Website Terms of Use and any disputes between you and us, whether in court or arbitration, without regard to conflict of laws provisions. +Швейцарское право регулирует настоящие Условия использования веб-сайта и любые споры между вами и нами, будь то в суде или арбитраже, без учета положений о коллизии законов. -### 10) Disputes +### 10) Споры -In these terms, “dispute” has the broadest meaning enforceable by law and includes any claim you make against or controversy you may have in relation to these Website Terms of Use, the Website, the content on the Website, or your use of the Website. +В этих условиях термин "спор" имеет самое широкое значение, допустимое законом, и включает любую претензию, которую вы предъявляете, или спор, который у вас может возникнуть в отношении настоящих Условий использования веб-сайта, веб-сайта, контента на веб-сайте или вашего использования веб-сайта. -We prefer arbitration over litigation as we believe it meets our principle of resolving disputes in the most effective and cost effective manner. You are bound by the following arbitration clause, which waives your right to litigation and to be heard by a judge. Please note that court review of an arbitration award is limited. You also waive all your rights to a jury trial (if any) in any and all jurisdictions. +Мы предпочитаем арбитраж судебному разбирательству, поскольку считаем, что он соответствует нашему принципу разрешения споров наиболее эффективным и экономически эффективным способом. Вы связаны следующим арбитражным положением, которое отказывает вам в праве на судебное разбирательство и на слушание судьей. Обратите внимание, что судебный пересмотр арбитражного решения ограничен. Вы также отказываетесь от всех своих прав на суд присяжных (если таковые имеются) во всех юрисдикциях. -If a (potential) dispute arises, you must first use your reasonable efforts to resolve it amicably with us. If these efforts do not result in a resolution of such dispute, you shall then send us a written notice of dispute setting out (i) the nature of the dispute, and the claim you are making; and (ii) the remedy you are seeking. +Если возникает (потенциальный) спор, вы должны сначала использовать разумные усилия для его урегулирования с нами. Если эти усилия не приводят к разрешению такого спора, вы должны отправить нам письменное уведомление о споре, в котором указывается (i) характер спора и претензия, которую вы предъявляете; и (ii) средство правовой защиты, которое вы ищете. -If we and you are unable to further resolve this dispute within sixty (60) calendar days of us receiving this notice of dispute, then any such dispute will be referred to and finally resolved by you and us through an arbitration administered by the Swiss Chambers’ Arbitration Institution in accordance with the Swiss Rules of International Arbitration for the time being in force, which rules are deemed to be incorporated herein by reference. The arbitral decision may be enforced in any court. The arbitration will be held in Zug, Switzerland, and may be conducted via video conference virtual/online methods if possible. The tribunal will consist of one arbitrator, and all proceedings as well as communications between the parties will be kept confidential. The language of the arbitration will be in English. Payment of all relevant fees in respect of the arbitration, including filing, administration and arbitrator fees will be in accordance with the Swiss Rules of International Arbitration. +Если мы и вы не сможем разрешить этот спор в течение шестидесяти (60) календарных дней с момента получения нами этого уведомления о споре, то любой такой спор будет передан и окончательно разрешен вами и нами через арбитраж, проводимый Швейцарским арбитражным институтом в соответствии с действующими Швейцарскими правилами международного арбитража, которые считаются включенными здесь посредством ссылки. Арбитражное решение может быть исполнено в любом суде. Арбитраж будет проводиться в Цуге, Швейцария, и может проводиться с помощью видеоконференции виртуальными/онлайн методами, если это возможно. Трибунал будет состоять из одного арбитра, и все разбирательства, а также переписка между сторонами будут конфиденциальными. Языком арбитража будет английский. Оплата всех соответствующих сборов в отношении арбитража, включая подачу, администрирование и гонорары арбитра, будет осуществляться в соответствии с Швейцарскими правилами международного арбитража. -Regardless of any applicable statute of limitations, you must bring any claims within one year after the claim arose or the time when you should have reasonably known about the claim. You also waive the right to participate in a class action lawsuit or a classwide arbitration against us. +Независимо от любого применимого срока исковой давности, вы должны предъявить любые претензии в течение одного года после возникновения претензии или времени, когда вы должны были разумно узнать о претензии. Вы также отказываетесь от права участвовать в коллективном иске или коллективном арбитраже против нас. -### 11) About these Website Terms of Use +### 11) О настоящих Условиях использования веб-сайта -These Website Terms of Use cover the entire agreement between you and us regarding the Website and supersede all prior and contemporaneous understandings, agreements, representations and warranties, both written and oral, with respect to the Website. +Настоящие Условия использования веб-сайта охватывают все соглашение между вами и нами в отношении веб-сайта и заменяют все предыдущие и современные договоренности, соглашения, заявления и гарантии, как письменные, так и устные, в отношении веб-сайта. -The captions and headings identifying sections and subsections of these Website Terms of Use are for reference only and do not define, modify, expand, limit, or affect the interpretation of any provisions of these Website Terms of Use. +Заголовки и подзаголовки, идентифицирующие разделы и подразделы настоящих Условий использования веб-сайта, предназначены только для справки и не определяют, не изменяют, не расширяют, не ограничивают и не влияют на толкование каких-либо положений настоящих Условий использования веб-сайта. -If any part of these Website Terms of Use is held invalid or unenforceable, that part will be severable from these Website Terms of Use, and the remaining portions will remain in full force and effect. If we fail to enforce any of these Website Terms of Use, that does not mean that we have waived our right to enforce them. +Если какая-либо часть настоящих Условий использования веб-сайта признана недействительной или не имеющей исковой силы, эта часть будет отделима от настоящих Условий использования веб-сайта, а оставшиеся части останутся в полной силе и действии. Если мы не применяем какие-либо из настоящих Условий использования веб-сайта, это не означает, что мы отказались от нашего права применять их. -If you have any specific questions about these Website Terms of Use, please contact us at llegal@free.technology. +Если у вас есть какие-либо конкретные вопросы о настоящих Условиях использования веб-сайта, пожалуйста, свяжитесь с нами по адресу legal@free.technology. This document is licensed under CC-BY-SA. diff --git a/developers/api.md b/developers/api.md index 4df2651..e37f0b9 100644 --- a/developers/api.md +++ b/developers/api.md @@ -1,5 +1,5 @@ -# Codex API +# API Codex - Codex uses REST API to interact with the node and we can use HTTP client for interaction and configuration. +Codex использует REST API для взаимодействия с узлом, и мы можем использовать HTTP-клиент для взаимодействия и настройки. - API specification can be found on the [api.codex.storage](https://api.codex.storage) and it is generated based on [openapi.yaml](https://github.com/codex-storage/nim-codex/blob/master/openapi.yaml). We also generate a [Postman Collection](https://api.codex.storage/postman.json). +Спецификация API доступна на [api.codex.storage](https://api.codex.storage) и генерируется на основе [openapi.yaml](https://github.com/codex-storage/nim-codex/blob/master/openapi.yaml). Мы также генерируем [Postman Collection](https://api.codex.storage/postman.json). diff --git a/learn/architecture.md b/learn/architecture.md index d6e8341..32d5090 100644 --- a/learn/architecture.md +++ b/learn/architecture.md @@ -1,123 +1,86 @@ -# Description and architecture +# Описание и архитектура -Codex is building a durable data storage engine that is fully decentralised, providing corruption and censorship resistance to web3 applications. It innately protects network participants by giving hosts plausible deniability over the data they store, and clients provable durability guarantees—up to 99.99%—while remaining storage and bandwidth efficient. +Codex создает надежный механизм хранения данных, который полностью децентрализован и обеспечивает устойчивость к коррупции и цензуре для web3-приложений. Он изначально защищает участников сети, предоставляя хостам правдоподобное отрицание ответственности за хранимые ими данные, а клиентам - доказуемые гарантии долговечности - до 99,99%, оставаясь при этом эффективным с точки зрения хранения и пропускной способности. -These four key features combine to differentiate Codex from existing projects in the decentralised storage niche: +Эти четыре ключевые особенности объединяются, чтобы отличить Codex от существующих проектов в нише децентрализованного хранения: -- **Erasure coding:** Provides efficient data redundancy, which increases data durability guarantees. +- **Кодирование с исправлением ошибок:** Обеспечивает эффективную избыточность данных, что повышает гарантии долговечности данных. -- **ZK-based proof-of-retrievability:** For lightweight data durability assurances. +- **Доказательство извлекаемости на основе ZK:** Для легких гарантий долговечности данных. -- **Lazy repair mechanism:** For efficient data reconstruction and loss prevention. +- **Механизм ленивого восстановления:** Для эффективного восстановления данных и предотвращения потерь. -- **Incentivization:** To encourage rational behaviour, widespread network participation, and the efficient provision of finite network resources. +- **Стимулирование:** Для поощрения рационального поведения, широкого участия в сети и эффективного предоставления ограниченных сетевых ресурсов. +### Стимулируемая децентрализация -### Incentivized decentralisation +Механизмы стимулирования - это один из ключевых элементов, отсутствующих в традиционных файлообменных сетях. Codex считает, что надежная структура стимулирования на основе рынка обеспечит широкое участие всех типов узлов, описанных ниже. -Incentivization mechanisms are one of the key pieces missing from traditional file-sharing networks. Codex believes that a robust marketplace-based incentive structure will ensure wide participation across the node types detailed below. +Разработка адекватной структуры стимулирования обусловлена следующими целями: -The development of an adequate incentive structure is driven by the following goals: +- Спрос и предложение для поощрения оптимального использования сетевых ресурсов. -- Supply and demand to encourage optimum network resource usage. +- Увеличение участия путем предоставления узлам возможности использовать свои конкурентные преимущества для максимизации прибыли. -- Increase participation by enabling nodes to utilise their competitive advantages to maximise profits. +- Предотвращение спама и сдерживание вредоносного участия. -- Prevent spam and discourage malicious participation. +Хотя структура стимулирования Codex еще не окончательно определена, она будет включать рынок участников, желающих хранить данные, и тех, кто предоставляет хранилище, размещающих залог, причем последние будут делать ставки на открытые контракты на хранение. Эта структура направлена на обеспечение согласования стимулов участников, в результате чего Codex будет функционировать как задумано. -Although still to be finalised, the Codex incentive structure will involve a marketplace of participants who want to store data, and those provisioning storage posting collateral, with the latter bidding on open storage contracts. This structure aims to ensure that participants' incentives align, resulting in Codex functioning as intended. +### Сетевая архитектура +Codex состоит из нескольких типов узлов, каждый из которых выполняет свою роль в работе сети. Аналогично, требования к оборудованию для каждого типа узла различаются, что позволяет участвовать тем, кто использует устройства с ограниченными ресурсами. -### Network architecture +**Узлы хранения** -Codex is composed of multiple node types, each taking a different role in the network's operation. Similarly, the hardware demands for each node type vary, enabling those operating resource-restricted devices to participate. +Как надежные поставщики долгосрочного хранения Codex, узлы хранения размещают залог на основе залога, размещенного на стороне запроса контрактов, и количества слотов, которые имеет контракт. Это связано с долговечностью, требуемой пользователем. Непредоставление периодических доказательств владения данными приводит к штрафам за сокращение. -**Storage nodes** +**Узел-агрегатор** -As Codex's long-term reliable storage providers, storage nodes stake collateral based on the collateral posted on the request side of contracts, and the number of slots that a contract has. This is tied to the durability demanded by the user. Failure to provide periodic proof of data possession results in slashing penalties. +Метод разгрузки кодирования с исправлением ошибок, генерации доказательств и агрегации доказательств клиентским узлом с низкими ресурсами, в настоящее время находится в разработке и будет частью следующего выпуска Codex во втором/четвертом квартале следующего года. -**Aggregator Node** +**Клиентские узлы** -A method for off-loading erasure coding, proof generation and proof aggregation by a client node with low-resources, currently a WIP and will be part of subsequent Codex release Q2/Q4 next year. +Клиентские узлы делают запросы к другим узлам на хранение, поиск и извлечение данных. Большая часть сети Codex будет состоять из клиентских узлов, и эти участники могут одновременно выступать в качестве кэширующих узлов для компенсации стоимости потребляемых сетевых ресурсов. -**Client nodes** +Когда узел берет на себя обязательство по контракту на хранение и пользователь загружает данные, сеть будет активно проверять, что узел хранения находится в сети и что данные доступны для извлечения. Затем узлы хранения случайным образом опрашиваются для передачи доказательств владения данными в течение интервала, соответствующего продолжительности контракта и гарантии извлекаемости, которую предоставляет протокол. -Client nodes make requests for other nodes to store, find, and retrieve data. Most of the Codex network will be Client nodes, and these participants can double as caching nodes to offset the cost of the network resources they consume. +Если узел хранения отправляет недействительные доказательства или не предоставляет их вовремя, сеть исключает узел хранения из слота, и слот станет доступным для первого узла, который сгенерирует действительное доказательство для этого слота. -When a node commits to a storage contract and a user uploads data, the network will proactively verify that the storage node is online and that the data is retrievable. Storage nodes are then randomly queried to broadcast proofs of data possession over an interval corresponding to the contract duration and 9's of retrievability guarantee the protocol provides. +Когда контракт перепубликуется, часть залога неисправного узла оплачивает комиссию за пропускную способность нового узла хранения. Кодирование с исправлением ошибок дополняет схему восстановления, позволяя восстанавливать отсутствующие фрагменты из данных в других слотах в рамках того же контракта на хранение, размещенного на безупречных узлах хранения. -If the storage node sends invalid proofs or fails to provide them in time, the network evicts the storage node from the slot, and the slot will become available for the first node that generates a valid proof for that slot. +![архитектура](/learn/architecture.png) -When the contract is reposted, some of the faulty node's collateral pays for the new storage node's bandwidth fees. Erasure coding complements the repair scheme by allowing the reconstruction of the missing chunks from data in other slots within the same storage contract hosted by faultless storage nodes. +### Архитектура рынка ### +Рынок состоит из смарт-контракта, развернутого в блокчейне, и модулей покупки и продажи, которые являются частью программного обеспечения узла. Модуль покупки отвечает за размещение запросов на хранение в смарт-контракте. Модуль продаж является его аналогом, который поставщики хранилищ используют для определения того, какие запросы на хранение их интересуют. -![architect](/learn/architecture.png) +#### Смарт-контракт #### -### Marketplace architecture ### +Смарт-контракт облегчает сопоставление между поставщиками хранилищ и клиентами хранилищ. Клиент хранилища может запросить определенный объем хранилища на определенный срок. Этот запрос затем размещается в блокчейне, чтобы поставщики хранилищ могли его увидеть и решить, хотят ли они заполнить слот в запросе. -The marketplace consists of a smart contract that is deployed on-chain, and the -purchasing and sales modules that are part of the node software. The purchasing -module is responsible for posting storage requests to the smart contract. The -sales module is its counterpart that storage providers use to determine which -storage requests they are interested in. +Основные параметры запроса на хранение: +- количество байтов хранилища, которое запрашивается +- идентификатор контента (CID) данных, которые должны быть сохранены +- срок, на который должны быть сохранены данные +- количество слотов (на основе параметров кодирования с исправлением ошибок) +- количество токенов для оплаты хранения -#### Smart contract #### +На уровне протокола клиент хранилища свободен в определении этих параметров по своему усмотрению, чтобы он мог выбрать уровень долговечности, подходящий для данных, и скорректировать его с учетом изменяющихся цен на хранение. Приложения, построенные на Codex, могут предоставлять рекомендации своим пользователям по выбору правильных параметров, аналогично тому, как кошельки Ethereum помогают с определением комиссий за газ. -The smart contract facilitates matching between storage providers and storage -clients. A storage client can request a certain amount of storage for a certain -duration. This request is then posted on-chain, so that storage providers can -see it, and decide whether they want to fill a slot in the request. +Смарт-контракт также проверяет, что поставщики хранилищ выполняют свои обещания. Поставщики хранилищ размещают залог, когда обещают заполнить слот запроса на хранение. От них ожидается предоставление периодических доказательств хранения в контракт, либо напрямую, либо через агрегатор. Если они неоднократно не делают этого, их залог может быть конфискован. Их слот затем присуждается другому поставщику хранилищ. -The main parameters of a storage request are: -- the amount of bytes of storage that is requested -- a content identifier (CID) of the data that should be stored -- the duration for which the data should be stored -- the number of slots (based on the erasure coding parameters) -- an amount of tokens to pay for the storage +Смарт-контракт указывает, когда определенный поставщик хранилищ должен предоставить доказательство хранения. Это делается не с фиксированным интервалом времени, а определяется стохастически, чтобы гарантировать, что поставщик хранилищ не может предсказать, когда он должен предоставить следующее доказательство хранения. -At the protocol level a storage client is free to determine these parameters as -it sees fit, so that it can choose a level of durability that is suitable for -the data, and adjust for changing storage prices. Applications built on Codex -can provide guidance to their users for picking the correct parameters, -analogous to how Ethereum wallets help with determining gas fees. +#### Покупка #### -The smart contract also checks that storage providers keep their promises. -Storage providers post collateral when they promise to fill a slot of a storage -request. They are expected to post periodic storage proofs to the contract, -either directly or through an aggregator. If they fail to do so repeatedly, then -their collateral can be forfeited. Their slot is then awarded to another storage -provider. +Модуль покупки в программном обеспечении узла взаимодействует со смарт-контрактом от имени оператора узла. Он размещает запросы на хранение и обрабатывает любые другие взаимодействия, которые требуются в течение срока действия запроса. Например, когда запрос отменяется из-за недостаточного количества заинтересованных поставщиков хранилищ, модуль покупки может вывести токены, связанные с запросом. -The smart contract indicates when a certain storage provider has to provide a -storage proof. This is not done on a fixed time interval, but determined -stochastically to ensure that it is not possible for a storage provider to -predict when it should provide the next storage proof. +#### Продажи #### -#### Purchasing #### +Модуль продаж является аналогом модуля продаж. Он отслеживает смарт-контракт, чтобы получать уведомления о входящих запросах на хранение. Он ведет список наиболее перспективных запросов, которые он может выполнить. Он будет отдавать предпочтение тем запросам, которые имеют высокое вознаграждение и низкий залог. Как только он найдет подходящий запрос, он попытается сначала зарезервировать, а затем заполнить слот, загрузив связанные данные, создав доказательство хранения и разместив его в смарт-контракте. Затем он продолжит отслеживать смарт-контракт, чтобы предоставлять ему доказательства хранения, когда они потребуются. -The purchasing module in the node software interacts with the smart contract on -behalf of the node operator. It posts storage requests, and handles any other -interactions that are required during the lifetime of the request. For instance, -when a request is canceled because there are not enough interested storage -providers, then the purchasing module can withdraw the tokens that were -associated with the request. +Модуль продаж содержит стратегию максимальных усилий для определения того, какие запросы на хранение его интересуют. Со временем мы ожидаем появления более специализированных стратегий для удовлетворения потребностей, например, крупных поставщиков по сравнению с поставщиками, которые запускают узел из дома. -#### Sales #### +### Белая книга ### -The sales module is the counterpart to the sales module. It monitors the smart -contract to be notified of incoming storage requests. It keeps a list of the -most promising requests that it can fulfill. It will favor those requests that -have a high reward and low collateral. As soon as it finds a suitable request, -it will then try to first reserve and then fill a slot by downloading the -associated data, creating a storage proof, and posting it to the smart contract. -It will then continue to monitor the smart contract to provide it with storage -proofs when they are required. - -The sales module contains a best effort strategy for determining which storage -requests it is interested in. Over time, we expect more specialized strategies -to emerge to cater to the needs of e.g. large providers versus providers that -run a node from their home. - -### Whitepaper ### - -Read the [Codex whitepaper](/learn/whitepaper) +Прочитайте [белую книгу Codex](/learn/whitepaper) diff --git a/learn/build.md b/learn/build.md index fa5f538..9ef9e78 100644 --- a/learn/build.md +++ b/learn/build.md @@ -1,83 +1,80 @@ -# Build Codex +# Сборка Codex -## Table of Contents +## Содержание -- [Install developer tools](#prerequisites) +- [Установка инструментов разработчика](#prerequisites) - [Linux](#linux) - [macOS](#macos) - [Windows + MSYS2](#windows-msys2) - - [Other](#other) -- [Clone and prepare the Git repository](#repository) -- [Build the executable](#executable) -- [Run the example](#example-usage) + - [Другие](#other) +- [Клонирование и подготовка Git-репозитория](#repository) +- [Сборка исполняемого файла](#executable) +- [Запуск примера](#example-usage) -**Optional** -- [Run the tests](#tests) +**Дополнительно** +- [Запуск тестов](#tests) -## Prerequisites +## Предварительные требования -To build nim-codex, developer tools need to be installed and accessible in the OS. +Для сборки nim-codex необходимо установить и сделать доступными инструменты разработчика в операционной системе. -Instructions below correspond roughly to environmental setups in nim-codex's [CI workflow](https://github.com/codex-storage/nim-codex/blob/master/.github/workflows/ci.yml) and are known to work. +Инструкции ниже примерно соответствуют настройкам окружения в [CI workflow](https://github.com/codex-storage/nim-codex/blob/master/.github/workflows/ci.yml) nim-codex и известны как рабочие. -Other approaches may be viable. On macOS, some users may prefer [MacPorts](https://www.macports.org/) to [Homebrew](https://brew.sh/). On Windows, rather than use MSYS2, some users may prefer to install developer tools with [winget](https://docs.microsoft.com/en-us/windows/package-manager/winget/), [Scoop](https://scoop.sh/), or [Chocolatey](https://chocolatey.org/), or download installers for e.g. Make and CMake while otherwise relying on official Windows developer tools. Community contributions to these docs and our build system are welcome! +Другие подходы могут быть жизнеспособны. На macOS некоторые пользователи могут предпочесть [MacPorts](https://www.macports.org/) вместо [Homebrew](https://brew.sh/). На Windows вместо MSYS2 некоторые пользователи могут предпочесть установку инструментов разработчика с помощью [winget](https://docs.microsoft.com/en-us/windows/package-manager/winget/), [Scoop](https://scoop.sh/) или [Chocolatey](https://chocolatey.org/), или загрузку установщиков для, например, Make и CMake, в остальном полагаясь на официальные инструменты разработчика Windows. Приветствуются вклады сообщества в эти документы и нашу систему сборки! ### Rust -The current implementation of Codex's zero-knowledge proving circuit requires the installation of rust v1.79.0 or greater. Be sure to install it for your OS and add it to your terminal's path such that the command `cargo --version` gives a compatible version. +Текущая реализация схемы доказательств с нулевым разглашением Codex требует установки Rust версии 1.79.0 или выше. Убедитесь, что вы установили его для вашей ОС и добавили в PATH вашего терминала так, чтобы команда `cargo --version` показывала совместимую версию. ### Linux > [!WARNING] -> Linux builds currently require gcc $\leq$ 13. If this is not an option in your -> system, you can try [building within Docker](#building-within-docker) as a workaround. +> Сборка в Linux в настоящее время требует gcc $\leq$ 13. Если это не вариант в вашей системе, вы можете попробовать [сборку в Docker](#building-within-docker) как обходной путь. -*Package manager commands may require `sudo` depending on OS setup.* +*Команды менеджера пакетов могут требовать `sudo` в зависимости от настройки ОС.* -On a bare bones installation of Debian (or a distribution derived from Debian, such as Ubuntu), run +На базовой установке Debian (или дистрибутива, производного от Debian, такого как Ubuntu), выполните ```shell apt-get update && apt-get install build-essential cmake curl git rustc cargo ``` -Non-Debian distributions have different package managers: `apk`, `dnf`, `pacman`, `rpm`, `yum`, etc. +Не-Debian дистрибутивы имеют разные менеджеры пакетов: `apk`, `dnf`, `pacman`, `rpm`, `yum` и т.д. -For example, on a bare bones installation of Fedora, run +Например, на базовой установке Fedora выполните ```shell dnf install @development-tools cmake gcc-c++ rust cargo ``` -In case your distribution does not provide required Rust version, we may install it using [rustup](https://www.rust-lang.org/tools/install) +В случае, если ваш дистрибутив не предоставляет требуемую версию Rust, мы можем установить её с помощью [rustup](https://www.rust-lang.org/tools/install) ```shell curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs/ | sh -s -- --default-toolchain=1.79.0 -y . "$HOME/.cargo/env" ``` -Note that you will currently not be able to build Codex with gcc 14. To verify that -you have a supported version, run: +Обратите внимание, что в настоящее время вы не сможете собрать Codex с gcc 14. Чтобы проверить, что у вас поддерживаемая версия, выполните: ```shell gcc --version ``` -If you get a number that starts with 14 (e.g. `14.2.0`), then you need to either -downgrade, or try a workaround like [building within Docker](#building-within-docker). +Если вы получите число, начинающееся с 14 (например, `14.2.0`), то вам нужно либо понизить версию, либо попробовать обходной путь, например [сборку в Docker](#building-within-docker). ### macOS -Install the [Xcode Command Line Tools](https://mac.install.guide/commandlinetools/index.html) by opening a terminal and running +Установите [Xcode Command Line Tools](https://mac.install.guide/commandlinetools/index.html), открыв терминал и выполнив ```shell xcode-select --install ``` -Install [Homebrew (`brew`)](https://brew.sh/) and in a new terminal run +Установите [Homebrew (`brew`)](https://brew.sh/) и в новом терминале выполните ```shell brew install bash cmake rust ``` -Check that `PATH` is setup correctly +Проверьте, что `PATH` настроен правильно ```shell which bash cmake @@ -87,33 +84,29 @@ which bash cmake ### Windows + MSYS2 -*Instructions below assume the OS is 64-bit Windows and that the hardware or VM is [x86-64](https://en.wikipedia.org/wiki/X86-64) compatible.* +*Инструкции ниже предполагают, что ОС - 64-битная Windows и что оборудование или ВМ совместимо с [x86-64](https://en.wikipedia.org/wiki/X86-64).* -Download and run the installer from [msys2.org](https://www.msys2.org/). +Скачайте и запустите установщик с [msys2.org](https://www.msys2.org/). -Launch an MSYS2 [environment](https://www.msys2.org/docs/environments/). UCRT64 is generally recommended: from the Windows *Start menu* select `MSYS2 MinGW UCRT x64`. +Запустите среду MSYS2 [environment](https://www.msys2.org/docs/environments/). UCRT64 обычно рекомендуется: из меню *Пуск* Windows выберите `MSYS2 MinGW UCRT x64`. -Assuming a UCRT64 environment, in Bash run +Предполагая среду UCRT64, в Bash выполните ```shell pacman -Suy pacman -S base-devel git unzip mingw-w64-ucrt-x86_64-toolchain mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-rust ``` -We should downgrade GCC to version 13 [^gcc-14] +Нам следует понизить GCC до версии 13 [^gcc-14] ```shell pacman -U --noconfirm \ https://repo.msys2.org/mingw/ucrt64/mingw-w64-ucrt-x86_64-gcc-13.2.0-6-any.pkg.tar.zst \ https://repo.msys2.org/mingw/ucrt64/mingw-w64-ucrt-x86_64-gcc-libs-13.2.0-6-any.pkg.tar.zst ``` - - - +#### Опционально: Интеграция с терминалом VSCode -#### Optional: VSCode Terminal integration - -You can link the MSYS2-UCRT64 terminal into VSCode by modifying the configuration file as shown below. -File: `C:/Users//AppData/Roaming/Code/User/settings.json` +Вы можете связать терминал MSYS2-UCRT64 с VSCode, изменив файл конфигурации, как показано ниже. +Файл: `C:/Users//AppData/Roaming/Code/User/settings.json` ```json { ... @@ -135,111 +128,111 @@ File: `C:/Users//AppData/Roaming/Code/User/settings.json` } ``` -### Other +### Другие -It is possible that nim-codex can be built and run on other platforms supported by the [Nim](https://nim-lang.org/) language: BSD family, older versions of Windows, etc. There has not been sufficient experimentation with nim-codex on such platforms, so instructions are not provided. Community contributions to these docs and our build system are welcome! +Возможно, что nim-codex может быть собран и запущен на других платформах, поддерживаемых языком [Nim](https://nim-lang.org/): семейство BSD, более старые версии Windows и т.д. Не было достаточного экспериментирования с nim-codex на таких платформах, поэтому инструкции не предоставляются. Приветствуются вклады сообщества в эти документы и нашу систему сборки! -## Repository +## Репозиторий -In Bash run +В Bash выполните ```shell git clone https://github.com/codex-storage/nim-codex.git repos/nim-codex && cd repos/nim-codex ``` -nim-codex uses the [nimbus-build-system](https://github.com/status-im/nimbus-build-system), so next run +nim-codex использует [nimbus-build-system](https://github.com/status-im/nimbus-build-system), поэтому затем выполните ```shell make update ``` -This step can take a while to complete because by default it builds the [Nim compiler](https://nim-lang.org/docs/nimc.html). +Этот шаг может занять некоторое время для завершения, потому что по умолчанию он собирает [компилятор Nim](https://nim-lang.org/docs/nimc.html). -To see more output from `make` pass `V=1`. This works for all `make` targets in projects using the nimbus-build-system +Чтобы увидеть больше вывода от `make`, передайте `V=1`. Это работает для всех целей `make` в проектах, использующих nimbus-build-system ```shell make V=1 update ``` -## Executable +## Исполняемый файл -In Bash run +В Bash выполните ```shell make ``` -The default `make` target creates the `build/codex` executable. +Цель `make` по умолчанию создает исполняемый файл `build/codex`. -## Tools +## Инструменты -### Circuit download tool +### Инструмент загрузки схемы -To build the circuit download tool located in `tools/cirdl` run: +Чтобы собрать инструмент загрузки схемы, расположенный в `tools/cirdl`, выполните: ```shell make cirdl ``` -## Example usage +## Пример использования -See the instructions in the [Quick Start](/learn/quick-start). +См. инструкции в [Быстром старте](/learn/quick-start). -## Tests +## Тесты -In Bash run +В Bash выполните ```shell make test ``` ### testAll -#### Prerequisites +#### Предварительные требования -To run the integration tests, an Ethereum test node is required. Follow these instructions to set it up. +Для запуска интеграционных тестов требуется тестовый узел Ethereum. Следуйте этим инструкциям для его настройки. -##### Windows (do this before 'All platforms') +##### Windows (сделайте это перед "Все платформы") -1. Download and install Visual Studio 2017 or newer. (Not VSCode!) In the Workloads overview, enable `Desktop development with C++`. ( https://visualstudio.microsoft.com ) +1. Скачайте и установите Visual Studio 2017 или новее. (Не VSCode!) В обзоре рабочих нагрузок включите `Desktop development with C++`. ( https://visualstudio.microsoft.com ) -##### All platforms +##### Все платформы -1. Install NodeJS (tested with v18.14.0), consider using NVM as a version manager. [Node Version Manager (`nvm`)](https://github.com/nvm-sh/nvm#readme) -1. Open a terminal -1. Go to the vendor/codex-contracts-eth folder: `cd //vendor/codex-contracts-eth/` -1. `npm install` -> Should complete with the number of packages added and an overview of known vulnerabilities. -1. `npm test` -> Should output test results. May take a minute. +1. Установите NodeJS (проверено с v18.14.0), рассмотрите использование NVM как менеджера версий. [Node Version Manager (`nvm`)](https://github.com/nvm-sh/nvm#readme) +1. Откройте терминал +1. Перейдите в папку vendor/codex-contracts-eth: `cd //vendor/codex-contracts-eth/` +1. `npm install` -> Должно завершиться с количеством добавленных пакетов и обзором известных уязвимостей. +1. `npm test` -> Должен вывести результаты тестов. Может занять минуту. -Before the integration tests are started, you must start the Ethereum test node manually. -1. Open a terminal -1. Go to the vendor/codex-contracts-eth folder: `cd //vendor/codex-contracts-eth/` -1. `npm start` -> This should launch Hardhat, and output a number of keys and a warning message. +Перед запуском интеграционных тестов вы должны вручную запустить тестовый узел Ethereum. +1. Откройте терминал +1. Перейдите в папку vendor/codex-contracts-eth: `cd //vendor/codex-contracts-eth/` +1. `npm start` -> Это должно запустить Hardhat и вывести ряд ключей и предупреждающее сообщение. -#### Run +#### Запуск -The `testAll` target runs the same tests as `make test` and also runs tests for nim-codex's Ethereum contracts, as well a basic suite of integration tests. +Цель `testAll` запускает те же тесты, что и `make test`, а также запускает тесты для контрактов Ethereum nim-codex, а также базовый набор интеграционных тестов. -To run `make testAll`. +Чтобы запустить `make testAll`. -Use a new terminal to run: +Используйте новый терминал для запуска: ```shell make testAll ``` -## Building Within Docker +## Сборка в Docker -For the specific case of Linux distributions which ship with gcc 14 -and a downgrade to 13 is not possible/desirable, building within a Docker -container and pulling the binaries out by copying or mounting remains an -option; e.g.: +Для конкретного случая дистрибутивов Linux, которые поставляются с gcc 14 +и понижение до 13 невозможно/нежелательно, сборка в контейнере Docker +и извлечение бинарных файлов путем копирования или монтирования остается +вариантом; например: ```bash= -# Clone original repo. +# Клонировать оригинальный репозиторий. git clone https://github.com/codex-storage/nim-codex -# Build inside docker +# Собрать внутри docker docker build -t codexstorage/nim-codex:latest -f nim-codex/docker/codex.Dockerfile nim-codex -# Extract executable +# Извлечь исполняемый файл docker create --name=codex-build codexstorage/nim-codex:latest docker cp codex-build:/usr/local/bin/codex ./codex docker cp codex-build:/usr/local/bin/cirdl ./cirdl ``` -and voilà, you should have the binaries available in the current folder. +и вуаля, у вас должны быть бинарные файлы доступны в текущей папке. diff --git a/learn/download-flow.md b/learn/download-flow.md index f8dec92..346627a 100644 --- a/learn/download-flow.md +++ b/learn/download-flow.md @@ -1,8 +1,8 @@ -# Download Flow -Sequence of interactions that result in dat blocks being transferred across the network. +# Процесс загрузки +Последовательность взаимодействий, приводящих к передаче блоков данных через сеть. -## Local Store -When data is available in the local blockstore, +## Локальное хранилище +Когда данные доступны в локальном хранилище блоков, ```mermaid sequenceDiagram @@ -21,8 +21,8 @@ Node/StoreStream->>-API: Data stream API->>Alice: Stream download of block ``` -## Network Store -When data is not found ih the local blockstore, the block-exchange engine is used to discover the location of the block within the network. Connection will be established to the node(s) that have the block, and exchange can take place. +## Сетевое хранилище +Когда данные не найдены в локальном хранилище блоков, используется механизм обмена блоками для обнаружения местоположения блока в сети. Устанавливается соединение с узлом(ами), у которых есть блок, и происходит обмен. ```mermaid sequenceDiagram diff --git a/learn/installer/install-and-run.md b/learn/installer/install-and-run.md index 133ecd9..c0342cf 100644 --- a/learn/installer/install-and-run.md +++ b/learn/installer/install-and-run.md @@ -1,48 +1,48 @@ -# Quick Start +# Быстрый старт -Codex Installer is a CLI tool that simplifies the process of setting up a Codex node. It handles all the necessary steps to get your node running quickly and efficiently. +Codex Installer - это инструмент командной строки, который упрощает процесс настройки узла Codex. Он обрабатывает все необходимые шаги для быстрого и эффективного запуска вашего узла. -> Before we get started, please make sure to review and accept the [disclaimer](/codex/installer-disclaimer) as Codex Installer collects some of your node information to improve the user experience. +> Прежде чем мы начнем, пожалуйста, просмотрите и примите [отказ от ответственности](/codex/installer-disclaimer), так как Codex Installer собирает некоторую информацию о вашем узле для улучшения пользовательского опыта.
-## Requirements +## Требования - git - npm -## Run the Codex Installer +## Запуск Codex Installer -To start the Codex Installer, simply run the following command in your terminal : +Чтобы запустить Codex Installer, просто выполните следующую команду в вашем терминале: ```bash npx codexstorage ``` -## Download and install Codex +## Скачивание и установка Codex -Once you run the above command, you will be seeing a command line interface with various options as below : +После выполнения вышеуказанной команды вы увидите интерфейс командной строки с различными опциями, как показано ниже: ![InstallCodex](/learn/codex-installer.png) -On selecting the `Download and install Codex` option, you will be asked to agree to the privacy disclaimer and provide an installation path to finish your installation. If you do not wish to agree to the data collection disclaimer, you can select the `Exit` option and follow the instructions [Manual setup](/learn/quick-start.md) to install Codex without using the Installer. +При выборе опции `Download and install Codex` вам будет предложено согласиться с отказом от ответственности за конфиденциальность и указать путь установки для завершения установки. Если вы не хотите соглашаться с отказом от ответственности за сбор данных, вы можете выбрать опцию `Exit` и следовать инструкциям [Ручной настройки](/learn/quick-start.md) для установки Codex без использования Installer. -## Run the Codex node +## Запуск узла Codex -Upon selecting the `Run Codex node` option, you will be asked for your Listening port (default is 8070) and discovery port (default is 8090). You can optionally provide your ERC20 public address to associate your testnet node with your wallet (Please note that Codex does not promise any incentives for running a node yet). +При выборе опции `Run Codex node` вам будет предложено указать порт прослушивания (по умолчанию 8070) и порт обнаружения (по умолчанию 8090). Вы можете дополнительно указать ваш публичный адрес ERC20 для привязки вашего тестового узла к вашему кошельку (Обратите внимание, что Codex пока не обещает никаких стимулов за запуск узла). ![RunCodex](/learn/codex-installer2.png) -Keep this terminal window open as closing this will terminate your node. +Держите это окно терминала открытым, так как его закрытие приведет к завершению работы вашего узла. -## Get the *ALTRUISTIC MODE* role on Codex discord +## Получение роли *ALTRUISTIC MODE* в Discord Codex -With that, your Codex node should be up and running. You can check the information and status of your node by proceeding to the third option. +После этого ваш узел Codex должен быть запущен и работать. Вы можете проверить информацию и статус вашего узла, выбрав третью опцию. ![Get Role](/learn/codex-installer3.png) -To claim the *ALTRUISTIC MODE* role, join the [Codex Discord](https://discord.gg/codex-storage) and go to the #bot channel. Run the `/node ` command where `` can be found in the Node Information menu in your Installer. +Чтобы получить роль *ALTRUISTIC MODE*, присоединитесь к [Discord Codex](https://discord.gg/codex-storage) и перейдите в канал #bot. Выполните команду `/node `, где `` можно найти в меню Node Information в вашем Installer. -In order to keep your role, you will be required to frequently interact with the Codex testnet by running your node and/or [uploading/downloading files](/learn/installer/upload-and-download.md) using the testnet. \ No newline at end of file +Чтобы сохранить свою роль, вам потребуется часто взаимодействовать с тестовой сетью Codex, запуская свой узел и/или [загружая/скачивая файлы](/learn/installer/upload-and-download.md) с использованием тестовой сети. \ No newline at end of file diff --git a/learn/installer/requirements.md b/learn/installer/requirements.md index 1f720a7..54e25b4 100644 --- a/learn/installer/requirements.md +++ b/learn/installer/requirements.md @@ -1,23 +1,23 @@ -# Requirements +# Требования -> **Note:** Using the Codex Installer is the recommended only if you agree to provide your node information to make the Codex experience better. If you don't agree to the disclaimer, please consider [setting up Codex manually](/learn/quick-start.md) +> **Примечание:** Использование установщика Codex рекомендуется только в том случае, если вы согласны предоставить информацию о вашем узле для улучшения работы Codex. Если вы не согласны с отказом от ответственности, пожалуйста, рассмотрите возможность [ручной настройки Codex](/learn/quick-start.md)
-To make sure that your Codex node is running smoothly, you will need to make sure that your machine has the following requirements : +Чтобы обеспечить бесперебойную работу вашего узла Codex, необходимо убедиться, что ваша машина соответствует следующим требованиям: -## Dependencies +## Зависимости - git - npm -## Port Forwarding +## Проброс портов -Codex requires two ports to be open on your machine in order to function properly. However, please note that the **ports provided below are configurable** based on your preference : +Для правильной работы Codex требуется, чтобы на вашей машине были открыты два порта. Обратите внимание, что **порты, указанные ниже, настраиваются** в соответствии с вашими предпочтениями: - | Protocol | Service | Port | - | -------- | --------- | ------ | - | UDP | Discovery | Default : `8090` | - | TCP | Transport | Default : `8070` | + | Протокол | Сервис | Порт | + | -------- | ---------- | ------ | + | UDP | Discovery | По умолчанию: `8090` | + | TCP | Transport | По умолчанию: `8070` | -If you are not familiar with port forwarding, you can follow the instructions [here](https://www.noip.com/support/knowledgebase/general-port-forwarding-guide/). \ No newline at end of file +Если вы не знакомы с пробросом портов, вы можете следовать инструкциям [здесь](https://www.noip.com/support/knowledgebase/general-port-forwarding-guide/). \ No newline at end of file diff --git a/learn/installer/upload-and-download.md b/learn/installer/upload-and-download.md index 04f36ff..690d78d 100644 --- a/learn/installer/upload-and-download.md +++ b/learn/installer/upload-and-download.md @@ -1,27 +1,27 @@ -# Upload/Download Files in the Testnet +# Загрузка/Скачивание файлов в тестовой сети -You can either upload or download files by using the Upload / Download option in the Codex Installer or by using the Codex GUI app (recommended). +Вы можете загружать или скачивать файлы, используя опцию Upload / Download в Codex Installer или с помощью приложения Codex GUI (рекомендуется). ## Codex Vault -Codex Vault is a GUI web application that can help you interact with the Codex testnet by uploading and downloading files. Once you have your Codex node running using the installer, you can access the Codex Vault by going to https://app.codex.storage +Codex Vault - это веб-приложение с графическим интерфейсом, которое помогает вам взаимодействовать с тестовой сетью Codex путем загрузки и скачивания файлов. После запуска вашего узла Codex с помощью установщика, вы можете получить доступ к Codex Vault, перейдя по адресу https://app.codex.storage ![Codex Vault](/learn/codex-vault.png) -Ensure that you have all the necessary conditions checked in the 'health check' section before you try uploading or downloading files. +Убедитесь, что все необходимые условия отмечены в разделе 'health check' перед попыткой загрузки или скачивания файлов. -### Uploading and Downloading Files +### Загрузка и скачивание файлов -To upload a file, you can either drag and drop the file to the upload area or click on the 'upload' button. You will be able to find a unique CID for the file once it has been uploaded. +Чтобы загрузить файл, вы можете либо перетащить файл в область загрузки, либо нажать кнопку 'upload'. После загрузки вы сможете найти уникальный CID для файла. -To download a file, enter the CID of the file in the 'download' section and click on the 'download' button. +Чтобы скачать файл, введите CID файла в разделе 'download' и нажмите кнопку 'download'. ![Upload and Download](/learn/upload-download.png) -## What's next? +## Что дальше? -Now that you know how to upload and download files in the testnet, you can try to explore some experimental features and build your own applications on top of Codex : +Теперь, когда вы знаете, как загружать и скачивать файлы в тестовой сети, вы можете попробовать изучить некоторые экспериментальные функции и создать свои собственные приложения на основе Codex: -- [Use Codex REST API](/learn/using) -- [Running Codex with Local Marketplace support](/learn/local-marketplace) -- [Build applications using codex-js Library](https://github.com/codex-storage/codex-js) \ No newline at end of file +- [Использование REST API Codex](/learn/using) +- [Запуск Codex с поддержкой локального маркетплейса](/learn/local-marketplace) +- [Создание приложений с использованием библиотеки codex-js](https://github.com/codex-storage/codex-js) \ No newline at end of file diff --git a/learn/local-marketplace.md b/learn/local-marketplace.md index 352f665..5950591 100644 --- a/learn/local-marketplace.md +++ b/learn/local-marketplace.md @@ -1,56 +1,56 @@ --- outline: [2, 3] --- -# Running a Local Codex Network with Marketplace Support +# Запуск локальной сети Codex с поддержкой маркетплейса -This tutorial will teach you how to run a small Codex network with the -_storage marketplace_ enabled; i.e., the functionality in Codex which -allows participants to offer and buy storage in a market, ensuring that -storage providers honor their part of the deal by means of cryptographic proofs. +Это руководство научит вас, как запустить небольшую сеть Codex с включенным +_маркетплейсом хранения_; т.е. функциональностью в Codex, которая +позволяет участникам предлагать и покупать хранилище на рынке, обеспечивая +честное выполнение обязательств поставщиками хранилища с помощью криптографических доказательств. -In this tutorial, you will: +В этом руководстве вы: -1. [Set Up a Geth PoA network](#_1-set-up-a-geth-poa-network); -2. [Set up The Marketplace](#_2-set-up-the-marketplace); -3. [Run Codex](#_3-run-codex); -4. [Buy and Sell Storage in the Marketplace](#_4-buy-and-sell-storage-on-the-marketplace). +1. [Настроите сеть Geth PoA](#_1-set-up-a-geth-poa-network); +2. [Настроите маркетплейс](#_2-set-up-the-marketplace); +3. [Запустите Codex](#_3-run-codex); +4. [Купите и продайте хранилище на маркетплейсе](#_4-buy-and-sell-storage-on-the-marketplace). -## Prerequisites +## Предварительные требования -To complete this tutorial, you will need: +Для прохождения этого руководства вам понадобится: -* the [geth](https://github.com/ethereum/go-ethereum) Ethereum client; - You need version `1.13.x` of geth as newer versions no longer support - Proof of Authority (PoA). This tutorial was tested using geth version `1.13.15`. -* a Codex binary, which [you can compile from source](https://github.com/codex-storage/nim-codex?tab=readme-ov-file#build-and-run). +* клиент Ethereum [geth](https://github.com/ethereum/go-ethereum); + Вам нужна версия `1.13.x` geth, так как более новые версии больше не поддерживают + Proof of Authority (PoA). Это руководство было протестировано с версией geth `1.13.15`. +* бинарный файл Codex, который [можно собрать из исходного кода](https://github.com/codex-storage/nim-codex?tab=readme-ov-file#build-and-run). -We will also be using [bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) -syntax throughout. If you use a different shell, you may need to adapt -things to your platform. +Мы также будем использовать синтаксис [bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) +на протяжении всего руководства. Если вы используете другую оболочку, вам может потребоваться адаптировать +команды под вашу платформу. -To get started, create a new folder where we will keep the tutorial-related -files so that we can keep them separate from the codex repository. -We assume the name of the folder to be `marketplace-tutorial`. +Для начала создайте новую папку, где мы будем хранить файлы, связанные с руководством, +чтобы держать их отдельно от репозитория codex. +Предположим, что имя папки будет `marketplace-tutorial`. -## 1. Set Up a Geth PoA Network +## 1. Настройка сети Geth PoA -For this tutorial, we will use a simple -[Proof-of-Authority](https://github.com/ethereum/EIPs/issues/225) network -with geth. The first step is creating a _signer account_: an account which -will be used by geth to sign the blocks in the network. -Any block signed by a signer is accepted as valid. +Для этого руководства мы будем использовать простую +[Proof-of-Authority](https://github.com/ethereum/EIPs/issues/225) сеть +с geth. Первым шагом является создание _учетной записи подписанта_: учетной записи, которая +будет использоваться geth для подписи блоков в сети. +Любой блок, подписанный подписантом, принимается как действительный. -### 1.1. Create a Signer Account +### 1.1. Создание учетной записи подписанта -To create a signer account, from the `marketplace-tutorial` directory run: +Чтобы создать учетную запись подписанта, из директории `marketplace-tutorial` выполните: ```bash geth account new --datadir geth-data ``` -The account generator will ask you to input a password, which you can -leave blank. It will then print some information, -including the account's public address: +Генератор учетных записей попросит вас ввести пароль, который вы можете +оставить пустым. Затем он выведет некоторую информацию, +включая публичный адрес учетной записи: ```bash INFO [09-29|16:49:24.244] Maximum peer count ETH=50 total=50 @@ -69,37 +69,37 @@ Path of the secret key file: geth-data/keystore/UTC--2024-09-29T14-49-31.6552720 - You must REMEMBER your password! Without the password, it's impossible to decrypt the key! ``` -In this example, the public address of the signer account is +В этом примере публичный адрес учетной записи подписанта - `0x33A904Ad57D0E2CB8ffe347D3C0E83C2e875E7dB`. -Yours will print a different address. Save it for later usage. +У вас будет выведен другой адрес. Сохраните его для дальнейшего использования. -Next set an environment variable for later usage: +Затем установите переменную окружения для дальнейшего использования: ```bash export GETH_SIGNER_ADDR="0x0000000000000000000000000000000000000000" echo ${GETH_SIGNER_ADDR} > geth_signer_address.txt ``` -> Here make sure you replace `0x0000000000000000000000000000000000000000` -> with your public address of the signer account -> (`0x33A904Ad57D0E2CB8ffe347D3C0E83C2e875E7dB` in our example). +> Здесь убедитесь, что вы заменили `0x0000000000000000000000000000000000000000` +> на ваш публичный адрес учетной записи подписанта +> (`0x33A904Ad57D0E2CB8ffe347D3C0E83C2e875E7dB` в нашем примере). -### 1.2. Configure The Network and Create the Genesis Block +### 1.2. Настройка сети и создание генезис-блока -The next step is telling geth what kind of network you want to run. -We will be running a [pre-merge](https://ethereum.org/en/roadmap/merge/) -network with Proof-of-Authority consensus. -To get that working, create a `network.json` file. +Следующий шаг - указать geth, какую сеть вы хотите запустить. +Мы будем запускать [pre-merge](https://ethereum.org/en/roadmap/merge/) +сеть с консенсусом Proof-of-Authority. +Чтобы это работало, создайте файл `network.json`. -If you set the `GETH_SIGNER_ADDR` variable above you can run the following -command to create the `network.json` file: +Если вы установили переменную `GETH_SIGNER_ADDR` выше, вы можете выполнить следующую +команду для создания файла `network.json`: ```bash echo "{\"config\": { \"chainId\": 12345, \"homesteadBlock\": 0, \"eip150Block\": 0, \"eip155Block\": 0, \"eip158Block\": 0, \"byzantiumBlock\": 0, \"constantinopleBlock\": 0, \"petersburgBlock\": 0, \"istanbulBlock\": 0, \"berlinBlock\": 0, \"londonBlock\": 0, \"arrowGlacierBlock\": 0, \"grayGlacierBlock\": 0, \"clique\": { \"period\": 1, \"epoch\": 30000 } }, \"difficulty\": \"1\", \"gasLimit\": \"8000000\", \"extradata\": \"0x0000000000000000000000000000000000000000000000000000000000000000${GETH_SIGNER_ADDR:2}0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\", \"alloc\": { \"${GETH_SIGNER_ADDR}\": { \"balance\": \"10000000000000000000000\"}}}" > network.json ``` -You can also manually create the file remembering update it with your -signer public address: +Вы также можете создать файл вручную, не забыв обновить его своим +публичным адресом подписанта: ```json { @@ -133,49 +133,48 @@ signer public address: } ``` -Note that the signer account address is embedded in two different places: -* inside of the `"extradata"` string, surrounded by zeroes and stripped of - its `0x` prefix; -* as an entry key in the `alloc` session. - Make sure to replace that ID with the account ID that you wrote down in - [Step 1.1](#_1-1-create-a-signer-account). +Обратите внимание, что адрес учетной записи подписанта встроен в два разных места: +* внутри строки `"extradata"`, окруженный нулями и без префикса `0x`; +* как ключ записи в секции `alloc`. + Убедитесь, что вы заменили этот ID на ID учетной записи, который вы записали в + [Шаге 1.1](#_1-1-create-a-signer-account). -Once `network.json` is created, you can initialize the network with: +После создания `network.json` вы можете инициализировать сеть с помощью: ```bash geth init --datadir geth-data network.json ``` -The output of the above command you may include some warnings, like: +В выводе этой команды могут быть предупреждения, например: ```bash WARN [08-21|14:48:12.305] Unknown config environment variable envvar=GETH_SIGNER_ADDR ``` -or even errors when running the command for the first time: +или даже ошибки при первом запуске команды: ```bash ERROR[08-21|14:48:12.399] Head block is not reachable ``` -The important part is that at the end you should see something similar to: +Важно, что в конце вы должны увидеть что-то похожее на: ```bash INFO [08-21|14:48:12.639] Successfully wrote genesis state database=lightchaindata hash=768bf1..42d06a ``` -### 1.3. Start your PoA Node +### 1.3. Запуск вашего PoA узла -We are now ready to start our $1$-node, private blockchain. -To launch the signer node, open a separate terminal in the same working -directory and make sure you have the `GETH_SIGNER_ADDR` set. -For convenience use the `geth_signer_address.txt`: +Теперь мы готовы запустить нашу $1$-узловую приватную блокчейн-сеть. +Чтобы запустить узел подписанта, откройте отдельный терминал в той же рабочей +директории и убедитесь, что у вас установлена переменная `GETH_SIGNER_ADDR`. +Для удобства используйте `geth_signer_address.txt`: ```bash export GETH_SIGNER_ADDR=$(cat geth_signer_address.txt) ``` -Having the `GETH_SIGNER_ADDR` variable set, run: +Имея установленную переменную `GETH_SIGNER_ADDR`, выполните: ```bash geth\ @@ -190,14 +189,14 @@ geth\ --allow-insecure-unlock ``` -Note that, once again, the signer account created in -[Step 1.1](#_1-1-create-a-signer-account) appears both in -`--unlock` and `--allow-insecure-unlock`. +Обратите внимание, что учетная запись подписанта, созданная в +[Шаге 1.1](#_1-1-create-a-signer-account), снова появляется как в +`--unlock`, так и в `--allow-insecure-unlock`. -Geth will prompt you to insert the account's password as it starts up. -Once you do that, it should be able to start up and begin "mining" blocks. +Geth попросит вас ввести пароль учетной записи при запуске. +После этого он должен запуститься и начать "майнить" блоки. -Also here, you may encounter errors like: +Здесь также могут возникнуть ошибки, например: ```bash ERROR[08-21|15:00:27.625] Bootstrap node filtered by netrestrict id=c845e51a5e470e44 ip=18.138.108.67 @@ -206,41 +205,41 @@ ERROR[08-21|15:00:27.625] Bootstrap node filtered by netrestrict id=ef2d7ab886 ERROR[08-21|15:00:27.625] Bootstrap node filtered by netrestrict id=6b36f791352f15eb ip=157.90.35.166 ``` -You can safely ignore them. +Их можно безопасно игнорировать. -If the command above fails with: +Если команда выше завершается с ошибкой: ```bash Fatal: Failed to register the Ethereum service: only PoS networks are supported, please transition old ones with Geth v1.13.x ``` -make sure, you are running the correct Geth version -(see Section [Prerequisites](#prerequisites)) +убедитесь, что вы используете правильную версию Geth +(см. раздел [Предварительные требования](#prerequisites)) -## 2. Set Up The Marketplace +## 2. Настройка маркетплейса -You will need to open new terminal for this section and geth needs to be -running already. Setting up the Codex marketplace entails: +Для этого раздела вам нужно открыть новый терминал, и geth должен быть уже запущен. +Настройка маркетплейса Codex включает: -1. Deploying the Codex Marketplace contracts to our private blockchain -2. Setup Ethereum accounts we will use to buy and sell storage in - the Codex marketplace -3. Provisioning those accounts with the required token balances +1. Развертывание контрактов маркетплейса Codex в нашу приватную блокчейн-сеть +2. Настройку учетных записей Ethereum, которые мы будем использовать для покупки и продажи хранилища в + маркетплейсе Codex +3. Обеспечение этих учетных записей необходимыми балансами токенов -### 2.1. Deploy the Codex Marketplace Contracts +### 2.1. Развертывание контрактов маркетплейса Codex -Make sure you leave the `marketplace-tutorial` directory, and clone -the `codex-storage/nim-codex.git`: +Убедитесь, что вы вышли из директории `marketplace-tutorial` и клонируйте +`codex-storage/nim-codex.git`: ```bash git clone https://github.com/codex-storage/nim-codex.git ``` -> If you just want to clone the repo to run the tutorial, you can -> skip the history and just download the head of the master branch by using -> `--depth 1` option: `git clone --depth 1 https://github.com/codex-storage/nim-codex.git` +> Если вы хотите просто клонировать репозиторий для прохождения руководства, вы можете +> пропустить историю и просто скачать голову ветки master, используя +> опцию `--depth 1`: `git clone --depth 1 https://github.com/codex-storage/nim-codex.git` -Thus, our directory structure for the purpose of this tutorial looks like this: +Таким образом, структура директорий для целей этого руководства выглядит так: ```bash | @@ -248,190 +247,188 @@ Thus, our directory structure for the purpose of this tutorial looks like this: └-- marketplace-tutorial ``` -> You could clone the `codex-storage/nim-codex.git` to some other location. -> Just to keeps things nicely separated it is best to make sure that -> `nim-codex` is not under `marketplace-tutorial` directory. +> Вы можете клонировать `codex-storage/nim-codex.git` в другое место. -Now, from the `nim-codex` folder run: +Теперь из папки `nim-codex` выполните: ```bash make update && make ``` -> This may take a moment as it will also build the `nim` compiler. Be patient. +> Это может занять некоторое время, так как это также соберет компилятор `nim`. Будьте терпеливы. -Now, in order to start a local Ethereum network run: +Теперь, чтобы запустить локальную сеть Ethereum, выполните: ```bash cd vendor/codex-contracts-eth npm install ``` -> While writing the document we used `node` version `v20.17.0` and -> `npm` version `11.0.0`. +> При написании документа мы использовали `node` версии `v20.17.0` и +> `npm` версии `10.8.2`. -Before continuing you now must **wait until $256$ blocks are mined** -**in your PoAnetwork**, or deploy will fail. This should take about -$4$ minutes and $30$ seconds. You can check which block height you are -currently at by running the following command -**from the `marketplace-tutorial` folder**: +Прежде чем продолжить, вы должны **дождаться, пока будет добыто $256$ блоков** +**в вашей PoA сети**, иначе развертывание завершится неудачей. Это должно занять около +$4$ минут и $30$ секунд. Вы можете проверить, на какой высоте блока вы находитесь, +выполнив следующую команду +**из папки `marketplace-tutorial`**: ```bash geth attach --exec web3.eth.blockNumber ./geth-data/geth.ipc ``` -once that gets past $256$, you are ready to go. +как только это превысит $256$, вы готовы к работе. -To deploy contracts, from the `codex-contracts-eth` directory run: +Чтобы развернуть контракты, из директории `codex-contracts-eth` выполните: ```bash export DISTTEST_NETWORK_URL=http://localhost:8545 npx hardhat --network codexdisttestnetwork deploy ``` -If the command completes successfully, you will see the output similar -to this one: +Если команда завершится успешно, вы увидите вывод, похожий на этот: ```bash Deployed Marketplace with Groth16 Verifier at: 0xCf0df6C52B02201F78E8490B6D6fFf5A82fC7BCd ``` -> of course your address will be different. +> конечно, ваш адрес будет другим. -You are now ready to prepare the accounts. +Теперь вы готовы подготовить учетные записи. -### 2.2. Generate the Required Accounts +### 2.2. Генерация необходимых учетных записей -We will run $2$ Codex nodes: a **storage provider**, which will sell storage -on the network, and a **client**, which will buy and use such storage; -we therefore need two valid Ethereum accounts. We could create random -accounts by using one of the many tools available to that end but, since -this is a tutorial running on a local private network, we will simply -provide you with two pre-made accounts along with their private keys, -which you can copy and paste instead: +Мы будем запускать $2$ узла Codex: **поставщик хранилища**, который будет продавать хранилище +в сети, и **клиент**, который будет покупать и использовать такое хранилище; +поэтому нам нужны две действительные учетные записи Ethereum. Мы могли бы создать случайные +учетные записи, используя один из многих доступных инструментов, но, поскольку +это руководство работает в локальной приватной сети, мы просто предоставим вам +две предварительно созданные учетные записи вместе с их приватными ключами, +которые вы можете скопировать и вставить: -First make sure you're back in the `marketplace-tutorial` folder and -not the `codex-contracts-eth` subfolder. Then set these variables: +Сначала убедитесь, что вы вернулись в папку `marketplace-tutorial` и +не находитесь в подпапке `codex-contracts-eth`. Затем установите эти переменные: -**Storage:** +**Хранилище:** ```bash export ETH_STORAGE_ADDR=0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37 export ETH_STORAGE_PK=0x06c7ac11d4ee1d0ccb53811b71802fa92d40a5a174afad9f2cb44f93498322c3 echo $ETH_STORAGE_PK > storage.pkey && chmod 0600 storage.pkey ``` -**Client:** +**Клиент:** ```bash export ETH_CLIENT_ADDR=0x9F0C62Fe60b22301751d6cDe1175526b9280b965 export ETH_CLIENT_PK=0x5538ec03c956cb9d0bee02a25b600b0225f1347da4071d0fd70c521fdc63c2fc echo $ETH_CLIENT_PK > client.pkey && chmod 0600 client.pkey ``` -### 2.3. Provision Accounts with Tokens +### 2.3. Обеспечение учетных записей токенами -We now need to transfer some ETH to each of the accounts, as well as provide -them with some Codex tokens for the storage node to use as collateral and -for the client node to buy actual storage. +Теперь нам нужно перевести немного ETH на каждую из учетных записей, а также предоставить +им некоторые токены Codex для использования узлом хранилища в качестве залога и +для клиентского узла для покупки фактического хранилища. -Although the process is not particularly complicated, I suggest you use -[the script we prepared](https://github.com/gmega/local-codex-bare/blob/main/scripts/mint-tokens.js) -for that. This script, essentially: +Хотя процесс не особенно сложен, я предлагаю вам использовать +[скрипт, который мы подготовили](https://github.com/gmega/local-codex-bare/blob/main/scripts/mint-tokens.js) +для этого. Этот скрипт, по сути: -1. reads the Marketplace contract address and its ABI from the deployment data; -2. transfers $1$ ETH from the signer account to a target account if the target - account has no ETH balance; -3. mints $n$ Codex tokens and adds it into the target account's balance. +1. читает адрес контракта маркетплейса и его ABI из данных развертывания; +2. переводит $1$ ETH с учетной записи подписанта на целевую учетную запись, если целевая + учетная запись не имеет баланса ETH; +3. чеканит $n$ токенов Codex и добавляет их в баланс целевой учетной записи. -To use the script, just download it into a local file named `mint-tokens.js`, -for instance using `curl` (make sure you are in -the `marketplace-tutorial` directory): +Чтобы использовать скрипт, просто скачайте его в локальный файл с именем `mint-tokens.js`, +например, используя `curl` (убедитесь, что вы находитесь в +директории `marketplace-tutorial`): ```bash -# download script +# скачать скрипт curl https://raw.githubusercontent.com/gmega/codex-local-bare/main/scripts/mint-tokens.js -o mint-tokens.js ``` -Then run: +Затем выполните: ```bash -# set the contract file location (we assume you are in the marketplace-tutorial directory) +# установить расположение файла контракта (мы предполагаем, что вы находитесь в директории marketplace-tutorial) export CONTRACT_DEPLOY_FULL="../nim-codex/vendor/codex-contracts-eth/deployments/codexdisttestnetwork" export GETH_SIGNER_ADDR=$(cat geth_signer_address.txt) -# Installs Web3-js +# Устанавливает Web3-js npm install web3 -# Provides tokens to the storage account. -node ./mint-tokens.js $CONTRACT_DEPLOY_FULL/TestToken.json $GETH_SIGNER_ADDR 0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37 1000000000000000000 -# Provides tokens to the client account. -node ./mint-tokens.js $CONTRACT_DEPLOY_FULL/TestToken.json $GETH_SIGNER_ADDR 0x9F0C62Fe60b22301751d6cDe1175526b9280b965 1000000000000000000 +# Предоставляет токены учетной записи хранилища. +node ./mint-tokens.js $CONTRACT_DEPLOY_FULL/TestToken.json $GETH_SIGNER_ADDR 0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37 10000000000 +# Предоставляет токены клиентской учетной записи. +node ./mint-tokens.js $CONTRACT_DEPLOY_FULL/TestToken.json $GETH_SIGNER_ADDR 0x9F0C62Fe60b22301751d6cDe1175526b9280b965 10000000000 ``` -If you get a message like +Если вы получите сообщение типа ```bash Usage: mint-tokens.js ``` -then you need to ensure you provided all the required arguments. -In particular you need to ensure that the `GETH_SIGNER_ADDR` env variable -holds the signer address (we used -`export GETH_SIGNER_ADDR=$(cat geth_signer_address.txt)` above to -make sure it is set). +то вам нужно убедиться, что вы предоставили все необходимые аргументы. +В частности, вам нужно убедиться, что переменная окружения `GETH_SIGNER_ADDR` +содержит адрес подписанта (мы использовали +`export GETH_SIGNER_ADDR=$(cat geth_signer_address.txt)` выше, чтобы +убедиться, что она установлена). -## 3. Run Codex +## 3. Запуск Codex -With accounts and geth in place, we can now start the Codex nodes. +С учетными записями и geth на месте, мы теперь можем запустить узлы Codex. -### 3.1. Storage Node +### 3.1. Узел хранилища -The storage node will be the one storing data and submitting the proofs of -storage to the chain. To do that, it needs access to: +Узел хранилища будет тем, который хранит данные и отправляет доказательства +хранения в цепочку. Для этого ему нужен доступ к: -1. the address of the Marketplace contract that has been deployed to - the local geth node in [Step 2.1](#_2-1-deploy-the-codex-marketplace-contracts); -2. the sample ceremony files which are shipped in the Codex contracts repo +1. адресу контракта маркетплейса, который был развернут в + локальном узле geth в [Шаге 2.1](#_2-1-deploy-the-codex-marketplace-contracts); +2. образцам файлов церемонии, которые поставляются в репозитории контрактов Codex (`nim-codex/vendor/codex-contracts-eth`). -**Address of the Marketplace Contract.** The contract address can be found -inside of the file `nim-codex/vendor/codex-contracts-eth/deployments/codexdisttestnetwork/Marketplace.json`. -We captured that location above in `CONTRACT_DEPLOY_FULL` variable, thus, from -the `marketplace-tutorial` folder just run: +**Адрес контракта маркетплейса.** Адрес контракта можно найти +внутри файла `nim-codex/vendor/codex-contracts-eth/deployments/codexdisttestnetwork/Marketplace.json`. +Мы захватили это расположение выше в переменной `CONTRACT_DEPLOY_FULL`, поэтому из +папки `marketplace-tutorial` просто выполните: ```bash grep '"address":' ${CONTRACT_DEPLOY_FULL}/Marketplace.json ``` -which should print something like: +что должно вывести что-то вроде: ```bash "address": "0xCf0df6C52B02201F78E8490B6D6fFf5A82fC7BCd", ``` -> This address should match the address we got earlier when deploying -> the Marketplace contract above. +> Этот адрес должен соответствовать адресу, который мы получили ранее при развертывании +> контракта маркетплейса выше. -Then run the following with the correct market place address: +Затем выполните следующее с правильным адресом маркетплейса: ```bash export MARKETPLACE_ADDRESS="0x0000000000000000000000000000000000000000" echo ${MARKETPLACE_ADDRESS} > marketplace_address.txt ``` -where you replace `0x0000000000000000000000000000000000000000` with -the address of the Marketplace contract. +где вы заменяете `0x0000000000000000000000000000000000000000` на +адрес контракта маркетплейса выше в +[Шаге 2.1](#_2-1-deploy-the-codex-marketplace-contracts). -**Prover ceremony files.** The ceremony files are under the -`nim-codex/vendor/codex-contracts-eth/verifier/networks/codexdisttestnetwork` -subdirectory. There are three of them: `proof_main.r1cs`, `proof_main.zkey`, -and `prooof_main.wasm`. We will need all of them to start the Codex storage node. +**Файлы церемонии провайдера.** Файлы церемонии находятся в подкаталоге +`nim-codex/vendor/codex-contracts-eth/verifier/networks/codexdisttestnetwork`. +Их три: `proof_main.r1cs`, `proof_main.zkey`, +и `prooof_main.wasm`. Нам понадобятся все они для запуска узла хранилища Codex. -**Starting the storage node.** Let: +**Запуск узла хранилища.** Пусть: -* `PROVER_ASSETS` contain the directory where the prover ceremony files are - located. **This must be an absolute path**; -* `CODEX_BINARY` contain the location of your Codex binary; -* `MARKETPLACE_ADDRESS` contain the address of the Marketplace contract - (we have already set it above). +* `PROVER_ASSETS` содержит директорию, где находятся файлы церемонии провайдера. + **Это должен быть абсолютный путь**; +* `CODEX_BINARY` содержит расположение вашего бинарного файла Codex; +* `MARKETPLACE_ADDRESS` содержит адрес контракта маркетплейса + (мы уже установили его выше). -Set these paths into environment variables (make sure you are in -the `marketplace-tutorial` directory): +Установите эти пути в переменные окружения (убедитесь, что вы находитесь в +директории `marketplace-tutorial`): ```bash export CONTRACT_DEPLOY_FULL=$(realpath "../nim-codex/vendor/codex-contracts-eth/deployments/codexdisttestnetwork") @@ -439,10 +436,10 @@ export PROVER_ASSETS=$(realpath "../nim-codex/vendor/codex-contracts-eth/verifie export CODEX_BINARY=$(realpath "../nim-codex/build/codex") export MARKETPLACE_ADDRESS=$(cat marketplace_address.txt) ``` -> you may notice, that we have already set the `CONTRACT_DEPLOY_FULL` variable -> above. Here, we make sure it is an absolute path. +> вы можете заметить, что мы уже установили переменную `CONTRACT_DEPLOY_FULL` +> выше. Здесь мы убеждаемся, что это абсолютный путь. -To launch the storage node, run: +Чтобы запустить узел хранилища, выполните: ```bash ${CODEX_BINARY}\ @@ -462,35 +459,35 @@ ${CODEX_BINARY}\ --circom-zkey=${PROVER_ASSETS}/proof_main.zkey ``` -**Starting the client node.** +**Запуск клиентского узла.** -The client node is started similarly except that: +Клиентский узел запускается аналогично, за исключением того, что: -* we need to pass the SPR of the storage node so it can form a network with it; -* since it does not run any proofs, it does not require any ceremony files. +* нам нужно передать SPR узла хранилища, чтобы он мог сформировать сеть с ним; +* поскольку он не выполняет никаких доказательств, ему не требуются файлы церемонии. -We get the Signed Peer Record (SPR) of the storage node so we can bootstrap -the client node with it. To get the SPR, issue the following call: +Мы получаем Signed Peer Record (SPR) узла хранилища, чтобы мы могли загрузить +клиентский узел с ним. Чтобы получить SPR, выполните следующий вызов: ```bash curl -H 'Accept: text/plain' 'http://localhost:8000/api/codex/v1/spr' --write-out '\n' ``` -You should get the SPR back starting with `spr:`. +Вы должны получить SPR, начинающийся с `spr:`. -Before you proceed, open new terminal, and enter `marketplace-tutorial` directory. +Прежде чем продолжить, откройте новый терминал и войдите в директорию `marketplace-tutorial`. -Next set these paths into environment variables: +Затем установите эти пути в переменные окружения: ```bash -# set the SPR for the storage node +# установить SPR для узла хранилища export STORAGE_NODE_SPR=$(curl -H 'Accept: text/plain' 'http://localhost:8000/api/codex/v1/spr') -# basic vars +# базовые переменные export CONTRACT_DEPLOY_FULL=$(realpath "../nim-codex/vendor/codex-contracts-eth/deployments/codexdisttestnetwork") export CODEX_BINARY=$(realpath "../nim-codex/build/codex") export MARKETPLACE_ADDRESS=$(cat marketplace_address.txt) ``` -and then run: +и затем выполните: ```bash ${CODEX_BINARY}\ @@ -501,85 +498,78 @@ ${CODEX_BINARY}\ --bootstrap-node=${STORAGE_NODE_SPR}\ persistence\ --eth-provider=http://localhost:8545\ - --eth-private-key=./client.pkey\ - --marketplace-address=${MARKETPLACE_ADDRESS} ``` -## 4. Buy and Sell Storage on the Marketplace +## 4. Покупка и продажа хранилища на маркетплейсе -Any storage negotiation has two sides: a buyer and a seller. -Therefore, before we can actually request storage, we must first offer -some of it for sale. +Любые переговоры о хранилище имеют две стороны: покупатель и продавец. +Поэтому, прежде чем мы сможем фактически запросить хранилище, мы должны сначала предложить +его на продажу. -### 4.1 Sell Storage +### 4.1 Продажа хранилища -The following request will cause the storage node to put out $5\text{MB}$ -of storage for sale for $1$ hour, at a minimum price of $1000$ Codex token -per byte per second, while expressing that maximum penalty (a collateral) -the storage provider is willing to risk for not fulfilling its part of the -contract is limited to $50000000$ tokens (wei) for this specific availability.[^1] -This total collateral will be distributed across all storage requests matching -this availability. +Следующий запрос заставит узел хранилища выставить $50\text{MB}$ +хранилища на продажу на $1$ час по цене $1$ токен Codex +за слот в секунду, при этом выражая готовность принять максимум +$1000$ токенов Codex в качестве штрафа за невыполнение своей части контракта.[^1] ```bash curl 'http://localhost:8000/api/codex/v1/sales/availability' \ --header 'Content-Type: application/json' \ --data '{ - "totalSize": "5000000", + "totalSize": "50000000", "duration": "3600", - "minPricePerBytePerSecond": "1000", - "totalCollateral": "50000000" + "minPrice": "1", + "maxCollateral": "1000" }' ``` -This should return a JSON response containing an `id` (e.g. -`"id": "0xb55b3bc7aac2563d5bf08ce8a177a38b5a40254bfa7ee8f9c52debbb176d44b0"`) -which identifies this storage offer. +Это должно вернуть JSON-ответ, содержащий `id` (например, `"id": "0xb55b3bc7aac2563d5bf08ce8a177a38b5a40254bfa7ee8f9c52debbb176d44b0"`), +который идентифицирует это предложение хранилища. -> To make JSON responses more readable, you can try -> [jq](https://jqlang.github.io/jq/) JSON formatting utility -> by just adding `| jq` after the command. -> On macOS you can install with `brew install jq`. +> Чтобы сделать JSON-ответы более читаемыми, вы можете попробовать +> утилиту форматирования JSON [jq](https://jqlang.github.io/jq/) +> просто добавив `| jq` после команды. +> На macOS вы можете установить с помощью `brew install jq`. -To check the current storage offers for this node, you can issue: +Чтобы проверить текущие предложения хранилища для этого узла, вы можете выполнить: ```bash curl 'http://localhost:8000/api/codex/v1/sales/availability' ``` -or with `jq`: +или с `jq`: ```bash curl 'http://localhost:8000/api/codex/v1/sales/availability' | jq ``` -This should print a list of offers, with the one you just created figuring -among them (for our tutorial, there will be only one offer returned -at this time). +Это должно вывести список предложений, с тем, который вы только что создали, среди +них (для нашего руководства, в это время будет возвращено только одно предложение). -### 4.2. Buy Storage +### 4.2. Покупка хранилища -Before we can buy storage, we must have some actual data to request -storage for. Start by uploading a small file to your client node. -On Linux (or macOS) you could, for instance, use `dd` to generate a $1M$ file: +Прежде чем мы сможем купить хранилище, у нас должны быть некоторые фактические данные для запроса +хранилища. Начните с загрузки небольшого файла на ваш клиентский узел. +В Linux (или macOS) вы могли бы, например, использовать `dd` для генерации файла размером $1M$: ```bash dd if=/dev/urandom of=./data.bin bs=1M count=1 ``` -Assuming your file is named `data.bin`, you can upload it with: +Предполагая, что ваш файл называется `data.bin`, вы можете загрузить его с помощью: ```bash curl --request POST http://localhost:8001/api/codex/v1/data --header 'Content-Type: application/octet-stream' --write-out '\n' -T ./data.bin ``` -Once the upload completes, you should see a _Content Identifier_, -or _CID_ (e.g. `zDvZRwzm2mK7tvDzKScRLapqGdgNTLyyEBvx1TQY37J2CdWdS6Sj`) -for the uploaded file printed to the terminal. -Use that CID in the purchase request: +После завершения загрузки вы должны увидеть _Content Identifier_, +или _CID_ (например, `zDvZRwzm2mK7tvDzKScRLapqGdgNTLyyEBvx1TQY37J2CdWdS6Sj`) +для загруженного файла, выведенный в терминал. +Используйте этот CID в запросе на покупку: ```bash -# make sure to replace the CID before with the CID you got in the previous step +# убедитесь, что заменили CID перед с CID, который вы получили на предыдущем шаге export CID=zDvZRwzm2mK7tvDzKScRLapqGdgNTLyyEBvx1TQY37J2CdWdS6Sj ``` @@ -588,83 +578,85 @@ curl "http://localhost:8001/api/codex/v1/storage/request/${CID}" \ --header 'Content-Type: application/octet-stream' \ --data "{ \"duration\": \"600\", - \"pricePerBytePerSecond\": \"2000\", + \"reward\": \"1\", \"proofProbability\": \"3\", \"expiry\": \"500\", \"nodes\": 3, \"tolerance\": 1, - \"collateralPerByte\": \"1\" + \"collateral\": \"1000\" }" \ --write-out '\n' ``` -The parameters under `--data` say that: +Параметры под `--data` говорят, что: -1. we want to purchase storage for our file for $5$ minutes (`"duration": "600"`); -2. we are willing to pay up to $2000$ tokens (wei) per slot per second - (`"pricePerBytePerSecond": "2000"`). It is then twice as much as - `minPricePerBytePerSecond`, which we set to $1000$ when creating the availability - above. -3. our file will be split into three pieces (`"nodes": 3`). - Because we set `"tolerance": 1` we only need two (`nodes - tolerance`) - pieces to rebuild the file; i.e., we can tolerate that at most one node - stops storing our data; either due to failure or other reasons; -4. we demand `1` token in collateral from storage providers per byte of storage - per second for each piece of data (called _slots_). Because we provide some redundancy to - the stored data, the actual size of the stored dataset will be bigger than original - content (the bigger the `tolerance` the bigger the resulting dataset). -5. finally, the `expiry` puts a time limit for filling all the slots by - the storage provider(s). If slots are not filled by the `expire` interval, - the request will timeout and fail. +1. мы хотим купить хранилище для нашего файла на $5$ минут (`"duration": "600"`); +2. мы готовы платить до $1$ токена за слот в секунду (`"reward": "1"`) +3. наш файл будет разделен на три части (`"nodes": 3`). + Поскольку мы установили `"tolerance": 1`, нам нужно только две части (`nodes - tolerance`) + для восстановления файла; т.е. мы можем допустить, что максимум один узел + перестанет хранить наши данные; либо из-за сбоя, либо по другим причинам; +4. мы требуем `1000` токенов в качестве залога от поставщиков хранилища для каждой части. + Поскольку есть $3$ такие части, всего будет `3000` залога, + зафиксированного поставщиком(ами) хранилища, как только наш запрос будет начат. +5. наконец, `expiry` устанавливает временной лимит для заполнения всех слотов + поставщиком(ами) хранилища. Если слоты не заполнены к моменту `expire`, + запрос истечет и завершится неудачей. -### 4.3. Track your Storage Requests +### 4.3. Отслеживание ваших запросов на хранилище -POSTing a storage request will make it available in the storage market, -and a storage node will eventually pick it up. +POST-запрос на хранилище сделает его доступным на рынке хранилища, +и узел хранилища в конечном итоге подберет его. -You can poll the status of your request by means of: +Вы можете опрашивать статус вашего запроса с помощью: ```bash -export STORAGE_PURCHASE_ID="6b6e2445f33ed624891f0543fe9dbf4bd0a6971febccaae2431375a5b9a2840d" +export STORAGE_PURCHASE_ID="1d0ec5261e3364f8b9d1cf70324d70af21a9b5dccba380b24eb68b4762249185" curl "http://localhost:8001/api/codex/v1/storage/purchases/${STORAGE_PURCHASE_ID}" ``` -This returns a result like: +Например: + +```bash +> curl 'http://localhost:8001/api/codex/v1/storage/purchases/6c698cd0ad71c41982f83097d6fa75beb582924e08a658357a1cd4d7a2a6766d' +``` + +Это возвращает результат типа: ```json { - "requestId": "0x6b6e2445f33ed624891f0543fe9dbf4bd0a6971febccaae2431375a5b9a2840d", + "requestId": "0x86501e4677a728c6a8031971d09b921c3baa268af06b9f17f1b745e7dba5d330", "request": { "client": "0x9f0c62fe60b22301751d6cde1175526b9280b965", "ask": { - "proofProbability": "3", - "pricePerBytePerSecond": "2000", - "collateralPerByte": "1", "slots": 3, - "slotSize": 524288, - "duration": 600, + "slotSize": "262144", + "duration": "1000", + "proofProbability": "3", + "reward": "1", + "collateral": "1", "maxSlotLoss": 1 }, "content": { - "cid": "zDvZRwzm18zqvTRMHhjDmwybKZaomW8bDFtdSyaQ4XM6MmER5fzy" + "cid": "zDvZRwzkyw1E7ABaUSmgtNEDjC7opzhUoHo99Vpvc98cDWeCs47u" }, - "expiry": 500, - "nonce": "0x5267b832fe9a978fb0dd3912b42fece7c5ac074a9cc3c74bf578b6cee9e43543", - "id": "0x6b6e2445f33ed624891f0543fe9dbf4bd0a6971febccaae2431375a5b9a2840d" + "expiry": "1711992852", + "nonce": "0x9f5e651ecd3bf73c914f8ed0b1088869c64095c0d7bd50a38fc92ebf66ff5915", + "id": "0x6c698cd0ad71c41982f83097d6fa75beb582924e08a658357a1cd4d7a2a6766d" }, "state": "submitted", "error": null } ``` -Shows that a request has been submitted but has not yet been filled. -Your request will be successful once `"state"` shows `"started"`. -Anything other than that means the request has not been completely -processed yet, and an `"error"` state other than `null` means it failed. +Показывает, что запрос был отправлен, но еще не заполнен. +Ваш запрос будет успешным, как только `"state"` покажет `"started"`. +Все, что отличается от этого, означает, что запрос еще не полностью +обработан, а состояние `"error"` отличное от `null` означает, что он завершился неудачей. -Well, it was quite a journey, wasn't it? You can congratulate yourself for -successfully finishing the codex marketplace tutorial! +Ну что, это было довольно долгое путешествие, не так ли? Вы можете поздравить себя с +успешным завершением руководства по маркетплейсу codex! -[^1]: Codex files get partitioned into pieces called "slots" and distributed -to various storage providers. The collateral refers to one such slot, -and will be slowly eaten away as the storage provider fails to deliver -timely proofs. +[^1]: Файлы Codex разделяются на части, называемые "слотами", и распределяются +по различным поставщикам хранилища. Залог относится к одному такому слоту, +и будет медленно уменьшаться по мере того, как поставщик хранилища не сможет предоставить +своевременные доказательства, но фактическая логика [более сложна, чем это](https://github.com/codex-storage/codex-contracts-eth/blob/6c9f797f408608958714024b9055fcc330e3842f/contracts/Marketplace.sol#L209). diff --git a/learn/local-two-client-test.md b/learn/local-two-client-test.md index 31c8efd..c1b51d7 100644 --- a/learn/local-two-client-test.md +++ b/learn/local-two-client-test.md @@ -1,28 +1,28 @@ -# Codex Two-Client Test +# Тест с двумя клиентами Codex -The two-client test is a manual test you can perform to check your setup and familiarize yourself with the Codex API. These steps will guide you through running and connecting two nodes, in order to upload a file to one and then download that file from the other. This test also includes running a local blockchain node in order to have the Marketplace functionality available. However, running a local blockchain node is not strictly necessary, and you can skip steps marked as optional if you choose not start a local blockchain node. +Тест с двумя клиентами - это ручной тест, который вы можете выполнить для проверки вашей настройки и ознакомления с API Codex. Эти шаги проведут вас через запуск и подключение двух узлов, чтобы загрузить файл на один и затем скачать этот файл с другого. Этот тест также включает запуск локального узла блокчейна для обеспечения доступности функциональности Marketplace. Однако запуск локального узла блокчейна не является строго необходимым, и вы можете пропустить шаги, отмеченные как необязательные, если решите не запускать локальный узел блокчейна. -## Prerequisite +## Предварительные требования -Make sure you have [built the client](/learn/build) or obtained [compiled binary](/learn/quick-start#get-codex-binary). +Убедитесь, что вы [собрали клиент](/learn/build) или получили [скомпилированный бинарный файл](/learn/quick-start#get-codex-binary). -## Steps +## Шаги -### 0. Setup blockchain node (optional) +### 0. Настройка узла блокчейна (необязательно) -You need to have installed NodeJS and npm in order to spinup a local blockchain node. +Вам необходимо установить NodeJS и npm для запуска локального узла блокчейна. -Go to directory `vendor/codex-contracts-eth` and run these two commands: +Перейдите в директорию `vendor/codex-contracts-eth` и выполните эти две команды: ``` npm ci npm start ``` -This will launch a local Ganache blockchain. +Это запустит локальный блокчейн Ganache. -### 1. Launch Node #1 +### 1. Запуск Узла #1 -Open a terminal and run: +Откройте терминал и выполните: - Mac/Linux: ```shell codex \ @@ -40,17 +40,20 @@ Open a terminal and run: --listen-addrs="/ip4/127.0.0.1/tcp/8070" ``` -Optionally, if you want to use the Marketplace blockchain functionality, you need to also include these flags: `--persistence --eth-account=`, where `account` can be one following: +Необязательно, если вы хотите использовать функциональность блокчейна Marketplace, вам также нужно включить эти флаги: `--persistence --eth-account=`, где `account` может быть одним из следующих: - `0x70997970C51812dc3A010C7d01b50e0d17dc79C8` - `0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC` - `0x90F79bf6EB2c4f870365E785982E1f101E93b906` - `0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65` -**For each node use a different account!** +**Для каждого узла используйте разный аккаунт!** -| Argument | Description | +| Аргумент | Описание | |----------------|-----------------------------------------------------------------------| +| `data-dir` | Мы указываем относительный путь, где узел будет хранить свои данные. | +| `listen-addrs` | Multiaddress, где узел будет принимать соединения от других узлов. | +| `api-port` | Порт на localhost, где узел будет предоставлять свой API. | | `data-dir` | We specify a relative path where the node will store its data. | | `listen-addrs` | Multiaddress where the node will accept connections from other nodes. | | `api-port` | Port on localhost where the node will expose its API. | diff --git a/learn/quick-start.md b/learn/quick-start.md index 0167b17..7a9d272 100644 --- a/learn/quick-start.md +++ b/learn/quick-start.md @@ -1,80 +1,80 @@ -# Quick Start +# Быстрый старт -To run Codex through this guide we would need to perform the following steps: -- [Review the disclaimer](/codex/disclaimer) -- [Get Codex binary](#get-codex-binary) -- [Run Codex](#run-codex) -- [Interact with Codex](#interact-with-codex) +Чтобы запустить Codex через это руководство, нам нужно выполнить следующие шаги: +- [Ознакомиться с отказом от ответственности](/codex/disclaimer) +- [Получить бинарный файл Codex](#get-codex-binary) +- [Запустить Codex](#run-codex) +- [Взаимодействовать с Codex](#interact-with-codex) -## Get Codex binary +## Получение бинарного файла Codex -For quick a start we will use precompiled binaries from [GitHub release page](https://github.com/codex-storage/nim-codex/releases). If you prefer to compile from the sources, please check [Build Codex](/learn/build). +Для быстрого старта мы будем использовать предварительно скомпилированные бинарные файлы со [страницы релизов GitHub](https://github.com/codex-storage/nim-codex/releases). Если вы предпочитаете компилировать из исходного кода, пожалуйста, проверьте [Сборка Codex](/learn/build). -Please follow the steps for your OS from the list: +Пожалуйста, следуйте шагам для вашей ОС из списка: - [Linux/macOS](#linux-macos) - [Windows](#windows) ### Linux/macOS -1. Install latest Codex release +1. Установите последний релиз Codex ```shell curl -s https://get.codex.storage/install.sh | bash ``` -2. Install dependencies +2. Установите зависимости ```shell # Debian-based Linux sudo apt update && sudo apt install libgomp1 ``` -3. Check the result +3. Проверьте результат ```shell codex --version ``` ### Windows -1. Install latest Codex release +1. Установите последний релиз Codex ```batch curl -sO https://get.codex.storage/install.cmd && install.cmd ``` > [!WARNING] - > Windows antivirus software and built-in firewalls may cause steps to fail. We will cover some possible errors here, but always consider checking your setup if requests fail - in particular, if temporarily disabling your antivirus fixes it, then it is likely to be the culprit. + > Антивирусное программное обеспечение Windows и встроенные брандмауэры могут привести к сбою шагов. Мы рассмотрим некоторые возможные ошибки здесь, но всегда учитывайте проверку вашей настройки, если запросы завершаются неудачей - в частности, если временное отключение вашего антивируса исправляет это, то, вероятно, это является причиной. - If you see an error like: + Если вы видите ошибку типа: ```batch curl: (35) schannel: next InitializeSecurityContext failed: CRYPT_E_NO_REVOCATION_CHECK (0x80092012) - The revocation function was unable to check revocation for the certificate. ``` - You may need to add the `--ssl-no-revoke` option to your curl calls, i.e., modify the calls above so they look like this: + Возможно, вам нужно добавить опцию `--ssl-no-revoke` к вашим вызовам curl, т.е. изменить вызовы выше, чтобы они выглядели так: ```batch curl -LO --ssl-no-revoke https://... ``` -2. Update path using console output - - Current session only +2. Обновите путь, используя вывод консоли + - Только для текущей сессии ```batch - :: Default installation directory + :: Путь установки по умолчанию set "PATH=%PATH%%LOCALAPPDATA%\Codex;" ``` - - Update PATH permanently - - Control Panel --> System --> Advanced System settings --> Environment Variables - - Alternatively, type `environment variables` into the Windows Search box + - Обновление PATH постоянно + - Панель управления --> Система --> Дополнительные параметры системы --> Переменные среды + - Или введите `environment variables` в поле поиска Windows -3. Check the result +3. Проверьте результат ```shell codex --version ``` -## Run Codex +## Запуск Codex -We may [run Codex in different modes](/learn/run#run), and for a quick start we will run [Codex node](/learn/run#codex-node), to be able to share files in the network. +Мы можем [запустить Codex в разных режимах](/learn/run#run), и для быстрого старта мы запустим [узел Codex](/learn/run#codex-node), чтобы иметь возможность обмениваться файлами в сети. -1. Run Codex +1. Запустите Codex **Linux/macOS** ```shell @@ -90,28 +90,28 @@ We may [run Codex in different modes](/learn/run#run), and for a quick start we **Windows** > [!WARNING] - > Windows might at this stage prompt you to grant internet access to Codex. You must allow it for things to work. - > It also might be required to add incoming firewall rules for Codex and we can use `netsh` utility. + > Windows на этом этапе может запросить разрешение на доступ в интернет для Codex. Вы должны разрешить это для работы. + > Также может потребоваться добавить правила входящего брандмауэра для Codex, и мы можем использовать утилиту `netsh`.
- add firewall rules using netsh + добавить правила брандмауэра с помощью netsh ```batch - :: Add rules + :: Добавить правила netsh advfirewall firewall add rule name="Allow Codex (TCP-In)" protocol=TCP dir=in localport=8070 action=allow netsh advfirewall firewall add rule name="Allow Codex (UDP-In)" protocol=UDP dir=in localport=8090 action=allow - :: List rules + :: Показать правила netsh advfirewall firewall show rule name=all | find /I "Codex" - :: Delete rules + :: Удалить правила netsh advfirewall firewall delete rule name="Allow Codex (TCP-In)" netsh advfirewall firewall delete rule name="Allow Codex (UDP-In)" ```
```batch - :: Run Codex + :: Запустить Codex codex ^ --data-dir=datadir ^ --disc-port=8090 ^ @@ -122,26 +122,26 @@ We may [run Codex in different modes](/learn/run#run), and for a quick start we ``` > [!TIP] - > In the example above we use [Codex Testnet](/networks/testnet#bootstrap-nodes) bootstrap nodes and thus we join Testnet. If you would like to join a different network, please use [appropriate value](/networks/networks). + > В примере выше мы используем [узлы начальной загрузки тестовой сети Codex](/networks/testnet#bootstrap-nodes) и, таким образом, присоединяемся к тестовой сети. Если вы хотите присоединиться к другой сети, пожалуйста, используйте [соответствующее значение](/networks/networks). -2. Configure port-forwarding for the TCP/UDP ports on your Internet router - | Protocol | Service | Port | - | -------- | --------- | ------ | - | UDP | Discovery | `8090` | - | TCP | Transport | `8070` | +2. Настройте проброс портов TCP/UDP на вашем интернет-маршрутизаторе + | Протокол | Сервис | Порт | + | -------- | ---------- | ------ | + | UDP | Discovery | `8090` | + | TCP | Transport | `8070` | -If you would like to purchase or sell storage, please consider to run [Codex node with marketplace support](/learn/run#codex-node-with-marketplace-support) or [Codex storage node](/learn/run#codex-storage-node). +Если вы хотите покупать или продавать хранилище, рассмотрите возможность запуска [узла Codex с поддержкой маркетплейса](/learn/run#codex-node-with-marketplace-support) или [узла хранения Codex](/learn/run#codex-storage-node). -## Interact with Codex +## Взаимодействие с Codex -When your Codex node is up and running you can interact with it using [Codex App UI](https://app.codex.storage) for files sharing. +Когда ваш узел Codex запущен и работает, вы можете взаимодействовать с ним, используя [Пользовательский интерфейс приложения Codex](https://app.codex.storage) для обмена файлами. -Also, you can interact with Codex using [Codex API](/developers/api) and for a walk-through of the API, consider following the [Using Codex](/learn/using) guide. +Также вы можете взаимодействовать с Codex, используя [API Codex](/developers/api), и для ознакомления с API рассмотрите возможность следования руководству [Использование Codex](/learn/using). -## Stay in touch +## Оставайтесь на связи -Want to stay up-date, or looking for further assistance? Try our [discord-server](https://discord.gg/codex-storage). +Хотите быть в курсе или ищете дополнительную помощь? Попробуйте наш [дискорд-сервер](https://discord.gg/codex-storage). -Ready to explore Codex functionality? Please [Join Codex Testnet](/networks/testnet). +Готовы исследовать функциональность Codex? Пожалуйста, [Присоединитесь к тестовой сети Codex](/networks/testnet). -If you want to run Codex locally without joining the Testnet, consider trying the [Codex Two-Client Test](/learn/local-two-client-test) or the [Running a Local Codex Network with Marketplace Support](/learn/local-marketplace). +Если вы хотите запустить Codex локально без присоединения к тестовой сети, рассмотрите возможность попробовать [Тест с двумя клиентами Codex](/learn/local-two-client-test) или [Запуск локальной сети Codex с поддержкой маркетплейса](/learn/local-marketplace). diff --git a/learn/run.md b/learn/run.md index d0175e0..302470b 100644 --- a/learn/run.md +++ b/learn/run.md @@ -1,35 +1,35 @@ --- outline: [2, 4] --- -# Run Codex +# Запуск Codex -As for now, Codex is implemented only in [Nim](https://nim-lang.org) and can be found in [nim-codex](https://github.com/codex-storage/nim-codex) repository. +На данный момент Codex реализован только на [Nim](https://nim-lang.org) и находится в репозитории [nim-codex](https://github.com/codex-storage/nim-codex). -It is a command-line application which may be run in a different ways: - - [Using binary](#using-binary) - - [Run as a service in Linux](#run-as-a-service-in-linux) - - [Run as a service in Windows](#run-as-a-service-in-windows) (not supported yet) - - [Using Docker](#using-docker) - - [Using Docker Compose](#using-docker-compose) - - [On Kubernetes](#on-kubernetes) +Это консольное приложение, которое может быть запущено разными способами: + - [Использование бинарного файла](#using-binary) + - [Запуск как сервис в Linux](#run-as-a-service-in-linux) + - [Запуск как сервис в Windows](#run-as-a-service-in-windows) (пока не поддерживается) + - [Использование Docker](#using-docker) + - [Использование Docker Compose](#using-docker-compose) + - [На Kubernetes](#on-kubernetes) -During the run, it is required to pass [configuration](#configuration) option to the application, which can be done in a different ways. +При запуске необходимо передать [параметры конфигурации](#configuration) приложению, что можно сделать разными способами. -## Configuration +## Конфигурация -It is possible to configure Codex node in several ways: - 1. [CLI options](#cli-options) - 2. [Environment variables](#environment-variables) - 3. [Configuration file](#configuration-file) +Настроить узел Codex можно несколькими способами: + 1. [Параметры командной строки](#cli-options) + 2. [Переменные окружения](#environment-variables) + 3. [Файл конфигурации](#configuration-file) -The order of priority is the same as above: -[CLI options](#cli-options) --> [Environment variables](#environment-variables) --> [Configuration file](#configuration-file). +Приоритет следующий: +[Параметры командной строки](#cli-options) --> [Переменные окружения](#environment-variables) --> [Файл конфигурации](#configuration-file). -### Common information +### Общая информация -#### Units +#### Единицы измерения -For some configuration options, we can pass values in common units like following: +Для некоторых параметров конфигурации мы можем передавать значения в общепринятых единицах измерения: ```shell --cache-size=1m/1M/1mb/1MB --storage-quota=2m/2M/2mb/2MB @@ -38,117 +38,117 @@ For some configuration options, we can pass values in common units like followin --block-ttl=2s/2S/2m/2M/2h/2H/2d/2D/2w/2W ``` -#### Logging +#### Логирование -Codex uses [Chronicles](https://github.com/status-im/nim-chronicles) logging library, which allows great flexibility in working with logs. -Chronicles has the concept of topics, which categorize log entries into semantic groups. +Codex использует библиотеку логирования [Chronicles](https://github.com/status-im/nim-chronicles), которая обеспечивает большую гибкость в работе с логами. +Chronicles использует концепцию тем, которые группируют записи логов по семантическим группам. -Using the `log-level` parameter, you can set the top-level log level like `--log-level="trace"`, but more importantly, -you can set log levels for specific topics like `--log-level="info; trace: marketplace,node; error: blockexchange"`, -which sets the top-level log level to `info` and then for topics `marketplace` and `node` sets the level to `trace` and so on. +Используя параметр `log-level`, вы можете установить общий уровень логирования, например `--log-level="trace"`, но что более важно, +вы можете установить уровни логирования для конкретных тем, например `--log-level="info; trace: marketplace,node; error: blockexchange"`, +что устанавливает общий уровень логирования в `info`, а для тем `marketplace` и `node` устанавливает уровень `trace` и так далее. -### CLI options +### Параметры командной строки ```shell codex --help -Usage: +Использование: -codex [OPTIONS]... command +codex [ПАРАМЕТРЫ]... команда -The following options are available: +Доступны следующие параметры: - --config-file Loads the configuration from a TOML file [=none]. - --log-level Sets the log level [=info]. - --metrics Enable the metrics server [=false]. - --metrics-address Listening address of the metrics server [=127.0.0.1]. - --metrics-port Listening HTTP port of the metrics server [=8008]. - -d, --data-dir The directory where codex will store configuration and data + --config-file Загружает конфигурацию из TOML файла [=none]. + --log-level Устанавливает уровень логирования [=info]. + --metrics Включает сервер метрик [=false]. + --metrics-address Адрес прослушивания сервера метрик [=127.0.0.1]. + --metrics-port HTTP порт прослушивания сервера метрик [=8008]. + -d, --data-dir Директория, где codex будет хранить конфигурацию и данные [=/root/.cache/codex]. - -i, --listen-addrs Multi Addresses to listen on [=/ip4/0.0.0.0/tcp/0]. - -a, --nat NAT traversal method for determining the public address. - Options: any, none, upnp, pmp, extip: [any] - -u, --disc-port Discovery (UDP) port [=8090]. - --net-privkey Source of network (secp256k1) private key file path or name [=key]. - -b, --bootstrap-node Specifies one or more bootstrap nodes to use when connecting to the network. - --max-peers The maximum number of peers to connect to [=160]. - --num-threads Number of worker threads (\"0\" = use as many threads as there are CPU cores available). - --agent-string Node agent string which is used as identifier in network [=Codex]. - --api-bindaddr The REST API bind address [=127.0.0.1]. - -p, --api-port The REST Api port [=8080]. - --api-cors-origin The REST Api CORS allowed origin for downloading data. '*' will allow all - origins, '' will allow none. [=Disallow all cross origin requests to download - data]. - --repo-kind Backend for main repo store (fs, sqlite, leveldb) [=fs]. - -q, --storage-quota The size of the total storage quota dedicated to the node [=$DefaultQuotaBytes]. - -t, --block-ttl Default block timeout in seconds - 0 disables the ttl [=$DefaultBlockTtl]. - --block-mi Time interval in seconds - determines frequency of block maintenance cycle: how - often blocks are checked for expiration and cleanup + -i, --listen-addrs Multi-адреса для прослушивания [=/ip4/0.0.0.0/tcp/0]. + -a, --nat Метод обхода NAT для определения публичного адреса. + Варианты: any, none, upnp, pmp, extip: [any] + -u, --disc-port Порт обнаружения (UDP) [=8090]. + --net-privkey Источник сетевого (secp256k1) приватного ключа - путь к файлу или имя [=key]. + -b, --bootstrap-node Указывает один или несколько узлов начальной загрузки для использования при подключении к сети. + --max-peers Максимальное количество пиров для подключения [=160]. + --num-threads Количество рабочих потоков ("0" = использовать столько потоков, сколько доступно ядер CPU). + --agent-string Строка агента узла, используемая как идентификатор в сети [=Codex]. + --api-bindaddr Адрес привязки REST API [=127.0.0.1]. + -p, --api-port Порт REST API [=8080]. + --api-cors-origin Разрешенный источник CORS для REST API при загрузке данных. '*' разрешит все + источники, '' не разрешит ни одного. [=Запретить все кросс-оригинальные запросы + для загрузки данных]. + --repo-kind Бэкенд для основного хранилища репозитория (fs, sqlite, leveldb) [=fs]. + -q, --storage-quota Размер общего квота хранилища, выделенного узлу [=$DefaultQuotaBytes]. + -t, --block-ttl Таймаут блока по умолчанию в секундах - 0 отключает ttl [=$DefaultBlockTtl]. + --block-mi Интервал времени в секундах - определяет частоту цикла обслуживания блоков: как + часто блоки проверяются на истечение срока действия и очищаются [=$DefaultBlockMaintenanceInterval]. - --block-mn Number of blocks to check every maintenance cycle [=1000]. - -c, --cache-size The size of the block cache, 0 disables the cache - might help on slow hardrives + --block-mn Количество блоков для проверки в каждом цикле обслуживания [=1000]. + -c, --cache-size Размер кэша блоков, 0 отключает кэш - может помочь на медленных жестких дисках [=0]. -Available sub-commands: +Доступные подкоманды: -codex persistence [OPTIONS]... command +codex persistence [ПАРАМЕТРЫ]... команда -The following options are available: +Доступны следующие параметры: - --eth-provider The URL of the JSON-RPC API of the Ethereum node [=ws://localhost:8545]. - --eth-account The Ethereum account that is used for storage contracts. - --eth-private-key File containing Ethereum private key for storage contracts. - --marketplace-address Address of deployed Marketplace contract. - --validator Enables validator, requires an Ethereum node [=false]. - --validator-max-slots Maximum number of slots that the validator monitors [=1000]. - --reward-recipient Address to send payouts to (eg rewards and refunds). - --request-cache-size Maximum number of StorageRequests kept in memory. Reduces fetching of StorageRequest data from the contract. [=128]. + --eth-provider URL JSON-RPC API узла Ethereum [=ws://localhost:8545]. + --eth-account Учетная запись Ethereum, используемая для контрактов хранения. + --eth-private-key Файл, содержащий приватный ключ Ethereum для контрактов хранения. + --marketplace-address Адрес развернутого контракта Marketplace. + --validator Включает валидатор, требует узел Ethereum [=false]. + --validator-max-slots Максимальное количество слотов, которые мониторит валидатор [=1000]. + --reward-recipient Адрес для отправки выплат (например, вознаграждений и возвратов). + --request-cache-size Максимальное количество StorageRequests, хранящихся в памяти. Уменьшает получение данных StorageRequest из контракта. [=128]. -Available sub-commands: +Доступные подкоманды: -codex persistence prover [OPTIONS]... +codex persistence prover [ПАРАМЕТРЫ]... -The following options are available: +Доступны следующие параметры: - -cd, --circuit-dir Directory where Codex will store proof circuit data + -cd, --circuit-dir Директория, где Codex будет хранить данные схемы доказательств [=/root/.cache/codex/circuits]. - --circom-r1cs The r1cs file for the storage circuit + --circom-r1cs Файл r1cs для схемы хранения [=/root/.cache/codex/circuits/proof_main.r1cs]. - --circom-wasm The wasm file for the storage circuit + --circom-wasm Файл wasm для схемы хранения [=/root/.cache/codex/circuits/proof_main.wasm]. - --circom-zkey The zkey file for the storage circuit + --circom-zkey Файл zkey для схемы хранения [=/root/.cache/codex/circuits/proof_main.zkey]. - --circom-no-zkey Ignore the zkey file - use only for testing! [=false]. - --proof-samples Number of samples to prove [=5]. - --max-slot-depth The maximum depth of the slot tree [=32]. - --max-dataset-depth The maximum depth of the dataset tree [=8]. - --max-block-depth The maximum depth of the network block merkle tree [=5]. - --max-cell-elements The maximum number of elements in a cell [=67]. + --circom-no-zkey Игнорировать файл zkey - использовать только для тестирования! [=false]. + --proof-samples Количество образцов для доказательства [=5]. + --max-slot-depth Максимальная глубина дерева слотов [=32]. + --max-dataset-depth Максимальная глубина дерева наборов данных [=8]. + --max-block-depth Максимальная глубина дерева Меркла сетевых блоков [=5]. + --max-cell-elements Максимальное количество элементов в ячейке [=67]. ``` -### Environment variables +### Переменные окружения -In order to set a configuration option using environment variables, first find the desired [CLI option](#cli-options) -and then transform it in the following way: +Чтобы установить параметр конфигурации с помощью переменных окружения, сначала найдите нужный [параметр командной строки](#cli-options) +и затем преобразуйте его следующим образом: - 1. prepend it with `CODEX_` - 2. make it uppercase - 3. replace `-` with `_` + 1. добавьте префикс `CODEX_` + 2. сделайте его заглавными буквами + 3. замените `-` на `_` -For example, to configure `--log-level`, use `CODEX_LOG_LEVEL` as the environment variable name. +Например, чтобы настроить `--log-level`, используйте `CODEX_LOG_LEVEL` как имя переменной окружения. > [!WARNING] -> Some options can't be configured via environment variables for now [^multivalue-env-var] [^sub-commands]. +> Некоторые параметры пока не могут быть настроены через переменные окружения [^multivalue-env-var] [^sub-commands]. -### Configuration file +### Файл конфигурации -A [TOML](https://toml.io/en/) configuration file can also be used to set configuration values. Configuration option names and corresponding values are placed in the file, separated by `=`. Configuration option names can be obtained from the [`codex --help`](#cli-options) command, and should not include the `--` prefix. For example, a node's log level (`--log-level`) can be configured using TOML as follows: +Для установки значений конфигурации также можно использовать файл [TOML](https://toml.io/en/). Имена параметров конфигурации и соответствующие значения размещаются в файле, разделенные `=`. Имена параметров конфигурации можно получить из команды [`codex --help`](#cli-options), и они не должны включать префикс `--`. Например, уровень логирования узла (`--log-level`) можно настроить с помощью TOML следующим образом: ```toml log-level = "trace" ``` -For option, like `bootstrap-node` and `listen-addrs` which accept multiple values we can specify data as an array +Для параметров, таких как `bootstrap-node` и `listen-addrs`, которые принимают несколько значений, мы можем указать данные как массив ```toml listen-addrs = [ "/ip4/0.0.0.0/tcp/1234", @@ -156,39 +156,39 @@ listen-addrs = [ ] ``` -The Codex node can then read the configuration from this file using the `--config-file` CLI parameter, like: +Узел Codex может затем прочитать конфигурацию из этого файла, используя параметр `--config-file` командной строки: ```shell codex --config-file=/path/to/your/config.toml ``` -Please check [Run as a service in Linux](#run-as-a-service-in-linux) for a full example of configuration file. +Пожалуйста, проверьте [Запуск как сервис в Linux](#run-as-a-service-in-linux) для полного примера файла конфигурации. -## Run +## Запуск -Basically, we can run Codex in three different modes: - - [Codex node](#codex-node) - useful for local testing/development and basic/files sharing. - - [Codex node with marketplace support](#codex-node-with-marketplace-support) - you can share files and buy the storage, this is the main mode and should be used by the end users. - - [Codex storage node](#codex-storage-node) - should be used by storage providers or if you would like to sell your local storage. +В основном, мы можем запустить Codex в трех разных режимах: + - [Узел Codex](#codex-node) - полезен для локального тестирования/разработки и базового обмена файлами. + - [Узел Codex с поддержкой маркетплейса](#codex-node-with-marketplace-support) - вы можете обмениваться файлами и покупать хранилище, это основной режим и должен использоваться конечными пользователями. + - [Узел хранения Codex](#codex-storage-node) - должен использоваться поставщиками хранилища или если вы хотите продавать свое локальное хранилище. - We also will touch in some words [Codex bootstrap node](#codex-bootstrap-node). + Мы также кратко рассмотрим [Узел начальной загрузки Codex](#codex-bootstrap-node). -### Using binary +### Использование бинарного файла -#### Codex node +#### Узел Codex -We can run Codex in a simple way like following: +Мы можем запустить Codex простым способом: ```shell codex ``` > [!WARNING] -> This command may not work properly when we use GitHub releases [^data-dir]. +> Эта команда может работать некорректно при использовании релизов GitHub [^data-dir]. -But, it will use a default `data-dir` value and we can pass a custom one: +Но, она будет использовать значение `data-dir` по умолчанию, и мы можем передать пользовательское: ```shell codex --data-dir=datadir ``` -This will run Codex as an isolated instance, and if we would like to join an existing network, it is required to pass a [bootstrap node](#codex-bootstrap-node). We can pass multiple nodes as well: +Это запустит Codex как изолированный экземпляр, и если мы хотим присоединиться к существующей сети, необходимо передать [узел начальной загрузки](#codex-bootstrap-node). Мы можем передать несколько узлов: ```shell codex \ --data-dir=datadir \ @@ -197,9 +197,9 @@ codex \ ``` > [!IMPORTANT] -> Make sure you are using a proper value for the [network](/networks/networks) you would like to join. +> Убедитесь, что вы используете правильное значение для [сети](/networks/networks), к которой хотите присоединиться. -Also, to make your Codex node accessible for other network participants, it is required to specify a public IP address which can be used to access your node: +Также, чтобы сделать ваш узел Codex доступным для других участников сети, необходимо указать публичный IP-адрес, который можно использовать для доступа к вашему узлу: ```shell codex \ --data-dir=datadir \ @@ -208,9 +208,9 @@ codex \ ``` > [!TIP] -> We can set public IP using curl and IP lookup service, like [ip.codex.storage](https://ip.codex.storage). +> Мы можем установить публичный IP с помощью curl и сервиса определения IP, например [ip.codex.storage](https://ip.codex.storage). -After that, node will announce itself using your public IP, default UDP ([discovery](https://docs.libp2p.io/concepts/discovery-routing/overview/)) and dynamic TCP port ([data transfer](https://docs.libp2p.io/concepts/transports/overview/)), which can be adjusted in the following way: +После этого узел будет объявлять себя, используя ваш публичный IP, UDP-порт по умолчанию ([обнаружение](https://docs.libp2p.io/concepts/discovery-routing/overview/)) и динамический TCP-порт ([передача данных](https://docs.libp2p.io/concepts/transports/overview/)), которые можно настроить следующим образом: ```shell codex \ --data-dir=datadir \ @@ -220,24 +220,24 @@ codex \ --listen-addrs=/ip4/0.0.0.0/tcp/8070 ``` -In that way, node will announce itself using specified [multiaddress](https://docs.libp2p.io/concepts/fundamentals/addressing/) and we can check that via [API](https://api.codex.storage/#tag/Debug/operation/getDebugInfo) call: +Таким образом, узел будет объявлять себя, используя указанный [multi-адрес](https://docs.libp2p.io/concepts/fundamentals/addressing/), и мы можем проверить это через [API](https://api.codex.storage/#tag/Debug/operation/getDebugInfo) вызов: ```shell curl -s localhost:8080/api/codex/v1/debug/info | jq -r '.announceAddresses' ``` ```json [ - "/ip4//tcp/8070" + "/ip4/<ваш публичный IP>/tcp/8070" ] ``` -Basically, for P2P communication we should specify and configure two ports: -| # | Protocol | Function | CLI option | Example | +В основном, для P2P-коммуникации мы должны указать и настроить два порта: +| # | Протокол | Функция | Параметр командной строки | Пример | | - | -------- | ------------------------------------------------------------------------ | ---------------- | -------------------------------------- | -| 1 | UDP | [Discovery](https://docs.libp2p.io/concepts/discovery-routing/overview/) | `--disc-port` | `--disc-port=8090` | -| 2 | TCP | [Transport](https://docs.libp2p.io/concepts/transports/overview/) | `--listen-addrs` | `--listen-addrs=/ip4/0.0.0.0/tcp/8070` | +| 1 | UDP | [Обнаружение](https://docs.libp2p.io/concepts/discovery-routing/overview/) | `--disc-port` | `--disc-port=8090` | +| 2 | TCP | [Транспорт](https://docs.libp2p.io/concepts/transports/overview/) | `--listen-addrs` | `--listen-addrs=/ip4/0.0.0.0/tcp/8070` | -And, also it is required to setup [port-forwarding](#port-forwarding) on your Internet router, to make your node accessible for participants. +Также необходимо настроить [проброс портов](#port-forwarding) на вашем интернет-маршрутизаторе, чтобы сделать ваш узел доступным для участников. -So, a fully working basic configuration will looks like following: +Итак, полностью рабочая базовая конфигурация будет выглядеть следующим образом: ```shell codex \ --data-dir=datadir \ @@ -254,428 +254,225 @@ You also can use [Codex App UI](https://app.codex.storage) for files upload/down And to be able to purchase a storage, we should run [Codex node with marketplace support](#codex-node-with-marketplace-support). -#### Codex node with marketplace support +#### Узел Codex с поддержкой маркетплейса -[Marketplace](/learn/architecture.md#marketplace-architecture) support permits to purchase the storage in Codex network. Basically, we should add just a `persistence` sub-command and required [CLI options](#cli-options) to the [previous run](#codex-node). +Для запуска узла Codex с поддержкой маркетплейса необходимо добавить несколько дополнительных параметров: -> [!NOTE] -> Please ignore `--eth-account` CLI option, as it is obsolete [^eth-account]. - -1. For a daily use, we should consider to run a local blockchain node based on the [network](/networks/networks) you would like to join. That process is described in the [Join Codex Testnet](/networks/testnet) guide, but for a quick start we can use a public RPC endpoint. - -2. Create a file with ethereum private key and set a proper permissions: - > [!CAUTION] - > Please use key generation service for demo purpose only. - - ```shell - response=$(curl -s https://key.codex.storage) - awk -F ': ' '/private/ {print $2}' <<<"${response}" > eth.key - awk -F ': ' '/address/ {print $2}' <<<"${response}" > eth.address - chmod 600 eth.key - ``` - Show your ethereum address: - ```shell - cat eth.address - ``` - ``` - 0x412665aFAb17768cd9aACE6E00537Cc6D5524Da9 - ``` - -3. Fill-up your ethereum address with ETH and Tokens based on the the [network](/networks/networks) you would like to join. - -4. Specify bootstrap nodes and marketplace address based on the [network](/networks/networks) you would like to join. - -5. Run the node: - ```shell - codex \ - --data-dir=datadir \ - --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P \ - --nat=any \ - --disc-port=8090 \ - --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ - --api-cors-origin="*" \ - persistence \ - --eth-provider=https://rpc.testnet.codex.storage \ - --eth-private-key=eth.key \ - --marketplace-address=0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed - ``` - -> [!NOTE] -> Codex also has a marketplace contract address autodiscovery mechanism based on the chain id, that mapping is done in the [source code](https://github.com/codex-storage/nim-codex/blob/master/codex/contracts/deployment.nim). In that way we can skip `--marketplace-address` argument or use it to override a hardcoded value. - -After node is up and running, and your address has founds, you should be able to [Purchase storage](/learn/using#purchase-storage) using [API](/developers/api). - -You also can use [Codex App UI](https://app.codex.storage) for storage purchase. - -#### Codex storage node - -Codex [storage node](architecture#network-architecture) should be run by storage providers or in case you would like to sell your local storage. - -For that, additionally to the [Codex node with marketplace support](#codex-node-with-marketplace-support) we should use `prover` sub-command and required [CLI options](#cli-options). - -That sub-command will make Codex to listen for a proof requests on the blockchain and answer them. To compute an answer for the proof request, Codex will use stored data and circuit files generated by the code in the [codex-storage-proofs-circuits](https://github.com/codex-storage/codex-storage-proofs-circuits) repository. - -Every [network](/networks/networks) uses its own generated set of the files which are stored in the [codex-contracts-eth](https://github.com/codex-storage/codex-contracts-eth/tree/master/verifier/networks) repository and also uploaded to the CDN. Hash of the files set is also known by the [marketplace smart contract](/learn/architecture#smart-contract). - -To download circuit files and make them available to Codex app, we have a stand-alone utility - `cirdl`. It can be [compiled from the sources](/learn/build#circuit-download-tool) or downloaded from the [GitHub release page](https://github.com/codex-storage/nim-codex/releases). - -1. Create ethereum key file -
- example - - > [!CAUTION] - > Please use key generation service for demo purpose only. - - ```shell - response=$(curl -s https://key.codex.storage) - awk -F ': ' '/private/ {print $2}' <<<"${response}" > eth.key - awk -F ': ' '/address/ {print $2}' <<<"${response}" > eth.address - chmod 600 eth.key - ``` - Show your ethereum address: - ```shell - cat eth.address - ``` - ``` - 0x412665aFAb17768cd9aACE6E00537Cc6D5524Da9 - ``` -
- -2. To download circuit files, we should pass directory, RPC endpoint and marketplace address to the circuit downloader: - ```shell - # Create circuit files folder - mkdir -p datadir/circuits - chmod 700 datadir/circuits - - # Download circuit files - cirdl \ - datadir/circuits \ - https://rpc.testnet.codex.storage \ - 0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed - ``` - -2. Start Codex storage node - ```shell - codex \ - --data-dir=datadir \ - --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P \ - --nat=any \ - --disc-port=8090 \ - --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ - persistence \ - --eth-provider=https://rpc.testnet.codex.storage \ - --eth-private-key=eth.key \ - --marketplace-address=0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed \ - prover \ - --circuit-dir=datadir/circuits - ``` +```shell +codex \ + --data-dir=datadir \ + --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P \ + --nat=any \ + --disc-port=8090 \ + --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ + --api-cors-origin="*" \ + --eth-provider=ws://localhost:8545 \ + --eth-account=0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37 \ + --eth-private-key=0x06c7ac11d4ee1d0ccb53811b71802fa92d40a5a174afad9f2cb44f93498322c3 \ + --marketplace-address=0x1234567890123456789012345678901234567890 +``` > [!NOTE] -> You would need to pass a bootstrap nodes, blockchain RPC endpoint and marketplace address based on the [network](/networks/networks) you would like to join. - +> Для работы с маркетплейсом необходимо иметь запущенный узел Ethereum и развернутый контракт Marketplace. -After node is up and running, and your address has founds, you should be able to [sell the storage](/learn/using#create-storage-availability) using [API](/developers/api). +#### Узел хранения Codex -You also can use [Codex App UI](https://app.codex.storage) to sell the storage. +Узел хранения Codex - это специальный тип узла, который предоставляет хранилище для других участников сети. Для его запуска необходимо добавить параметр `--validator`: -#### Codex bootstrap node - -Bootstrap nodes are used just to help peers with the initial nodes discovery and we need to run Codex with just some basic options: ```shell codex \ --data-dir=datadir \ + --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P \ --nat=any \ - --disc-port=8090 + --disc-port=8090 \ + --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ + --api-cors-origin="*" \ + --eth-provider=ws://localhost:8545 \ + --eth-account=0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37 \ + --eth-private-key=0x06c7ac11d4ee1d0ccb53811b71802fa92d40a5a174afad9f2cb44f93498322c3 \ + --marketplace-address=0x1234567890123456789012345678901234567890 \ + --validator=true \ + --validator-max-slots=1000 \ + --reward-recipient=0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37 ``` -To get bootstrap node SPR we can use [API](https://api.codex.storage/#tag/Debug/operation/getDebugInfo) call: -```shell -curl -s localhost:8080/api/codex/v1/debug/info | jq -r '.spr' -``` -```shell -spr:CiUIAhIhApd79-AxPqwRDmu7Pk-berTDtoIoMz0ovKjo85Tz8CUdEgIDARo8CicAJQgCEiECl3v34DE-rBEOa7s-T5t6tMO2gigzPSi8qOjzlPPwJR0Qjv_WtwYaCwoJBFxzjbKRAh-aKkYwRAIgCiTq5jBTaJJb6lUxN-0uNCj8lkV9AGY682D21kIAMiICIE1yxrjbDdiSCiARnS7I2zqJpXC2hOvjB4JoL9SAAk67 -``` +> [!NOTE] +> Узел хранения требует больше ресурсов, чем обычный узел, так как он должен хранить и обслуживать данные для других участников сети. -That SPR record then can be used then by other peers for initial nodes discovery. - -We should keep in mind some important things about SPR record (see [ENR](https://eips.ethereum.org/EIPS/eip-778)): -- It uses nodes public IP, discovery port (`--disc-port`) and private key (`--net-privkey`) for record creation -- Specified data is signed on each run and will be changed but still contain specified node data when decoded -- You can decode it by passing to the Codex node at run and with `--log-level=trace` - -For bootstrap node, it is required to forward just discovery port on your Internet router. - -### Run as a service in Linux - -We can run Codex as a service via [systemd](https://systemd.io) using following steps - - 1. Create an user for Codex - ```shell - sudo useradd \ - --system \ - --home-dir /opt/codex \ - --shell /usr/sbin/nologin \ - codex - ``` - In case you would like to run commands using a created user, you could do it like following `sudo -u codex ls -la /opt/codex`. - - 2. Install Codex [using a script](https://github.com/codex-storage/get-codex) or [build from sources](/learn/build) - ```shell - # codex with cirdl - curl -s https://get.codex.storage/install.sh | INSTALL_DIR=/usr/local/bin CIRDL=true bash - ``` - - 3. Create directories - ```shell - sudo mkdir -p /opt/codex/data - ``` - - 4. Create a configuration file - ```shell - sudo vi /opt/codex/codex.conf - ``` - ```toml - data-dir = "/opt/codex/data" - listen-addrs = ["/ip4/0.0.0.0/tcp/8070"] - nat = "extip:" - disc-port = 8090 - api-port = 8080 - bootstrap-node = [ - "spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P", - "spr:CiUIAhIhAyUvcPkKoGE7-gh84RmKIPHJPdsX5Ugm_IHVJgF-Mmu_EgIDARo8CicAJQgCEiEDJS9w-QqgYTv6CHzhGYog8ck92xflSCb8gdUmAX4ya78QoemesAYaCwoJBES39Q2RAnVOKkYwRAIgLi3rouyaZFS_Uilx8k99ySdQCP1tsmLR21tDb9p8LcgCIG30o5YnEooQ1n6tgm9fCT7s53k6XlxyeSkD_uIO9mb3", - "spr:CiUIAhIhA6_j28xa--PvvOUxH10wKEm9feXEKJIK3Z9JQ5xXgSD9EgIDARo8CicAJQgCEiEDr-PbzFr74--85TEfXTAoSb195cQokgrdn0lDnFeBIP0QzOGesAYaCwoJBK6Kf1-RAnVEKkcwRQIhAPUH5nQrqG4OW86JQWphdSdnPA98ErQ0hL9OZH9a4e5kAiBBZmUl9KnhSOiDgU3_hvjXrXZXoMxhGuZ92_rk30sNDA", - "spr:CiUIAhIhA7E4DEMer8nUOIUSaNPA4z6x0n9Xaknd28Cfw9S2-cCeEgIDARo8CicAJQgCEiEDsTgMQx6vydQ4hRJo08DjPrHSf1dqSd3bwJ_D1Lb5wJ4Qt_CesAYaCwoJBEDhWZORAnVYKkYwRAIgFNzhnftocLlVHJl1onuhbSUM7MysXPV6dawHAA0DZNsCIDRVu9gnPTH5UkcRXLtt7MLHCo4-DL-RCMyTcMxYBXL0", - "spr:CiUIAhIhAzZn3JmJab46BNjadVnLNQKbhnN3eYxwqpteKYY32SbOEgIDARo8CicAJQgCEiEDNmfcmYlpvjoE2Np1Wcs1ApuGc3d5jHCqm14phjfZJs4QrvWesAYaCwoJBKpA-TaRAnViKkcwRQIhANuMmZDD2c25xzTbKSirEpkZYoxbq-FU_lpI0K0e4mIVAiBfQX4yR47h1LCnHznXgDs6xx5DLO5q3lUcicqUeaqGeg", - "spr:CiUIAhIhAuN-P1D0HrJdwBmrRlZZzg6dqllRNNcQyMDUMuRtg3paEgIDARpJCicAJQgCEiEC434_UPQesl3AGatGVlnODp2qWVE01xDIwNQy5G2DeloQm_L2vQYaCwoJBI_0zSiRAnVsGgsKCQSP9M0okQJ1bCpHMEUCIQDgEVjUp1RJGb59eRPs7RPYMSGAI_fo1yv70iBtnTqefQIgVoXszc87EGFVO3aaqorEYZ21OGRko5ho_Pybdyqa6AI", - "spr:CiUIAhIhAsi_hgxFppWjHiKRwnYPX_qkB28dLtwK9c7apnlBanFuEgIDARpJCicAJQgCEiECyL-GDEWmlaMeIpHCdg9f-qQHbx0u3Ar1ztqmeUFqcW4Q2O32vQYaCwoJBNEmoCiRAnV2GgsKCQTRJqAokQJ1dipHMEUCIQDpC1isFfdRqNmZBfz9IGoEq7etlypB6N1-9Z5zhvmRMAIgIOsleOPr5Ra_Nk7BXmXGhe-YlLosH9jo83JtfWCy3-o" - ] - storage-quota = "8gb" - block-ttl = "24h" - log-level = "info" - ``` - - Make sure to use bootstrap nodes for the [network](/networks/networks) you would like to join, update `nat` variable with a node Public IP and adjust other settings by your needs. - - 5. Change folders ownership and permissions - ```shell - sudo chown -R codex:codex /opt/codex - ``` - - 6. Create systemd unit file - ```shell - sudo vi /lib/systemd/system/codex.service - ``` - ```shell - [Unit] - Description=Codex service - Documentation=https://docs.codex.storage - After=local-fs.target network-online.target - - [Service] - MemorySwapMax=0 - TimeoutStartSec=infinity - Type=exec - User=codex - Group=codex - StateDirectory=codex - ExecStart=/usr/local/bin/codex --config-file="/opt/codex/codex.conf" - Restart=always - RestartSec=3 - - [Install] - WantedBy=multi-user.target - ``` - Check `man systemd`, `man systemd.service` and `man systemd.directives` for additional details. - - 7. Enable and start Codex service - ```shell - sudo systemctl enable codex - sudo systemctl start codex - ``` - - 8. Check service status - ```shell - sudo systemctl status codex - ``` - - 9. Check the logs - ```shell - sudo journalctl -u codex -S "5min ago" - sudo journalctl -f -u codex - sudo tail -f /var/log/syslog | grep codex - ``` - -### Run as a service in Windows +#### Узел начальной загрузки Codex -This functionality is not supported yet :construction: +Узел начальной загрузки - это специальный узел, который помогает новым узлам присоединиться к сети. Для его запуска необходимо добавить параметр `--bootstrap`: -### Using Docker +```shell +codex \ + --data-dir=datadir \ + --nat=any \ + --disc-port=8090 \ + --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ + --api-cors-origin="*" \ + --bootstrap=true +``` -We also ship Codex in Docker containers, which can be run on `amd64` and `arm64` platforms. +> [!NOTE] +> Узел начальной загрузки должен быть доступен для других участников сети, поэтому важно правильно настроить проброс портов. -#### Docker entrypoint +### Запуск как сервис в Linux -[Docker entrypoint](https://github.com/codex-storage/nim-codex/blob/master/docker/docker-entrypoint.sh), supports some additional options, which can be used for easier configuration: +Для запуска Codex как системного сервиса в Linux можно использовать systemd. Создайте файл конфигурации `/etc/systemd/system/codex.service`: -- `ENV_PATH` - path to the file, in form `env=value` which will be sourced and available for Codex at run. That is useful for Kubernetes Pods configuration. -- `NAT_IP_AUTO` - when set to `true`, will set `CODEX_NAT` variable with container internal IP address. It also is useful for Kubernetes Pods configuration, when we perform automated tests. -- `NAT_PUBLIC_IP_AUTO` - used to set `CODEX_NAT` to public IP address using lookup services, like [ip.codex.storage](https://ip.codex.storage). Can be used for Docker/Kubernetes to set public IP in auto mode. -- `ETH_PRIVATE_KEY` - can be used to pass ethereum private key, which will be saved and passed as a value of the `CODEX_ETH_PRIVATE_KEY` variable. It should be considered as unsafe option and used for testing purposes only. -- When we set `prover` sub-command, entrypoint will run `cirdl` tool to download ceremony files, required by [Codex storage node](#codex-storage-node). +```ini +[Unit] +Description=Codex Node +After=network.target -#### Docker network +[Service] +Type=simple +User=codex +Group=codex +WorkingDirectory=/home/codex +ExecStart=/usr/local/bin/codex --config-file=/etc/codex/config.toml +Restart=always +RestartSec=10 -When we are running Codex using Docker with default [bridge network](https://docs.docker.com/engine/network/drivers/bridge/), it will create a double NAT: - - One on the Docker side - - Second on your Internet router +[Install] +WantedBy=multi-user.target +``` -If your Internet router does not support [Full Cone NAT](https://learningnetwork.cisco.com/s/question/0D56e0000CWxJ9sCQF/lets-explain-in-details-full-cone-nat-restricted-cone-nat-and-symmetric-nat-terminologies-vs-cisco-nat-terminologies), you might have an issue and peer discovery and data transport will not work or might work unexpected. +И файл конфигурации `/etc/codex/config.toml`: -In that case, we should consider the following solutions: -- Use [host network](https://docs.docker.com/engine/network/drivers/host/) for Docker, which is supported only in Linux -- Run [Using binary](#using-binary) -- Use VM/VPS in the Cloud to run Docker with bridge or host network +```toml +data-dir = "/home/codex/.codex" +bootstrap-node = [ + "spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P" +] +nat = "any" +disc-port = 8090 +listen-addrs = ["/ip4/0.0.0.0/tcp/8070"] +api-cors-origin = "*" +eth-provider = "ws://localhost:8545" +eth-account = "0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37" +eth-private-key = "0x06c7ac11d4ee1d0ccb53811b71802fa92d40a5a174afad9f2cb44f93498322c3" +marketplace-address = "0x1234567890123456789012345678901234567890" +validator = true +validator-max-slots = 1000 +reward-recipient = "0x45BC5ca0fbdD9F920Edd12B90908448C30F32a37" +``` -#### Run using Docker +Затем выполните следующие команды: -And we basically can use same options we [used for binary](#using-binary) and additionally it is required to mount volumes and map the ports. +```shell +sudo systemctl daemon-reload +sudo systemctl enable codex +sudo systemctl start codex +``` -[Codex storage node](#codex-storage-node) +### Запуск как сервис в Windows -1. Create ethereum key file -
- example +This functionality is not supported yet :construction: - > [!CAUTION] - > Please use key generation service for demo purpose only. +### Использование Docker - ```shell - response=$(curl -s https://key.codex.storage) - awk -F ': ' '/private/ {print $2}' <<<"${response}" > eth.key - awk -F ': ' '/address/ {print $2}' <<<"${response}" > eth.address - chmod 600 eth.key - ``` - Show your ethereum address: - ```shell - cat eth.address - ``` - ``` - 0x412665aFAb17768cd9aACE6E00537Cc6D5524Da9 - ``` -
+Для запуска Codex в Docker можно использовать официальный образ: -2. Run Codex: ```shell -docker run \ - --rm \ - -v $PWD/datadir:/datadir \ - -v $PWD/eth.key:/opt/eth.key \ +docker run -d \ + --name codex \ -p 8070:8070 \ - -p 8080:8080 \ -p 8090:8090/udp \ - codexstorage/nim-codex:latest \ - codex \ - --data-dir=/datadir \ - --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P \ - --nat=any \ - --disc-port=8090 \ - --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ - --api-cors-origin="*" \ - --api-bindaddr=0.0.0.0 \ - --api-port=8080 \ - persistence \ - --eth-provider=https://rpc.testnet.codex.storage \ - --eth-private-key=/opt/eth.key \ - --marketplace-address=0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed \ - prover \ - --circuit-dir=/datadir/circuits + -p 8080:8080 \ + -v /path/to/data:/root/.codex \ + codexstorage/codex:latest \ + --data-dir=/root/.codex \ + --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P \ + --nat=any \ + --disc-port=8090 \ + --listen-addrs=/ip4/0.0.0.0/tcp/8070 \ + --api-cors-origin="*" ``` -> [!NOTE] -> You would need to pass a bootstrap nodes, blockchain RPC endpoint and marketplace address based on the [network](/networks/networks) you would like to join. - -### Using Docker Compose - -For Docker Compose, it is more suitable to use [environment variables](#environment-variables) for Codex configuration and we can reuse commands from example above, for Docker. - -[Codex storage node](#codex-storage-node) - -1. Create ethereum key file -
- example - - > [!CAUTION] - > Please use key generation service for demo purpose only. - - ```shell - response=$(curl -s https://key.codex.storage) - awk -F ': ' '/private/ {print $2}' <<<"${response}" > eth.key - awk -F ': ' '/address/ {print $2}' <<<"${response}" > eth.address - chmod 600 eth.key - ``` - Show your ethereum address: - ```shell - cat eth.address - ``` - ``` - 0x412665aFAb17768cd9aACE6E00537Cc6D5524Da9 - ``` -
- -2. Create `docker-compose.yaml` file: - ```yaml - services: - codex: - image: codexstorage/nim-codex:latest - container_name: codex - command: - - codex - - persistence - - prover - - --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P - - --bootstrap-node=spr:CiUIAhIhAyUvcPkKoGE7-gh84RmKIPHJPdsX5Ugm_IHVJgF-Mmu_EgIDARo8CicAJQgCEiEDJS9w-QqgYTv6CHzhGYog8ck92xflSCb8gdUmAX4ya78QoemesAYaCwoJBES39Q2RAnVOKkYwRAIgLi3rouyaZFS_Uilx8k99ySdQCP1tsmLR21tDb9p8LcgCIG30o5YnEooQ1n6tgm9fCT7s53k6XlxyeSkD_uIO9mb3 - - --bootstrap-node=spr:CiUIAhIhA6_j28xa--PvvOUxH10wKEm9feXEKJIK3Z9JQ5xXgSD9EgIDARo8CicAJQgCEiEDr-PbzFr74--85TEfXTAoSb195cQokgrdn0lDnFeBIP0QzOGesAYaCwoJBK6Kf1-RAnVEKkcwRQIhAPUH5nQrqG4OW86JQWphdSdnPA98ErQ0hL9OZH9a4e5kAiBBZmUl9KnhSOiDgU3_hvjXrXZXoMxhGuZ92_rk30sNDA - - --bootstrap-node=spr:CiUIAhIhA7E4DEMer8nUOIUSaNPA4z6x0n9Xaknd28Cfw9S2-cCeEgIDARo8CicAJQgCEiEDsTgMQx6vydQ4hRJo08DjPrHSf1dqSd3bwJ_D1Lb5wJ4Qt_CesAYaCwoJBEDhWZORAnVYKkYwRAIgFNzhnftocLlVHJl1onuhbSUM7MysXPV6dawHAA0DZNsCIDRVu9gnPTH5UkcRXLtt7MLHCo4-DL-RCMyTcMxYBXL0 - - --bootstrap-node=spr:CiUIAhIhAzZn3JmJab46BNjadVnLNQKbhnN3eYxwqpteKYY32SbOEgIDARo8CicAJQgCEiEDNmfcmYlpvjoE2Np1Wcs1ApuGc3d5jHCqm14phjfZJs4QrvWesAYaCwoJBKpA-TaRAnViKkcwRQIhANuMmZDD2c25xzTbKSirEpkZYoxbq-FU_lpI0K0e4mIVAiBfQX4yR47h1LCnHznXgDs6xx5DLO5q3lUcicqUeaqGeg - - --bootstrap-node=spr:CiUIAhIhAuN-P1D0HrJdwBmrRlZZzg6dqllRNNcQyMDUMuRtg3paEgIDARpJCicAJQgCEiEC434_UPQesl3AGatGVlnODp2qWVE01xDIwNQy5G2DeloQm_L2vQYaCwoJBI_0zSiRAnVsGgsKCQSP9M0okQJ1bCpHMEUCIQDgEVjUp1RJGb59eRPs7RPYMSGAI_fo1yv70iBtnTqefQIgVoXszc87EGFVO3aaqorEYZ21OGRko5ho_Pybdyqa6AI - - --bootstrap-node=spr:CiUIAhIhAsi_hgxFppWjHiKRwnYPX_qkB28dLtwK9c7apnlBanFuEgIDARpJCicAJQgCEiECyL-GDEWmlaMeIpHCdg9f-qQHbx0u3Ar1ztqmeUFqcW4Q2O32vQYaCwoJBNEmoCiRAnV2GgsKCQTRJqAokQJ1dipHMEUCIQDpC1isFfdRqNmZBfz9IGoEq7etlypB6N1-9Z5zhvmRMAIgIOsleOPr5Ra_Nk7BXmXGhe-YlLosH9jo83JtfWCy3-o - environment: - - CODEX_DATA_DIR=/datadir - - NAT_PUBLIC_IP_AUTO=https://ip.codex.storage - - CODEX_DISC_PORT=8090 - - CODEX_LISTEN_ADDRS=/ip4/0.0.0.0/tcp/8070 - - CODEX_API_CORS_ORIGIN="*" - - CODEX_API_PORT=8080 - - CODEX_API_BINDADDR=0.0.0.0 - - CODEX_ETH_PROVIDER=https://rpc.testnet.codex.storage - - CODEX_ETH_PRIVATE_KEY=/opt/eth.key - - CODEX_MARKETPLACE_ADDRESS=0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed - - CODEX_CIRCUIT_DIR=/datadir/circuits - ports: - - 8080:8080/tcp # API - - 8090:8090/udp # Discovery - - 8070:8070/tcp # Transport - volumes: - - ./datadir:/datadir - - ./eth.key:/opt/eth.key - logging: - driver: json-file - options: - max-size: 100m - max-file: 5 - ``` - -3. Run Codex: - ```shell - docker compose up - ``` +### Использование Docker Compose + +Для более сложных конфигураций можно использовать Docker Compose. Создайте файл `docker-compose.yml`: + +```yaml +version: '3' +services: + codex: + image: codexstorage/codex:latest + container_name: codex + ports: + - "8070:8070" + - "8090:8090/udp" + - "8080:8080" + volumes: + - /path/to/data:/root/.codex + command: > + --data-dir=/root/.codex + --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P + --nat=any + --disc-port=8090 + --listen-addrs=/ip4/0.0.0.0/tcp/8070 + --api-cors-origin="*" +``` -> [!NOTE] -> You would need to pass a bootstrap nodes, blockchain RPC endpoint and marketplace address based on the [network](/networks/networks) you would like to join. +Затем выполните: -### On Kubernetes +```shell +docker-compose up -d +``` -Helm chart code is available in [helm-charts](https://github.com/codex-storage/helm-charts) repository, but chart was not published yet. +### На Kubernetes + +Для запуска Codex в Kubernetes создайте файл `codex-deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: codex +spec: + replicas: 1 + selector: + matchLabels: + app: codex + template: + metadata: + labels: + app: codex + spec: + containers: + - name: codex + image: codexstorage/codex:latest + ports: + - containerPort: 8070 + name: tcp + - containerPort: 8090 + name: udp + protocol: UDP + - containerPort: 8080 + name: api + volumeMounts: + - name: codex-data + mountPath: /root/.codex + command: + - codex + - --data-dir=/root/.codex + - --bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P + - --nat=any + - --disc-port=8090 + - --listen-addrs=/ip4/0.0.0.0/tcp/8070 + - --api-cors-origin="*" + volumes: + - name: codex-data + persistentVolumeClaim: + claimName: codex-pvc +``` + +И примените его: + +```shell +kubectl apply -f codex-deployment.yaml +``` ## How-tos @@ -729,8 +526,6 @@ ipconfig | findstr /i "IPv4 Address" ifconfig | grep "inet " | grep -v 127.0.0.1 ``` - - ## Known issues [^multivalue-env-var]: Environment variables like `CODEX_BOOTSTRAP_NODE` and `CODEX_LISTEN_ADDRS` does not support multiple values. Please check [[Feature request] Support multiple SPR records via environment variable #525](https://github.com/codex-storage/nim-codex/issues/525), for more information. diff --git a/learn/tokenomics-litepaper.md b/learn/tokenomics-litepaper.md index 1c6973a..4fed2ec 100644 --- a/learn/tokenomics-litepaper.md +++ b/learn/tokenomics-litepaper.md @@ -1,276 +1,276 @@ --- outline: [1, 3] --- -# Codex Tokenomics Litepaper - Testnet Version +# Лайтбук по токеномике Codex - Версия для тестовой сети -**Codex: A Decentralized Storage Protocol for Durable Information** +**Codex: Децентрализованный протокол хранения для долговременной информации** -# Legal Notices +# Юридические уведомления -*The information contained in this document is intended to be made available for informational purposes only and does not constitute a prospectus, nor an offer to buy, a solicitation or an invitation to buy, or a recommendation for any token or any security. Neither this document nor any of its content should be considered as creating any expectations or forming the basis of any contract, commitment or binding obligation. No information herein should be considered to contain or be relied upon as a promise, representation, warranty or guarantee, whether express or implied and whether as to the past, present or the future in relation to the projects and matters described herein. The information presented is a summary and does not purport to be accurate, reliable or complete. This document is under continuous legal review and may be amended or supplemented at any time without prior notice.  No responsibility will be borne for the accuracy, reliability or completeness of information contained herein. Because of the high degree of risk and uncertainty described above, undue reliance should not be placed by anyone on any matters described in this document. Any tokens referenced in this document have not been registered under any securities laws and may not be offered or sold in any jurisdiction where such offer or sale would be prohibited.* +*Информация, содержащаяся в этом документе, предназначена только для информационных целей и не является проспектом, предложением о покупке, приглашением к покупке или рекомендацией для любого токена или ценной бумаги. Ни этот документ, ни какое-либо его содержание не должны рассматриваться как создание каких-либо ожиданий или формирование основы любого контракта, обязательства или обязательства. Никакая информация здесь не должна рассматриваться как содержащая или полагаться на обещание, представление, гарантию или гарантию, будь то явная или подразумеваемая и будь то в отношении прошлого, настоящего или будущего в отношении проектов и вопросов, описанных здесь. Представленная информация является кратким изложением и не претендует на точность, надежность или полноту. Этот документ находится в постоянном юридическом рассмотрении и может быть изменен или дополнен в любое время без предварительного уведомления. Никакая ответственность не будет нести за точность, надежность или полноту информации, содержащейся здесь. Из-за высокой степени риска и неопределенности, описанных выше, никто не должен полагаться на какие-либо вопросы, описанные в этом документе. Любые токены, упомянутые в этом документе, не были зарегистрированы в соответствии с какими-либо законами о ценных бумагах и не могут быть предложены или проданы в любой юрисдикции, где такое предложение или продажа были бы запрещены.* -*This document may contain forward-looking statements that are based only on current expectations, estimates, forecasts, assumptions and projections about the technology, industry and markets in general. The forward looking statements, projects, content and any other matters described in this document are subject to a high degree of risk and uncertainty. The roadmap, results, project descriptions, technical details, functionalities, and other features are subject to change based on, among other things, market conditions, technical developments, and regulatory environment. The actual development and results, including the order and the timeline, might differ materially from those anticipated in these forward-looking statements.* +*Этот документ может содержать прогнозные заявления, которые основаны только на текущих ожиданиях, оценках, прогнозах, предположениях и проекциях о технологии, отрасли и рынках в целом. Прогнозные заявления, проекты, содержание и любые другие вопросы, описанные в этом документе, подвержены высокой степени риска и неопределенности. Дорожная карта, результаты, описания проектов, технические детали, функциональность и другие функции могут быть изменены на основе, среди прочего, рыночных условий, технических разработок и нормативной среды. Фактическая разработка и результаты, включая порядок и сроки, могут существенно отличаться от тех, которые ожидаются в этих прогнозных заявлениях.* -*The information contained in this document does not constitute financial, legal, tax, investment, professional or other advice and should not be treated as such.* +*Информация, содержащаяся в этом документе, не является финансовой, юридической, налоговой, инвестиционной, профессиональной или иной консультацией и не должна рассматриваться как таковая.* -# Overview +# Обзор -## Scope +## Область применения -This document describes the Codex Tokenomics with elements that reflect the Testnet deployment of the Codex Protocol. +Этот документ описывает токеномику Codex с элементами, отражающими развертывание тестовой сети протокола Codex. -## What Codex Does +## Что делает Codex -Codex is a state-of-the-art decentralized storage platform that offers a novel solution that enhances data durability guarantees for storing vast amounts of data while eliminating any reliance on centralized institutions that could lead to a single point of failure. +Codex - это современная децентрализованная платформа хранения, которая предлагает новое решение, повышающее гарантии долговечности данных для хранения огромных объемов данных, устраняя при этом любую зависимость от централизованных учреждений, которые могут привести к единой точке отказа. -While centralized storage systems such as Google Cloud tout eleven nines of durability, durable file storage in distributed systems that provide censorship resistance and privacy are a vital prerequisite to use cases such as preserving factual records of history in network states. +В то время как централизованные системы хранения, такие как Google Cloud, заявляют о одиннадцати девятках долговечности, долговременное хранение файлов в распределенных системах, обеспечивающих устойчивость к цензуре и конфиденциальность, является жизненно важным предварительным условием для использования, такого как сохранение фактических записей истории в сетевых состояниях. -While no system can guarantee absolute protection against data loss, through its technical architecture, economic incentives, and algorithmic encoding, Codex is designed to provide highly decentralized data storage with high durability, resiliency to cloud failures, and resistance to censorship. +Хотя ни одна система не может гарантировать абсолютную защиту от потери данных, благодаря своей технической архитектуре, экономическим стимулам и алгоритмическому кодированию, Codex разработан для обеспечения высоко децентрализованного хранения данных с высокой долговечностью, устойчивостью к сбоям облака и устойчивостью к цензуре. -## How Codex Works +## Как работает Codex -Codex operates as a network of storage nodes, referred to herein as **Storage Providers** (SP), that store user data for the duration of a contract entered into by SPs and storage users, referred to herein simply as **Clients**. +Codex работает как сеть узлов хранения, называемых здесь **Поставщиками Хранения** (SP), которые хранят пользовательские данные в течение срока контракта, заключенного между SP и пользователями хранения, называемыми здесь просто **Клиентами**. -Storage contracts are initiated by a **Client** requesting to store a specified amount of data, for a specified amount of time, and at a specific price per the full contract. **Storage Providers** commit to slots to store redundant fragments of this data. +Контракты на хранение инициируются **Клиентом**, запрашивающим хранение определенного объема данных на определенный срок и по определенной цене за весь контракт. **Поставщики Хранения** берут на себя обязательства по слотам для хранения избыточных фрагментов этих данных. -The fact that **SPs** must post collateral (stake) in order to fill a slot helps protect against Sybil attacks, promoting diversity in storage nodes fulfilling each contract. Additionally, this collateral acts as an economic incentive to ensure that **SPs** fulfill their obligations to periodically prove that they are still in possession of the data in question. +Тот факт, что **SP** должны размещать залог (стейкать) для заполнения слота, помогает защититься от атак Сибил, способствуя разнообразию узлов хранения, выполняющих каждый контракт. Кроме того, этот залог действует как экономический стимул для обеспечения того, чтобы **SP** выполняли свои обязательства по периодическому доказательству того, что они все еще владеют рассматриваемыми данными. -This is achieved by periodic challenges to **SPs** to provide cryptographic proofs that demonstrate the data they have contracted to store can be retrieved. Codex incorporates Zero Knowledge (ZK) and Data Availability Sampling (DAS) to achieve low-cost, highly efficient, and reliable data loss detection. +Это достигается путем периодических вызовов **SP** для предоставления криптографических доказательств, демонстрирующих, что данные, которые они обязались хранить, могут быть извлечены. Codex включает Zero Knowledge (ZK) и Data Availability Sampling (DAS) для достижения недорогого, высокоэффективного и надежного обнаружения потери данных. -**SPs** are required to respond to these challenges, sending their proofs to **Validators,** who verify the validity of the proofs and posts to the blockchain only the absence of a proof. This reduces costs of validating proofs, while not affecting the **Protocol**’s security. +**SP** должны отвечать на эти вызовы, отправляя свои доказательства **Валидаторам**, которые проверяют действительность доказательств и публикуют в блокчейне только отсутствие доказательства. Это снижает затраты на проверку доказательств, не влияя на безопасность **Протокола**. -Should SPs fail to prove a fixed number of times they still have the data in question, or send an invalid proof, their collateral is partially slashed. The slash penalty is a fixed percentage of the total collateral. This slashing continues until a certain number of slashings is reached, at which point the entire collateral is slashed. At this moment, the SP slot is considered “abandoned”. The slashed collateral is used as an incentive for a new **SP** to take over the failed slot through the “slot recovery mechanism” (discussed further later). This ensures the collateral provides an economic incentive to ensure the durability of the data. +Если SP не докажут фиксированное количество раз, что они все еще владеют рассматриваемыми данными, или отправят недействительное доказательство, их залог частично сокращается. Штраф за сокращение - это фиксированный процент от общего залога. Это сокращение продолжается до тех пор, пока не будет достигнуто определенное количество сокращений, после чего весь залог сокращается. В этот момент слот SP считается "оставленным". Сокращенный залог используется как стимул для нового **SP** взять на себя неудачный слот через "механизм восстановления слота" (обсуждается далее). Это гарантирует, что залог обеспечивает экономический стимул для обеспечения долговечности данных. -Codex is thus designed such that rational behavior for **SPs** consists of storing the data in the most space-efficient manner to minimize excess storage costs, while balancing the need for enough redundancy to recover from the possibility of data loss/corruption by the penalty of forfeiture of their collateral (slashing). +Таким образом, Codex разработан таким образом, что рациональное поведение для **SP** состоит в хранении данных наиболее эффективным с точки зрения пространства способом для минимизации избыточных затрат на хранение, при этом балансируя необходимость достаточной избыточности для восстановления от возможности потери/повреждения данных штрафом за конфискацию их залога (сокращение). -While Codex’s tech maximizes recoverability and durability in the event of partial data loss, Codex’s economic incentives coordinate rational actors to provide a stable and predictable environment for data storage users. At the heart of these economic incentives is the Codex utility token (CDX), which serves as the collateral to protect file durability and facilitate slot repair, and the means of payment to coordinate successful storage contracts. +Хотя технология Codex максимизирует восстанавливаемость и долговечность в случае частичной потери данных, экономические стимулы Codex координируют рациональных участников для обеспечения стабильной и предсказуемой среды для пользователей хранения данных. В основе этих экономических стимулов лежит утилитарный токен Codex (CDX), который служит залогом для защиты долговечности файлов и облегчения восстановления слотов, а также средством платежа для координации успешных контрактов на хранение. -# Contract Lifecycle +# Жизненный цикл контракта -The marketplace coordinates matching **Clients** who want to pay for storing files with **Storage Providers** who are offering storage space and posting collateral in order to earn payments for the contract. +Рынок координирует сопоставление **Клиентов**, которые хотят платить за хранение файлов, с **Поставщиками Хранения**, которые предлагают пространство для хранения и размещают залог для получения платежей по контракту. -## Contract Request Initiation +## Инициация запроса контракта -As a design principle, **Clients** should post the deal terms they are looking for, and Storage Providers prioritize which deals meet their criteria and pose the best deals to take. +Как принцип проектирования, **Клиенты** должны публиковать условия сделки, которые они ищут, а Поставщики Хранения определяют приоритеты, какие сделки соответствуют их критериям и представляют лучшие сделки для принятия. -When the contract request is created, the **Client** deposits the full price of the length of the contract at that time. This deposit acts as a spam prevention mechanism and ensures that **SP** time and resources are not wasted filling slots for deals that a **Client** does not complete payment for. +Когда создается запрос на контракт, **Клиент** вносит полную цену за длительность контракта на тот момент. Этот депозит действует как механизм предотвращения спама и гарантирует, что время и ресурсы **SP** не тратятся на заполнение слотов для сделок, за которые **Клиент** не завершает оплату. -## Storage Providers Fill Requests +## Поставщики Хранения заполняют запросы -Ahead of matching with storage contracts, **Storage Providers** specify their aggregate availabilities for new contracts. +Перед сопоставлением с контрактами на хранение **Поставщики Хранения** указывают свою совокупную доступность для новых контрактов. -Based on each **SPs’** availabilities, a queue is created for each **SP**, ranking the open **Client** request for contract deals with the most favorable deals at the top. Over time, this queue resolves by pairing **SPs** with contracts that are compatible with their availabilities, starting with the highest ranked deals first. +На основе доступности каждого **SP** создается очередь для каждого **SP**, ранжирующая открытые запросы **Клиента** на контрактные сделки с наиболее благоприятными сделками наверху. Со временем эта очередь разрешается путем сопоставления **SP** с контрактами, совместимыми с их доступностью, начиная с сделок с самым высоким рейтингом. -At launch, **SPs** will not be able to customize the queue creation algorithm, which means **SPs** with the same availabilities will have identical queues (other than differences due to a randomness function that increases **SP** diversity per each contract). In the future, **SPs** are expected to be able to customize their queue ranking algorithm. +При запуске **SP** не смогут настраивать алгоритм создания очереди, что означает, что **SP** с одинаковой доступностью будут иметь идентичные очереди (за исключением различий из-за функции случайности, которая увеличивает разнообразие **SP** для каждого контракта). В будущем ожидается, что **SP** смогут настраивать свой алгоритм ранжирования очереди. -If a **SP** matches with a storage contract and they're eligible to reserve a slot in the contract, they reserve an open slot, download the slot data from the **Client** or existing **SPs** whose data can be used to reconstruct the slot’s contents, create an initial storage proof, and submit this proof, along with collateral, to the **Protocol**. +Если **SP** сопоставляется с контрактом на хранение и они имеют право зарезервировать слот в контракте, они резервируют открытый слот, загружают данные слота от **Клиента** или существующих **SP**, чьи данные могут быть использованы для восстановления содержимого слота, создают начальное доказательство хранения и отправляют это доказательство вместе с залогом в **Протокол**. -Note that a slot is not considered confirmed as filled until after an **SP** both posts associated collateral and produces a proof for the slot. +Обратите внимание, что слот не считается подтвержденным как заполненный до тех пор, пока **SP** не разместит связанный залог и не создаст доказательство для слота. -## Contract Expires Before Beginning +## Контракт истекает до начала -If there are still empty slots when the timeout/expiry for the contract request expires, the deal is terminated. +Если все еще есть пустые слоты, когда истекает таймаут/срок действия запроса на контракт, сделка прекращается. -The **Storage Providers** who did fill slots, if any, are compensated for the amount of time which they did store the slot data, at the contract requests specified price per TB per Month. The remainder of the **Client**’s deposit is returned. +**Поставщики Хранения**, которые заполнили слоты, если таковые имеются, получают компенсацию за время, в течение которого они хранили данные слота, по указанной в запросе на контракт цене за ТБ в месяц. Остаток депозита **Клиента** возвращается. -As there is a high probability of having at least a few slots occupied, there should be no need for further penalties on the **Client** to prevent spam requests and incentivise **Clients** to submit attractive deals. +Поскольку существует высокая вероятность наличия хотя бы нескольких занятых слотов, не должно быть необходимости в дополнительных штрафах для **Клиента** для предотвращения спам-запросов и стимулирования **Клиентов** к подаче привлекательных сделок. -## Contract Begins +## Контракт начинается -The contract begins if *all* slots are occupied, that is, **SPs** have downloaded the data, posted collateral, and posted proofs before the timeout/expiry for the contract request is reached. +Контракт начинается, если *все* слоты заняты, то есть **SP** загрузили данные, разместили залог и опубликовали доказательства до достижения таймаута/срока действия запроса на контракт. -At this moment, a *protocol fee* is applied on the user’s deposit. The proceedings are burned. +В этот момент применяется *комиссия протокола* к депозиту пользователя. Поступления сжигаются. -The remaining of the client’s deposit is held by the protocol and will be used to pay **SPs** at the end of the contract. +Остаток депозита клиента удерживается протоколом и будет использоваться для оплаты **SP** в конце контракта. -## Contract is Running +## Контракт выполняется -**Storage Providers** must submit proofs to **Validators** according to the storage request’s proof frequency, a parameter set by the Client in the request. +**Поставщики Хранения** должны отправлять доказательства **Валидаторам** в соответствии с частотой доказательств запроса на хранение, параметром, установленным Клиентом в запросе. -### Missing Proofs +### Отсутствующие доказательства -If an **SP** fails to submit proofs within the rolling last periods, they are partially slashed. The penalty is a fixed percentage of the collateral. Upon provision of a proof after being partially slashed, the SP should top up the missing collateral. +Если **SP** не отправляет доказательства в течение последних периодов, они частично сокращаются. Штраф - это фиксированный процент от залога. После предоставления доказательства после частичного сокращения SP должен пополнить недостающий залог. -Should the SP be slashed enough times, their entire collateral will be slashed and confiscated, and the SP is considered to have abandoned its slot. The provision of a correct proof at this moment will not revert the start of the slot recovery mechanism. +Если SP будет сокращен достаточное количество раз, весь их залог будет сокращен и конфискован, и SP считается оставившим свой слот. Предоставление правильного доказательства в этот момент не отменит начало механизма восстановления слота. -## A Slot in the Contract is Abandoned +## Слот в контракте оставлен -When an **SP** fails to submit enough proofs such that they are slashed enough times, their slot is considered abandoned. In order to incentivize a new **SP** to come in and takeover the abandoned slot (slot recovery), 50% of the collateral confiscated from the **SP** which has abandoned the slot is used as an incentive to the new **SP**. The remaining confiscated collateral is burned. +Когда **SP** не отправляет достаточное количество доказательств, так что они сокращаются достаточное количество раз, их слот считается оставленным. Для стимулирования нового **SP** прийти и взять на себя оставленный слот (восстановление слота), 50% залога, конфискованного у **SP**, который оставил слот, используется как стимул для нового **SP**. Оставшийся конфискованный залог сжигается. -This helps align the economic incentive for **SPs** to take over abandoned slots before filling new deals, since they can effectively earn forfeited collateral for taking over and fulfilling abandoned slots. +Это помогает согласовать экономический стимул для **SP** взять на себя оставленные слоты перед заполнением новых сделок, поскольку они могут эффективно заработать конфискованный залог за взятие на себя и выполнение оставленных слотов. -## Contract Defaults +## Контракт не выполняется -If, at any time during the life of the storage contract, the number of slots currently in an abandoned state (not yet recovered), meets or exceeds the maximum number of storage slots that can be lost before the data is unrecoverable, then the entire storage deal is considered to be in a *failed* state. +Если в любой момент в течение срока действия контракта на хранение количество слотов, находящихся в оставленном состоянии (еще не восстановленных), достигает или превышает максимальное количество слотов хранения, которые могут быть потеряны до того, как данные станут невосстановимыми, то вся сделка хранения считается находящейся в состоянии *сбоя*. -Each **Storage Providers** posted collateral is burned. This incentivizes **SPs** not to let storage deals to be at risk of defaulting. **SPs** are incentivized to *proactively* avoid this by diversifying their infrastructure and the storage contracts they enter, and *reactively* by backing up their own slot data, or even backing up data from other slots so they can better assist slot recovery, as the deal approaches a failed state. +Каждый залог, размещенный **Поставщиками Хранения**, сжигается. Это стимулирует **SP** не допускать, чтобы сделки хранения подвергались риску невыполнения обязательств. **SP** стимулируются *проактивно* избегать этого путем диверсификации своей инфраструктуры и контрактов на хранение, в которые они вступают, и *реактивно* путем резервного копирования своих собственных данных слота или даже резервного копирования данных из других слотов, чтобы они могли лучше помочь восстановлению слота, когда сделка приближается к состоянию сбоя. -Clients also receive back any leftover from their original payment. +Клиенты также получают обратно любой остаток от их первоначального платежа. -## Contract Ends Its Full Duration +## Контракт завершает свой полный срок -When a started contract reaches its pre-specified duration without having previously defaulted, the contract completes. +Когда начатый контракт достигает своего предварительно указанного срока без предварительного невыполнения обязательств, контракт завершается. -All collateral is returned to **SPs t**hat currently fill the slots (note due to slot recovery these are not necessarily the same **SPs** that filled the slots at contract inception), and all remaining payment is returned to the client. +Весь залог возвращается **SP**, которые в настоящее время заполняют слоты (обратите внимание, что из-за восстановления слота это не обязательно те же **SP**, которые заполняли слоты при начале контракта), и весь оставшийся платеж возвращается клиенту. -Deals can not be automatically rolled forward or extended. If a **Client** desires to continue a deal, they must create a new storage contract request. Otherwise, Clients can retrieve their data. +Сделки не могут быть автоматически продлены или продлены. Если **Клиент** желает продолжить сделку, он должен создать новый запрос на контракт хранения. В противном случае Клиенты могут получить свои данные. -# CDX Testnet Tokenomics +# Токеномика CDX в тестовой сети -The CDX token does not exist in the Testnet Phase. The description below refers to the mechanics of a Testnet token and not CDX itself and will be referred to as *CDX (Testnet token)* for this purpose. +Токен CDX не существует в фазе тестовой сети. Описание ниже относится к механике тестового токена, а не к самому CDX, и для этой цели будет называться *CDX (тестовый токен)*. -For the avoidance of doubt, the *CDX (Testnet token)* are virtual items with no value of any kind and they are not convertible to any other currency, token, or any other form of property. They are solely intended to be utilised for the purposes of enabling the tokenomics and facilitating the different roles in this Testnet Phase. +Для избежания сомнений, *CDX (тестовый токен)* являются виртуальными предметами без какой-либо ценности и не конвертируются в какую-либо другую валюту, токен или любую другую форму собственности. Они предназначены исключительно для использования в целях включения токеномики и облегчения различных ролей в этой фазе тестовой сети. -## Roles +## Роли -The Codex protocol has two primary roles fulfilled by network participants. +Протокол Codex имеет две основные роли, выполняемые участниками сети. -- **Clients**: pay Storage Providers in *CDX (Testnet token)* to securely store their data on the Codex network for an agreed upon amount of time. -- **Storage Providers**: post *CDX (Testnet token)* collateral to enter into storage contracts with Clients in exchange for a *CDX (Testnet token)* denominated payment. -- **Validators**: post *CDX (Testnet token)* collateral to validate storage proofs in exchange for a *CDX (Testnet token)* denominated payment. +- **Клиенты**: платят Поставщикам Хранения в *CDX (тестовый токен)* за безопасное хранение своих данных в сети Codex на согласованный срок. +- **Поставщики Хранения**: размещают залог в *CDX (тестовый токен)* для вступления в контракты на хранение с Клиентами в обмен на платеж, номинированный в *CDX (тестовый токен)*. +- **Валидаторы**: размещают залог в *CDX (тестовый токен)* для проверки доказательств хранения в обмен на платеж, номинированный в *CDX (тестовый токен)*. -## Token Utility +## Утилита токена -The *CDX (Testnet token)* is used as both a form of posted collateral and a means of payment in order to secure the network and access its services. +*CDX (тестовый токен)* используется как форма размещенного залога и средство платежа для защиты сети и доступа к ее услугам. -Collateral is primarily used as a spam and sybil-attack prevention mechanism, liability insurance (e.g. compensating Clients in case of catastrophic loss of data), and to enforce rational behavior. +Залог в основном используется как механизм предотвращения спама и атак Сибил, страхование ответственности (например, компенсация Клиентам в случае катастрофической потери данных) и для обеспечения рационального поведения. -Payments are made by Clients to Providers for services rendered, such as for storing data for a certain amount of time or retrieving data. This is implemented through the Marketplace contract, which serves as an escrow. Data in a storage contract is distributed into slots where each is, ideally, hosted by a different Storage Provider. +Платежи производятся Клиентами Поставщикам за оказанные услуги, такие как хранение данных в течение определенного времени или извлечение данных. Это реализуется через контракт Marketplace, который служит эскроу. Данные в контракте хранения распределяются по слотам, где каждый, в идеале, размещается на разных Поставщиках Хранения. -### **For Clients** +### **Для Клиентов** -- Pay storage costs and fees in *CDX (Testnet token)* for storing files. +- Оплата затрат на хранение и комиссий в *CDX (тестовый токен)* за хранение файлов. -### **For Storage Providers** +### **Для Поставщиков Хранения** -- Post collateral in *CDX (Testnet token)* when committing to new storage contracts. This collateral is slashed if they do not fulfill their agreed upon services. -- Earn *CDX (Testnet token)* from the collateral of slashed Storage Providers by participating in the slot recovery mechanism. -- Earn *CDX (Testnet token)* from Clients when successfully completing the storage service. +- Размещение залога в *CDX (тестовый токен)* при принятии обязательств по новым контрактам хранения. Этот залог сокращается, если они не выполняют свои согласованные услуги. +- Заработок *CDX (тестовый токен)* от залога сокращенных Поставщиков Хранения путем участия в механизме восстановления слота. +- Заработок *CDX (тестовый токен)* от Клиентов при успешном завершении услуги хранения. -### For Validators +### Для Валидаторов -- Post collateral in *CDX (Testnet token)* to operate the validation service. This collateral is slashed if they do not mark a proof as missing within a predetermined period. -- Earn *CDX (Testnet token)* from the collateral of slashed Storage Providers by marking proofs as missed +- Размещение залога в *CDX (тестовый токен)* для работы службы валидации. Этот залог сокращается, если они не отмечают доказательство как отсутствующее в течение предопределенного периода. +- Заработок *CDX (тестовый токен)* от залога сокращенных Поставщиков Хранения путем отметки доказательств как пропущенных -Figure below depicts the flow of the *CDX (Testnet token)* token within the system. +На рисунке ниже показан поток *CDX (тестовый токен)* в системе. -![Flow of the *CDX token within the system](/learn/tokenomics-token-flow.png) +![Поток *CDX токена в системе](/learn/tokenomics-token-flow.png) -## Value Capture and Accrual Mechanisms +## Механизмы захвата и накопления стоимости -Codex creates *value* to participants: +Codex создает *ценность* для участников: -- Clients can benefit from storing data with strong durability guarantees; -- Storage Providers can earn yield from their spare resources or capital by providing a service. -- Validators earn payouts for marking proofs as missing. +- Клиенты могут получить выгоду от хранения данных с сильными гарантиями долговечности; +- Поставщики Хранения могут получать доход от своих свободных ресурсов или капитала, предоставляя услугу. +- Валидаторы получают выплаты за отметку доказательств как отсутствующих. -Clients need *CDX (Testnet token)* tokens to request storage deals. *CDX (Testnet token)* captures the value created to Clients by being a *Value Transfer Token* to them. +Клиентам нужны токены *CDX (тестовый токен)* для запроса сделок хранения. *CDX (тестовый токен)* захватывает ценность, созданную для Клиентов, будучи для них *Токеном Передачи Ценности*. -Storage Providers and Validators are rewarded in *CDX (Testnet token)* token and also need it as a proof of commitment to the Protocol. They risk being slashed in exchange for rewards. *CDX (Testnet token)* captures the value created to Providers by being a *Work Token* to them. +Поставщики Хранения и Валидаторы вознаграждаются токеном *CDX (тестовый токен)* и также нуждаются в нем как в доказательстве приверженности Протоколу. Они рискуют быть сокращенными в обмен на вознаграждения. *CDX (тестовый токен)* захватывает ценность, созданную для Поставщиков, будучи для них *Токеном Работы*. -The following mechanisms describe how the value accrues to the *CDX (Testnet token)* token. +Следующие механизмы описывают, как ценность накапливается в токене *CDX (тестовый токен)*. -### Protocol Fee over Contracts +### Комиссия протокола за контракты -If the contract is canceled before it starts, Client's deposited amount is charged a small penalty and returned, aiding to prevent low quality spam deal requests. +Если контракт отменяется до его начала, с депонированной суммы Клиента взимается небольшой штраф и возвращается, что помогает предотвратить запросы сделок низкого качества спама. -If the contract successfully initiates, the protocol collects a fee for facilitating the transaction. The remaining amount is made available for payments to Storage Providers. +Если контракт успешно инициируется, протокол взимает комиссию за облегчение транзакции. Оставшаяся сумма становится доступной для платежей Поставщикам Хранения. -The collected fees are burned in both cases. This creates a small but constant deflationary force on the token supply, which is proportional to the product demand. +Собранные комиссии сжигаются в обоих случаях. Это создает небольшую, но постоянную дефляционную силу на предложение токена, которая пропорциональна спросу на продукт. -## Behavior & Motivations +## Поведение и мотивации -### Clients +### Клиенты -Clients have the following rational behavior: +Клиенты имеют следующее рациональное поведение: -- Requesting storage from the network with a fee at fair market rates -- Providing data to storage nodes that meet their criteria +- Запрос хранения от сети с комиссией по справедливым рыночным ставкам +- Предоставление данных узлам хранения, которые соответствуют их критериям -They may also exhibit the following adversarial behavior, whether for profit driven, malicious, or censorship motivations: +Они также могут демонстрировать следующее враждебное поведение, будь то по мотивам прибыли, злонамеренности или цензуры: -- Requesting storage from the network but never making the data available for any or all slots -- Requesting storage from the network but not releasing the data within required time period to begin the contract successfully -- Requesting storage from the network but not releasing the data to specific Providers -- Attacking SPs that host their data to attempt to relieve their payment obligations at the end of the contract. +- Запрос хранения от сети, но никогда не предоставление данных доступными для любых или всех слотов +- Запрос хранения от сети, но не предоставление данных в течение требуемого периода времени для успешного начала контракта +- Запрос хранения от сети, но не предоставление данных конкретным Поставщикам +- Атака на SP, которые размещают их данные, чтобы попытаться освободить свои платежные обязательства в конце контракта. -### **Storage Providers** +### **Поставщики Хранения** -Storage Providers have the following rational behavior: +Поставщики Хранения имеют следующее рациональное поведение: -- Committing to slots of storage contracts to earn a fee. -- Providing proofs of storage for their committed slots to avoid collateral slashing penalties. -- Releasing the data to anyone who requests it. -- Committing to failed slots of storage contracts to maintain the integrity of the data +- Принятие обязательств по слотам контрактов хранения для получения комиссии. +- Предоставление доказательств хранения для их обязательных слотов для избежания штрафов за сокращение залога. +- Предоставление данных любому, кто их запрашивает. +- Принятие обязательств по неудачным слотам контрактов хранения для поддержания целостности данных -They may also exhibit the following adversarial behavior, whether for profit driven, malicious, or censorship motivations: +Они также могут демонстрировать следующее враждебное поведение, будь то по мотивам прибыли, злонамеренности или цензуры: -- Reserving a contract slot but never filling it (attempt to prevent contract from starting) -- Ceasing to provide proofs mid the lifespan of a contract -- Producing proofs, but not making data available for other nodes to retrieve +- Резервирование слота контракта, но никогда его заполнение (попытка предотвратить начало контракта) +- Прекращение предоставления доказательств в середине срока действия контракта +- Создание доказательств, но не предоставление данных доступными для других узлов для извлечения -### Validators +### Валидаторы -Validators have the following rational behavior: +Валидаторы имеют следующее рациональное поведение: -- Marking a proof as missing to earn a fee -- Tracking the history of missed proofs of a **SP** -- Triggering the Slot Recovery Mechanism when an **SP** reaches the maximum allowed number of missed proofs +- Отметка доказательства как отсутствующего для получения комиссии +- Отслеживание истории пропущенных доказательств **SP** +- Запуск механизма восстановления слота, когда **SP** достигает максимально допустимого количества пропущенных доказательств -They may also exhibit the following adversarial behavior, whether for profit driven, malicious, or censorship motivations: +Они также могут демонстрировать следующее враждебное поведение, будь то по мотивам прибыли, злонамеренности или цензуры: -- Colluding with SPs to ignore missed proofs -- Observing a missed proof but do not post it onchain +- Сговор с SP для игнорирования пропущенных доказательств +- Наблюдение пропущенного доказательства, но не публикация его в блокчейне -## Incentive Mechanisms +## Механизмы стимулирования -The following mechanisms help incentivize the expected behavior of each role and mitigate the detrimental ones. +Следующие механизмы помогают стимулировать ожидаемое поведение каждой роли и смягчать вредные. -### Clients Provide Full Payment Upfront +### Клиенты предоставляют полную оплату заранее -Clients must deposit the full amount in *CDX (Testnet token)* that covers the entirety of the storage contract duration upfront. This indicates their pledge to pay a certain amount for the storage contract, though the contract only begins when and if all data slots are filled by Storage Providers. +Клиенты должны внести полную сумму в *CDX (тестовый токен)*, которая покрывает весь срок действия контракта хранения заранее. Это указывает на их обязательство заплатить определенную сумму за контракт хранения, хотя контракт начинается только тогда и если все слоты данных заполнены Поставщиками Хранения. -### Delayed Payment to Storage Providers +### Отложенный платеж Поставщикам Хранения -Storage Providers only receive payment related to the provision of services at the end of the contract duration. +Поставщики Хранения получают платеж, связанный с предоставлением услуг, только в конце срока действия контракта. -### Collateral Requirement +### Требование залога -In order to fill a data slot, Storage Providers first stake and commit the required collateral in the form of the *CDX (Testnet token)* for that slot which is then subject to slashing if they do not post a proof to confirm the slot. +Для заполнения слота данных Поставщики Хранения сначала размещают и обязуются предоставить требуемый залог в форме *CDX (тестовый токен)* для этого слота, который затем подлежит сокращению, если они не публикуют доказательство для подтверждения слота. -Validators also need to post collateral to participate in the validation service. +Валидаторы также должны размещать залог для участия в службе валидации. -### Proof of Storage +### Доказательство хранения -Contracts only start when all data slots are filled. Slots are only considered filled after a Storage Provider has posted collateral and the associated proof for its slot. +Контракты начинаются только тогда, когда все слоты данных заполнены. Слоты считаются заполненными только после того, как Поставщик Хранения разместил залог и связанное с ним доказательство для своего слота. -Once the contract begins, Storage Providers regularly provide proof of storage. +После начала контракта Поставщики Хранения регулярно предоставляют доказательство хранения. -### **Slashing for Missed Proofs of Storage** +### **Сокращение за пропущенные доказательства хранения** -At any point during the duration of the storage contract, the storage provider is slashed if it fails to provide a certain number of proof of storage in a row. Should the SP resume providing proof of storage, it needs to top up the slashed collateral. The penalty is a fixed percentage of the total collateral. +В любой момент в течение срока действия контракта на хранение поставщик хранения сокращается, если он не предоставляет определенное количество доказательств хранения подряд. Если SP возобновляет предоставление доказательств хранения, он должен пополнить сокращенный залог. Штраф представляет собой фиксированный процент от общего залога. -### Slot Recovery Mechanism +### Механизм восстановления слота -If a Storage Provider does not submit the required storage proofs when required, after a number of slashings their entire collateral will be seized. A portion of the confiscated collateral is used as an incentive for the new Storage Provider who recovers and starts serving the abandoned slot. The remainder of the confiscated collateral in *CDX (Testnet token)* is burned. +Если поставщик хранения не отправляет требуемые доказательства хранения, когда это необходимо, после определенного количества сокращений весь его залог будет конфискован. Часть конфискованного залога используется как стимул для нового поставщика хранения, который восстанавливает и начинает обслуживать оставленный слот. Оставшаяся часть конфискованного залога в *CDX (тестовый токен)* сжигается. -### Slashing Defaulted Contract +### Сокращение невыполненного контракта -If, at any point during the duration of the storage contract, the number of data slots currently abandoned (and not yet recovered) reaches or surpasses the maximum allowable lost slots (meaning the data becomes irretrievable), then the entire storage contract is deemed to be *failed*. +Если в любой момент в течение срока действия контракта на хранение количество оставленных (и еще не восстановленных) слотов данных достигает или превышает максимально допустимое количество потерянных слотов (что означает, что данные становятся невосстанавливаемыми), то весь контракт на хранение считается *невыполненным*. -At this stage, collaterals of all Storage Providers serving data slots in the contract are entirely slashed. +На этом этапе залоги всех поставщиков хранения, обслуживающих слоты данных в контракте, полностью сокращаются. -### Client Reimbursement +### Возмещение клиентам -If at any point during the contract, sufficient slots are abandoned such that the data is not fully recoverable, Clients receive back any leftover from their original payment. +Если в любой момент в течение контракта достаточное количество слотов оставлено, так что данные не могут быть полностью восстановлены, клиенты получают обратно любой остаток от их первоначального платежа. -## Token Lifecycle +## Жизненный цикл токена -### Burning +### Сжигание -*CDX (Testnet token)* tokens are burned in these instances: +*CDX (тестовый токен)* сжигаются в следующих случаях: -- When a storage deal contract fails to initiate, a small portion of the Client's payment for the storage deal is burned. This serves primarily as a mechanism to deter spam and ensure that deal requests are submitted at market-appropriate prices for storage. -- When a storage deal contract successfully initiates, the protocol applies a fee for facilitating the transaction. -- Whenever a Storage Provider misses a certain number of storage proofs, a portion of the collateral is slashed and burned. -- Once the slot recovery mechanism resolves, the remaining of the abandoning Storage Provider’s collateral is burned. +- Когда контракт на хранение не может быть инициирован, небольшая часть платежа клиента за сделку хранения сжигается. Это служит в первую очередь механизмом для предотвращения спама и обеспечения того, чтобы запросы сделок подавались по рыночным ценам для хранения. +- Когда контракт на хранение успешно инициируется, протокол взимает комиссию за облегчение транзакции. +- Когда поставщик хранения пропускает определенное количество доказательств хранения, часть залога сокращается и сжигается. +- После разрешения механизма восстановления слота оставшаяся часть залога оставившего поставщика хранения сжигается. diff --git a/learn/troubleshoot.md b/learn/troubleshoot.md index a9e0eee..5841f4c 100644 --- a/learn/troubleshoot.md +++ b/learn/troubleshoot.md @@ -1,30 +1,30 @@ --- outline: [2, 3] --- -# Troubleshoot +# Устранение неполадок -Having trouble getting your Codex node connected to the testnet? Here's a list of common Codex connection conundrums and steps to diagnose and solve them. If your troubles are not addressed here, check our open issues on Github or reach out via our Discord server. +Проблемы с подключением вашего узла Codex к тестовой сети? Вот список распространенных проблем подключения Codex и шаги для их диагностики и решения. Если ваши проблемы не рассматриваются здесь, проверьте наши открытые проблемы на Github или свяжитесь с нами через наш Discord-сервер. -## Some basics +## Основы -You've probably already considered these. But just in case: +Вы, вероятно, уже рассмотрели это. Но на всякий случай: -1. Are you using a VPN? Make sure it's configured correctly to forward the right ports, and make sure you announce your node by the public IP address where you can be reached. -1. Are you using a firewall or other security software? Make sure it's configured to allow incoming connections to Codex's discovery and peer-to-peer ports. +1. Используете ли вы VPN? Убедитесь, что он правильно настроен для переадресации нужных портов, и убедитесь, что вы объявляете свой узел по публичному IP-адресу, по которому к вам можно обратиться. +1. Используете ли вы брандмауэр или другое программное обеспечение безопасности? Убедитесь, что он настроен на разрешение входящих подключений к портам обнаружения и одноранговой сети Codex. -## Check your announce address +## Проверьте ваш объявляемый адрес -Your node announces your public address to the network, so other nodes can connect to you. A common issue is connection failure due to incorrect announce addresses. Follow these steps to check your announce address. +Ваш узел объявляет ваш публичный адрес в сети, чтобы другие узлы могли подключиться к вам. Распространенной проблемой является сбой подключения из-за неправильных объявляемых адресов. Следуйте этим шагам, чтобы проверить ваш объявляемый адрес. -1. Go to a whats-my-ip site, or `ip.codex.storage` and note the IP address. -1. Go into your router/modem WAN settings and find the public IP address. -1. These two addresses should match. -1. If they do not, it's possible that A) you're behind a VPN. In this case, it's up to you to disable the VPN or make sure all forwarding is configured correctly. or B) Your internet-service-provider has placed your uplink behind a secondary NAT. ISPs do this to save public IP addresses. The address assigned to your router/moderm is not a 'true' public internet address. Usually this issue can be solved by your ISP. Contact customer support and ask them to give you a public address (sometimes also called Dynamic IP address). -1. Call Codex's debug/info endpoint. See the [Using Codex](/learn/using) for the details. -1. In the JSON response, you'll find "announceAddresses". -1. The IP address listed there should match your public IP. -1. If the announce address in the JSON is incorrect, you can adjust it manually by changing Codex's CLI argument `--nat` or setting the environment variable `CODEX_NAT`. After you've changed your announce address and restarted your node, please allow some time (20-30mins) for the network to disseminate the updated address. +1. Перейдите на сайт whats-my-ip или `ip.codex.storage` и запишите IP-адрес. +1. Перейдите в настройки WAN вашего маршрутизатора/модема и найдите публичный IP-адрес. +1. Эти два адреса должны совпадать. +1. Если они не совпадают, возможно, что A) вы находитесь за VPN. В этом случае вам нужно отключить VPN или убедиться, что вся переадресация настроена правильно. или B) Ваш интернет-провайдер поместил ваше восходящее соединение за вторичным NAT. Интернет-провайдеры делают это для экономии публичных IP-адресов. Адрес, назначенный вашему маршрутизатору/модему, не является "истинным" публичным интернет-адресом. Обычно эту проблему может решить ваш интернет-провайдер. Свяжитесь со службой поддержки и попросите их предоставить вам публичный адрес (иногда также называемый динамическим IP-адресом). +1. Вызовите конечную точку отладки/информации Codex. Смотрите [Использование Codex](/learn/using) для подробностей. +1. В JSON-ответе вы найдете "announceAddresses". +1. IP-адрес, указанный там, должен соответствовать вашему публичному IP. +1. Если объявляемый адрес в JSON неверен, вы можете настроить его вручную, изменив аргумент командной строки Codex `--nat` или установив переменную окружения `CODEX_NAT`. После того, как вы изменили свой объявляемый адрес и перезапустили узел, пожалуйста, дайте некоторое время (20-30 минут) для распространения обновленного адреса в сети. -If you've performed these steps and haven't found any issues, your announce address is probably not the problem. +Если вы выполнили эти шаги и не нашли никаких проблем, ваш объявляемый адрес, вероятно, не является проблемой. diff --git a/learn/using.md b/learn/using.md index 5ad8044..3078dd8 100644 --- a/learn/using.md +++ b/learn/using.md @@ -1,38 +1,38 @@ --- outline: [2, 3] --- -# Using Codex +# Использование Codex -We can interact with Codex using [REST API](/developers/api). This document will show you several useful examples. +Мы можем взаимодействовать с Codex, используя [REST API](/developers/api). В этом документе показаны несколько полезных примеров. -Also, we can check [Codex App UI](https://app.codex.storage). +Также мы можем использовать [Пользовательский интерфейс приложения Codex](https://app.codex.storage). -Command line interpreter on [Linux/macOS](#linux-macos) and [Windows](#windows) works slightly different, so please use steps for your OS. +Интерпретатор командной строки работает немного по-разному на [Linux/macOS](#linux-macos) и [Windows](#windows), поэтому используйте инструкции для вашей ОС. ## Linux/macOS -### Overview -1. [Debug](#debug) -2. [Upload a file](#upload-a-file) -3. [Download a file](#download-a-file) -4. [Local data](#local-data) -5. [Create storage availability](#create-storage-availability) -6. [Purchase storage](#purchase-storage) -7. [View purchase status](#view-purchase-status) +### Обзор +1. [Отладка](#debug) +2. [Загрузка файла](#upload-a-file) +3. [Скачивание файла](#download-a-file) +4. [Локальные данные](#local-data) +5. [Создание доступности хранилища](#create-storage-availability) +6. [Покупка хранилища](#purchase-storage) +7. [Просмотр статуса покупки](#view-purchase-status) -### Debug -An easy way to check that your node is up and running is: +### Отладка +Простой способ проверить, что ваш узел запущен и работает: ```shell curl http://localhost:8080/api/codex/v1/debug/info \ -w '\n' ``` -This will return a JSON structure with plenty of information about your local node. It contains peer information that may be useful when troubleshooting connection issues. +Это вернет JSON-структуру с множеством информации о вашем локальном узле. Она содержит информацию о пирах, которая может быть полезна при устранении проблем с подключением. -### Upload a file +### Загрузка файла > [!Warning] -> Once you upload a file to Codex, other nodes in the network can download it. Please do not upload anything you don't want others to access, or, properly encrypt your data *first*. +> После загрузки файла в Codex другие узлы в сети могут его скачать. Пожалуйста, не загружайте ничего, что вы не хотите, чтобы другие видели, или правильно зашифруйте ваши данные *перед загрузкой*. ```shell curl -X POST \ @@ -42,16 +42,16 @@ curl -X POST \ -T ``` -On successful upload, you'll receive a CID. This can be used to download the file from any node in the network. +При успешной загрузке вы получите CID. Его можно использовать для скачивания файла с любого узла в сети. > [!TIP] -> Are you on the [Codex Discord server](https://discord.gg/codex-storage)? Post your CID in the [# :wireless: | share-cids](https://discord.com/channels/895609329053474826/1278383098102284369) channel, see if others are able to download it. Codex does not (yet?) provide file metadata, so if you want others to be able to open your file, tell them which extension to give it. +> Вы на [сервере Discord Codex](https://discord.gg/codex-storage)? Опубликуйте ваш CID в канале [# :wireless: | share-cids](https://discord.com/channels/895609329053474826/1278383098102284369), посмотрите, смогут ли другие его скачать. Codex пока не предоставляет метаданные файлов, поэтому если вы хотите, чтобы другие могли открыть ваш файл, скажите им, какое расширение ему дать. -### Download a file -When you have a CID of data you want to download, you can use the following commands: +### Скачивание файла +Когда у вас есть CID данных, которые вы хотите скачать, вы можете использовать следующие команды: ```shell -# paste your CID from the previous step here between the quotes +# вставьте ваш CID из предыдущего шага между кавычками CID="..." ``` @@ -60,21 +60,21 @@ curl "http://localhost:8080/api/codex/v1/data/${CID}/network/stream" \ -o "${CID}.png" ``` -Please use the correct extension for the downloaded file, because Codex does not store yet content-type or extension information. +Пожалуйста, используйте правильное расширение для скачанного файла, потому что Codex пока не хранит информацию о типе содержимого или расширении. -### Local data -You can view which datasets are currently being stored by your node: +### Локальные данные +Вы можете просмотреть, какие наборы данных в настоящее время хранятся вашим узлом: ```shell curl http://localhost:8080/api/codex/v1/data \ -w '\n' ``` -### Create storage availability +### Создание доступности хранилища > [!WARNING] -> This step requires that Codex was started with the [`prover`](/learn/run#codex-storage-node) option. +> Этот шаг требует, чтобы Codex был запущен с опцией [`prover`](/learn/run#codex-storage-node). -In order to start selling storage space to the network, you must configure your node with the following command. Once configured, the node will monitor on-chain requests-for-storage and will automatically enter into contracts that meet these specifications. In order to enter and maintain storage contracts, your node is required to submit zero-knowledge storage proofs. The calculation of these proofs will increase the CPU and RAM usage of Codex. +Чтобы начать продавать пространство для хранения в сети, вы должны настроить ваш узел с помощью следующей команды. После настройки узел будет отслеживать запросы на хранение в блокчейне и автоматически вступать в контракты, соответствующие этим спецификациям. Для вступления и поддержания контрактов на хранение ваш узел должен предоставлять доказательства хранения с нулевым разглашением. Расчет этих доказательств увеличит использование CPU и RAM Codex. ```shell curl -X POST \ @@ -89,20 +89,20 @@ curl -X POST \ }' ``` -For descriptions of each parameter, please view the [spec](https://api.codex.storage/#tag/Marketplace/operation/offerStorage). +Для описания каждого параметра, пожалуйста, просмотрите [спецификацию](https://api.codex.storage/#tag/Marketplace/operation/offerStorage). -### Purchase storage -To purchase storage space from the network, first you must upload your data. Once you have the CID, use the following to create a request-for-storage. +### Покупка хранилища +Чтобы купить пространство для хранения в сети, сначала вы должны загрузить ваши данные. После получения CID используйте следующее для создания запроса на хранение. -Set your CID: +Установите ваш CID: ```shell -# paste your CID from the previous step here between the quotes +# вставьте ваш CID из предыдущего шага между кавычками CID="..." echo "CID: ${CID}" ``` -Next you can run: +Затем вы можете выполнить: ```shell curl -X POST \ @@ -119,59 +119,59 @@ curl -X POST \ }' ``` -For descriptions of each parameter, please view the [spec](https://api.codex.storage/#tag/Marketplace/operation/createStorageRequest). +Для описания каждого параметра, пожалуйста, просмотрите [спецификацию](https://api.codex.storage/#tag/Marketplace/operation/createStorageRequest). -When successful, this request will return a Purchase-ID. +При успешном выполнении этот запрос вернет Purchase-ID. -### View purchase status -Using a Purchase-ID, you can check the status of your request-for-storage contract: +### Просмотр статуса покупки +Используя Purchase-ID, вы можете проверить статус вашего контракта на хранение: ```shell -# paste your PURCHASE_ID from the previous step here between the quotes +# вставьте ваш PURCHASE_ID из предыдущего шага между кавычками PURCHASE_ID="..." ``` -Then: +Затем: ```shell curl "http://localhost:8080/api/codex/v1/storage/purchases/${PURCHASE_ID}" \ -w '\n' ``` -This will display state and error information for your purchase. -| State | Description | -|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| Pending | Request is waiting for chain confirmation. | -| Submitted | Request is on-chain. Hosts may now attempt to download the data. | -| Started | Hosts have downloaded the data and provided proof-of-storage. | -| Failed | The request was started, but (too many) hosts failed to provide proof-of-storage on time. While the data may still be available in the network, for the purpose of the purchase it is considered lost. | -| Finished | The request was started successfully and the duration has elapsed. | -| Expired | (Not enough) hosts have submitted proof-of-storage before the request's expiry elapsed. | -| Errored | An unfortunate state of affairs. The 'error' field should tell you more. | +Это отобразит информацию о состоянии и ошибках для вашей покупки. +| Состояние | Описание | +|------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Pending | Запрос ожидает подтверждения в блокчейне. | +| Submitted | Запрос находится в блокчейне. Хосты теперь могут попытаться скачать данные. | +| Started | Хосты скачали данные и предоставили доказательство хранения. | +| Failed | Запрос был начат, но (слишком много) хостов не смогли предоставить доказательство хранения вовремя. Хотя данные все еще могут быть доступны в сети, для целей покупки они считаются утерянными. | +| Finished | Запрос был успешно начат, и срок действия истек. | +| Expired | (Недостаточно) хостов предоставили доказательство хранения до истечения срока действия запроса. | +| Errored | Неудачное состояние. Поле 'error' должно рассказать больше. | ## Windows -### Overview {#overview-windows} -1. [Debug](#debug-windows) -2. [Upload a file](#upload-a-file-windows) -3. [Download a file](#download-a-file-windows) -4. [Local data](#local-data-windows) -5. [Create storage availability](#create-storage-availability-windows) -6. [Purchase storage](#purchase-storage-windows) -7. [View purchase status](#view-purchase-status-windows) +### Обзор {#overview-windows} +1. [Отладка](#debug-windows) +2. [Загрузка файла](#upload-a-file-windows) +3. [Скачивание файла](#download-a-file-windows) +4. [Локальные данные](#local-data-windows) +5. [Создание доступности хранилища](#create-storage-availability-windows) +6. [Покупка хранилища](#purchase-storage-windows) +7. [Просмотр статуса покупки](#view-purchase-status-windows) -### Debug {#debug-windows} -An easy way to check that your node is up and running is: +### Отладка {#debug-windows} +Простой способ проверить, что ваш узел запущен и работает: ```batch curl http://localhost:8080/api/codex/v1/debug/info ``` -This will return a JSON structure with plenty of information about your local node. It contains peer information that may be useful when troubleshooting connection issues. +Это вернет JSON-структуру с множеством информации о вашем локальном узле. Она содержит информацию о пирах, которая может быть полезна при устранении проблем с подключением. -### Upload a file {#upload-a-file-windows} +### Загрузка файла {#upload-a-file-windows} > [!Warning] -> Once you upload a file to Codex, other nodes in the network can download it. Please do not upload anything you don't want others to access, or, properly encrypt your data *first*. +> После загрузки файла в Codex другие узлы в сети могут его скачать. Пожалуйста, не загружайте ничего, что вы не хотите, чтобы другие видели, или правильно зашифруйте ваши данные *перед загрузкой*. ```batch curl -X POST ^ @@ -180,16 +180,16 @@ curl -X POST ^ -T ``` -On successful upload, you'll receive a CID. This can be used to download the file from any node in the network. +При успешной загрузке вы получите CID. Его можно использовать для скачивания файла с любого узла в сети. > [!TIP] -> Are you on the [Codex Discord server](https://discord.gg/codex-storage)? Post your CID in the [# :wireless: | share-cids](https://discord.com/channels/895609329053474826/1278383098102284369) channel, see if others are able to download it. Codex does not (yet?) provide file metadata, so if you want others to be able to open your file, tell them which extension to give it. +> Вы на [сервере Discord Codex](https://discord.gg/codex-storage)? Опубликуйте ваш CID в канале [# :wireless: | share-cids](https://discord.com/channels/895609329053474826/1278383098102284369), посмотрите, смогут ли другие его скачать. Codex пока не предоставляет метаданные файлов, поэтому если вы хотите, чтобы другие могли открыть ваш файл, скажите им, какое расширение ему дать. -### Download a file {#download-a-file-windows} -When you have a CID of data you want to download, you can use the following commands: +### Скачивание файла {#download-a-file-windows} +Когда у вас есть CID данных, которые вы хотите скачать, вы можете использовать следующие команды: ```batch -:: paste your CID from the previous step here between the quotes +:: вставьте ваш CID из предыдущего шага между кавычками set CID="..." ``` @@ -198,20 +198,20 @@ curl "http://localhost:8080/api/codex/v1/data/%CID%/network/stream" ^ -o "%CID%.png" ``` -Please use the correct extension for the downloaded file, because Codex does not store yet content-type or extension information. +Пожалуйста, используйте правильное расширение для скачанного файла, потому что Codex пока не хранит информацию о типе содержимого или расширении. -### Local data {#local-data-windows} -You can view which datasets are currently being stored by your node: +### Локальные данные {#local-data-windows} +Вы можете просмотреть, какие наборы данных в настоящее время хранятся вашим узлом: ```batch curl http://localhost:8080/api/codex/v1/data ``` -### Create storage availability {#create-storage-availability-windows} +### Создание доступности хранилища {#create-storage-availability-windows} > [!WARNING] -> This step requires that Codex was started with the [`prover`](/learn/run#codex-storage-node) option. +> Этот шаг требует, чтобы Codex был запущен с опцией [`prover`](/learn/run#codex-storage-node). -In order to start selling storage space to the network, you must configure your node with the following command. Once configured, the node will monitor on-chain requests-for-storage and will automatically enter into contracts that meet these specifications. In order to enter and maintain storage contracts, your node is required to submit zero-knowledge storage proofs. The calculation of these proofs will increase the CPU and RAM usage of Codex. +Чтобы начать продавать пространство для хранения в сети, вы должны настроить ваш узел с помощью следующей команды. После настройки узел будет отслеживать запросы на хранение в блокчейне и автоматически вступать в контракты, соответствующие этим спецификациям. Для вступления и поддержания контрактов на хранение ваш узел должен предоставлять доказательства хранения с нулевым разглашением. Расчет этих доказательств увеличит использование CPU и RAM Codex. ```batch curl -X POST ^ @@ -220,20 +220,20 @@ curl -X POST ^ -d "{""totalSize"": ""8000000"", ""duration"": ""7200"", ""minPricePerBytePerSecond"": ""1000"", ""totalCollateral"": ""80000000""}" ``` -For descriptions of each parameter, please view the [spec](https://api.codex.storage/#tag/Marketplace/operation/offerStorage). +Для описания каждого параметра, пожалуйста, просмотрите [спецификацию](https://api.codex.storage/#tag/Marketplace/operation/offerStorage). -### Purchase storage {#purchase-storage-windows} -To purchase storage space from the network, first you must upload your data. Once you have the CID, use the following to create a request-for-storage. +### Покупка хранилища {#purchase-storage-windows} +Чтобы купить пространство для хранения в сети, сначала вы должны загрузить ваши данные. После получения CID используйте следующее для создания запроса на хранение. -Set your CID: +Установите ваш CID: ```batch -:: paste your CID from the previous step here between the quotes +:: вставьте ваш CID из предыдущего шага между кавычками set CID="..." echo CID: %CID% ``` -Next you can run: +Затем вы можете выполнить: ```batch curl -X POST ^ @@ -242,34 +242,34 @@ curl -X POST ^ -d "{""duration"": ""3600"",""pricePerBytePerSecond"": ""2000"", ""proofProbability"": ""5"", ""expiry"": ""1200"", ""nodes"": 5, ""tolerance"": 2, ""**collateralPerByte**"": ""1""}" ``` -For descriptions of each parameter, please view the [spec](https://api.codex.storage/#tag/Marketplace/operation/createStorageRequest). +Для описания каждого параметра, пожалуйста, просмотрите [спецификацию](https://api.codex.storage/#tag/Marketplace/operation/createStorageRequest). -When successful, this request will return a Purchase-ID. +При успешном выполнении этот запрос вернет Purchase-ID. -### View purchase status {#view-purchase-status-windows} -Using a Purchase-ID, you can check the status of your request-for-storage contract: +### Просмотр статуса покупки {#view-purchase-status-windows} +Используя Purchase-ID, вы можете проверить статус вашего контракта на хранение: ```batch -:: paste your PURCHASE_ID from the previous step here between the quotes +:: вставьте ваш PURCHASE_ID из предыдущего шага между кавычками set PURCHASE_ID="..." ``` -Then: +Затем: ```batch curl "http://localhost:8080/api/codex/v1/storage/purchases/%PURCHASE_ID%" ``` -This will display state and error information for your purchase. -| State | Description | -|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| Pending | Request is waiting for chain confirmation. | -| Submitted | Request is on-chain. Hosts may now attempt to download the data. | -| Started | Hosts have downloaded the data and provided proof-of-storage. | -| Failed | The request was started, but (too many) hosts failed to provide proof-of-storage on time. While the data may still be available in the network, for the purpose of the purchase it is considered lost. | -| Finished | The request was started successfully and the duration has elapsed. | -| Expired | (Not enough) hosts have submitted proof-of-storage before the request's expiry elapsed. | -| Errored | An unfortunate state of affairs. The 'error' field should tell you more. | +Это отобразит информацию о состоянии и ошибках для вашей покупки. +| Состояние | Описание | +|------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Pending | Запрос ожидает подтверждения в блокчейне. | +| Submitted | Запрос находится в блокчейне. Хосты теперь могут попытаться скачать данные. | +| Started | Хосты скачали данные и предоставили доказательство хранения. | +| Failed | Запрос был начат, но (слишком много) хостов не смогли предоставить доказательство хранения вовремя. Хотя данные все еще могут быть доступны в сети, для целей покупки они считаются утерянными. | +| Finished | Запрос был успешно начат, и срок действия истек. | +| Expired | (Недостаточно) хостов предоставили доказательство хранения до истечения срока действия запроса. | +| Errored | Неудачное состояние. Поле 'error' должно рассказать больше. | ## Known issues 1. We add a new line to the API calls to get more readable output, please check [[rest] Add line ending on responses #771](https://github.com/codex-storage/nim-codex/issues/771) for more details. diff --git a/learn/what-is-codex.md b/learn/what-is-codex.md index d8096fd..f45c8f0 100644 --- a/learn/what-is-codex.md +++ b/learn/what-is-codex.md @@ -1,39 +1,39 @@ -# What is Codex? +# Что такое Codex? -Codex is a decentralised data storage protocol. Its primary features are strong censorship resistance and durability guarantees. It has a reference implementation by the same name, written in nim. It serves as the storage layer of the [Logos](https://logos.co/) tech stack. Alongside the trustless agreement layer, [Nomos](http://nomos.tech), and the communications layer, [Waku](http://waku.org), it is one of the Logos Collective's foundational projects. +Codex - это децентрализованный протокол хранения данных. Его основные особенности - сильная устойчивость к цензуре и гарантии долговечности. Он имеет эталонную реализацию с тем же названием, написанную на nim. Он служит слоем хранения в стеке технологий [Logos](https://logos.co/). Наряду с уровнем бездоверительных соглашений [Nomos](http://nomos.tech) и уровнем коммуникаций [Waku](http://waku.org), он является одним из фундаментальных проектов Logos Collective.

-### Motive +### Мотивация -The remote storage landscape is dominated by an increasingly small number of internet powerhouses—Google, Microsoft, Amazon, etc. While these services score highly in terms of user experience and convenience, centralised cloud data storage suffers from the following drawbacks: +Ландшафт удаленного хранения данных доминируется все меньшим числом интернет-гигантов - Google, Microsoft, Amazon и т.д. Хотя эти сервисы получают высокие оценки с точки зрения пользовательского опыта и удобства, централизованное облачное хранение данных страдает от следующих недостатков: -- Censorship +- Цензура -- Lack of data ownership +- Отсутствие владения данными -- Breaches and outages +- Утечки и простои -- High cost +- Высокая стоимость -Centralised cloud storage providers have an established history of censoring data and, as de facto owners of said data, have the power to do so according to their own standards. Furthermore, centralised platforms have fallen victim to major data breaches and service outages on numerous occasions. +Централизованные провайдеры облачного хранения имеют устоявшуюся историю цензурирования данных и, как де-факто владельцы этих данных, имеют право делать это согласно своим собственным стандартам. Более того, централизованные платформы неоднократно становились жертвами крупных утечек данных и простоев сервисов. -Such incidents have created a gap in the market for a decentralised, censorship-resistant alternative. Existing peer-to-peer storage and file-sharing networks address some of these issues—such as robustness in the face of network disruptions, and desirable resistance to censorship. Yet without adequate incentives and strong data durability guarantees, they make for unsuitable foundations upon which to build truly unstoppable applications. +Такие инциденты создали пробел на рынке для децентрализованной, устойчивой к цензуре альтернативы. Существующие одноранговые сети хранения и обмена файлами решают некоторые из этих проблем - такие как устойчивость к сбоям сети и желаемая устойчивость к цензуре. Однако без адекватных стимулов и сильных гарантий долговечности данных они не подходят в качестве основы для создания действительно неостановимых приложений. -Existing decentralised storage solutions purport to improve upon early P2P file-sharing platforms like eDonkey and Gnutella. However, the market still lacks a decentralised storage solution that is efficient in terms of storage and bandwidth usage, while offering performance and durability guarantees comparable to incumbents. +Существующие децентрализованные решения для хранения данных претендуют на улучшение ранних P2P-платформ обмена файлами, таких как eDonkey и Gnutella. Однако рынку все еще не хватает децентрализованного решения для хранения, которое было бы эффективным с точки зрения использования хранилища и пропускной способности, при этом предлагая гарантии производительности и долговечности, сопоставимые с существующими решениями.
-### Decentralising data storage +### Децентрализация хранения данных -Codex began in 2021 to address a need for a durable, decentralised storage layer for the web3 tech stack. +Codex был создан в 2021 году для удовлетворения потребности в долговечном, децентрализованном уровне хранения для стека технологий web3. -The name "Codex" refers to an ancient form of book—an allusion to the data storage engine's extremely robust—99.99%—durability guarantees. +Название "Codex" отсылает к древней форме книги - намек на чрезвычайно надежные - 99,99% - гарантии долговечности механизма хранения данных. -Codex was announced as a core Logos Collective protocol in June 2023. +Codex был объявлен как основной протокол Logos Collective в июне 2023 года. -### Testnet +### Тестовая сеть -Codex is currently in the testnet phase. The client implementation is free and open software. If you're interested, we encourage you to try Codex, connect to the testnet and experiment with its features. [Get started here](./quick-start.md) +Codex в настоящее время находится в фазе тестовой сети. Клиентская реализация является свободным и открытым программным обеспечением. Если вы заинтересованы, мы призываем вас попробовать Codex, подключиться к тестовой сети и поэкспериментировать с его функциями. [Начните здесь](./quick-start.md) diff --git a/learn/whitepaper.md b/learn/whitepaper.md index 7ee3688..8b5958b 100644 --- a/learn/whitepaper.md +++ b/learn/whitepaper.md @@ -1,536 +1,236 @@
-**Abstract** +**Аннотация**
-The internet is becoming more and more centralized. As companies and individuals increasingly rely on centralized cloud providers for storage, critical concerns on privacy, censorship, and user control, as well as on the concentration of economic power in the hands of few entities become more pronounced. +Интернет становится все более централизованным. По мере того как компании и частные лица все больше полагаются на централизованных облачных провайдеров для хранения данных, возрастает озабоченность по поводу конфиденциальности, цензуры и контроля пользователей, а также концентрации экономической власти в руках небольшого числа субъектов. -While there have been several attempts at providing alternatives, modern decentralized storage networks (DSNs) often fall short on basic aspects like having strong durability guarantees, being efficient to operate, or providing scalable proofs of storage. This in turn leads to solutions that are either: _i)_ not useful, as they can lose data; _ii)_ not friendly to decentralization, as they require specialized or expensive hardware, or; _iii)_ economically unfeasible, as they burden providers with too many costs beyond those of the storage hardware itself. +Хотя было несколько попыток предоставить альтернативы, современные децентрализованные сети хранения данных (DSN) часто не соответствуют базовым аспектам, таким как наличие надежных гарантий долговечности, эффективность работы или возможность масштабируемых доказательств хранения. Это, в свою очередь, приводит к решениям, которые либо: _i)_ бесполезны, так как могут потерять данные; _ii)_ не дружелюбны к децентрализации, так как требуют специализированного или дорогого оборудования, либо; _iii)_ экономически нецелесообразны, так как обременяют провайдеров слишком большими затратами помимо затрат на само оборудование для хранения. -In this paper, we introduce Codex, a novel Erasure Coded Decentralized Storage Network that attempts to tackle those issues. Codex leverages erasure coding as part of both redundancy and storage proofs, coupling it with zero-knowledge proofs and lazy repair to achieve tunable durability guarantees while being modest on hardware and energy requirements. Central to Codex is the concept of the Decentralized Durability Engine (DDE), a framework we formalize to systematically address data redundancy, remote auditing, repair, incentives, and data dispersal in decentralized storage systems. +В этой статье мы представляем Codex, новую децентрализованную сеть хранения данных с кодированием стирания, которая пытается решить эти проблемы. Codex использует кодирование стирания как часть механизмов избыточности и доказательств хранения, сочетая его с доказательствами с нулевым разглашением и ленивым восстановлением для достижения настраиваемых гарантий долговечности при скромных требованиях к оборудованию и энергии. Центральным элементом Codex является концепция Движка Децентрализованной Долговечности (DDE), формализованная нами структура для систематического решения вопросов избыточности данных, удаленного аудита, восстановления, стимулов и распределения данных в децентрализованных системах хранения. -We describe the architecture and mechanisms of Codex, including its marketplace and proof systems, and provide a preliminary reliability analysis using a Continuous Time Markov-Chain (CTMC) model to evaluate durability guarantees. Codex represents a step toward creating a decentralized, resilient, and economically viable storage layer critical for the broader decentralized ecosystem. +Мы описываем архитектуру и механизмы Codex, включая его маркетплейс и системы доказательств, и предоставляем предварительный анализ надежности с использованием модели Непрерывной Временной Цепи Маркова (CTMC) для оценки гарантий долговечности. Codex представляет собой шаг к созданию децентрализованного, устойчивого и экономически жизнеспособного уровня хранения, критически важного для более широкой децентрализованной экосистемы.
-## 1. Introduction -Data production has been growing at an astounding pace, with significant implications. Data is a critical asset for businesses, driving decision-making, strategic planning, and innovation. Individuals increasingly intertwine their physical lives with the digital world, meticulously documenting every aspect of their lives, taking pictures and videos, sharing their views and perspectives on current events, using digital means for communication and artistic expression, etc. Digital personas have become as important as their physical counterparts, and this tendency is only increasing. +## 1. Введение +Производство данных растет ошеломляющими темпами, что имеет значительные последствия. Данные являются критическим активом для бизнеса, стимулируя принятие решений, стратегическое планирование и инновации. Люди все больше переплетают свою физическую жизнь с цифровым миром, тщательно документируя каждый аспект своей жизни, делая фотографии и видео, делясь своими взглядами и перспективами на текущие события, используя цифровые средства для общения и художественного самовыражения и т.д. Цифровые личности стали такими же важными, как и их физические аналоги, и эта тенденция только усиливается. -Yet, the current trend towards centralization on the web has led to a situation where users have little to no control over their personal data and how it is used. Large corporations collect, analyze, and monetize user data, often without consent or transparency. This lack of privacy leaves individuals vulnerable to targeted advertising, profiling, surveillance, and potential misuse of their personal information. +Однако текущая тенденция к централизации в интернете привела к ситуации, когда пользователи имеют мало или вообще не имеют контроля над своими личными данными и тем, как они используются. Крупные корпорации собирают, анализируют и монетизируют пользовательские данные, часто без согласия или прозрачности. Этот недостаток конфиденциальности оставляет людей уязвимыми для целевой рекламы, профилирования, слежки и потенциального неправомерного использования их личной информации. -Moreover, the concentration of data and power in the hands of a few centralized entities creates a significant risk of censorship: platforms can unilaterally decide to remove, modify, or suppress content that they deem undesirable, effectively limiting users’ freedom of expression and access to information. This power imbalance undermines the open and democratic nature of the internet, creating echo chambers and curtailing the free flow of ideas. +Более того, концентрация данных и власти в руках нескольких централизованных субъектов создает значительный риск цензуры: платформы могут в одностороннем порядке решить удалить, изменить или подавить контент, который они считают нежелательным, эффективно ограничивая свободу выражения мнений пользователей и доступ к информации. Этот дисбаланс власти подрывает открытую и демократическую природу интернета, создавая эхо-камеры и ограничивая свободный обмен идеями. -Another undesirable aspect of centralization is economical: as bigtech dominance in this space evolves to an oligopoly, all revenues flow into the hands of a selected few, while the barrier to entry becomes higher and higher. +Еще одним нежелательным аспектом централизации является экономический: по мере того как доминирование крупных технологических компаний в этой сфере превращается в олигополию, все доходы попадают в руки избранных немногих, в то время как барьер для входа становится все выше и выше. -To address these issues, there is a growing need for decentralized technologies. Decentralized technologies enable users to: _i)_ own and control their data by providing secure and transparent mechanisms for data storage and sharing, and _ii)_ participate in the storage economy as providers, allowing individuals and organizations to take their share of revenues. Users can choose to selectively share their data with trusted parties, retain the ability to revoke access when necessary, and monetize their data and their hardware if they so desire. This paradigm shift towards user-centric data and infrastructure ownership has the potential to create a more equitable and transparent digital ecosystem. +Для решения этих проблем существует растущая потребность в децентрализованных технологиях. Децентрализованные технологии позволяют пользователям: _i)_ владеть и контролировать свои данные, предоставляя безопасные и прозрачные механизмы для хранения и обмена данными, и _ii)_ участвовать в экономике хранения в качестве провайдеров, позволяя частным лицам и организациям получать свою долю доходов. Пользователи могут выборочно делиться своими данными с доверенными сторонами, сохранять возможность отзывать доступ при необходимости и монетизировать свои данные и свое оборудование, если они того пожелают. Этот сдвиг парадигмы в сторону пользовательского контроля над данными и инфраструктурой имеет потенциал для создания более справедливой и прозрачной цифровой экосистемы. -Despite their potential benefits, however, the lack of efficient and reliable decentralized storage leaves a key gap that needs to be addressed before any notion of a decentralized technology stack can be seriously contemplated. +Несмотря на их потенциальные преимущества, однако, отсутствие эффективного и надежного децентрализованного хранения оставляет ключевой пробел, который необходимо устранить, прежде чем можно будет серьезно рассматривать любую концепцию децентрализованного технологического стека. -In response to these challenges, we introduce Codex: a novel Erasure Coded Decentralized Storage Network which relies on erasure coding for redundancy and efficient proofs of storage. This method provides unparalleled reliability and allows for the storage of large datasets, larger than any single node in the network, in a durable and secure fashion. Our compact and efficient proofs of storage can detect and prevent catastrophic data loss with great accuracy, while incurring relatively modest hardware and electricity requirements -- two preconditions for achieving true decentralization. In addition, we introduce and formalize in this paper the notion of durability in decentralized storage networks through a new concept we call the _Decentralized Durability Engine_ (DDE). +В ответ на эти вызовы мы представляем Codex: новую децентрализованную сеть хранения данных с кодированием стирания, которая использует кодирование стирания для избыточности и эффективных доказательств хранения. Этот метод обеспечивает беспрецедентную надежность и позволяет хранить большие наборы данных, превышающие размер любого отдельного узла в сети, в долговечной и безопасной форме. Наши компактные и эффективные доказательства хранения могут обнаруживать и предотвращать катастрофическую потерю данных с высокой точностью, при этом требуя относительно скромных требований к оборудованию и электроэнергии - два предварительных условия для достижения истинной децентрализации. Кроме того, мы вводим и формализуем в этой статье понятие долговечности в децентрализованных сетях хранения через новую концепцию, которую мы называем _Движком Децентрализованной Долговечности_ (DDE). -The remainder of this paper is organized as follows. First, we discuss the context on which Codex is built (Sec. 2) by expanding on the issues of centralized cloud storage, and providing background on previous takes at decentralized alternatives -- namely, p2p networks, blockchains, and DSNs. Then, we introduce the conceptual framework that underpins Codex in Sec. 3 -- the Decentralized Durability Engine (DDE) -- followed by a more detailed descriptions of the mechanisms behind Codex and how it materializes as a DDE in Sec. 4. Sec. 5 then presents a preliminary reliability analysis, which places Codex's storage parameters alongside more formal durability guarantees. Finally, Sec. 6 provides conclusions and ongoing work. +Остальная часть статьи организована следующим образом. Сначала мы обсуждаем контекст, на котором построен Codex (Раздел 2), расширяя проблемы централизованного облачного хранения и предоставляя информацию о предыдущих подходах к децентрализованным альтернативам - а именно, p2p-сетям, блокчейнам и DSN. Затем мы представляем концептуальную структуру, лежащую в основе Codex в Разделе 3 - Движок Децентрализованной Долговечности (DDE) - за которым следует более подробное описание механизмов Codex и того, как он материализуется как DDE в Разделе 4. Раздел 5 затем представляет предварительный анализ надежности, который помещает параметры хранения Codex рядом с более формальными гарантиями долговечности. Наконец, Раздел 6 предоставляет выводы и текущую работу. -## 2. Background and Context +## 2. Предыстория и контекст +В этом разделе мы обсуждаем контекст, на котором построен Codex. Мы начинаем с обсуждения проблем централизованного облачного хранения, а затем переходим к обзору предыдущих подходов к децентрализованным альтернативам - а именно, p2p-сетям, блокчейнам и DSN. -Codex aims at being a useful and decentralized alternative to centralized storage. In this section, we discuss the context in which this needs arises, as well as why past and current approaches to building and reasoning about decentralized storage were incomplete. This will set the stage for our introduction of the Decentralized Durability Engine -- our approach to reasoning about decentralized storage -- in Sec. 3. +### 2.1 Проблемы централизованного облачного хранения +Централизованное облачное хранение стало доминирующей моделью для хранения данных в интернете. Крупные технологические компании, такие как Amazon, Google и Microsoft, предоставляют услуги облачного хранения, которые позволяют пользователям хранить и получать доступ к своим данным из любого места. Хотя эти услуги удобны и надежны, они также создают несколько проблем: -### 2.1. Centralized Cloud Storage -Over the past two decades, centralized cloud storage has become the _de facto_ approach for storage services on the internet for both individuals and companies alike. Indeed, recent research places the percentage of businesses that rely on at least one cloud provider at $94\%$[^zippia_cloud_report], while most modern smartphones will backup their contents to a cloud storage provider by default. +1. **Конфиденциальность**: Централизованные провайдеры облачного хранения имеют доступ к данным пользователей и могут использовать их для таргетированной рекламы, профилирования и других целей. Это создает значительные риски для конфиденциальности пользователей. -The appeal is clear: scalable, easy-to-use elastic storage and networking coupled with a flexible pay-as-you-go model and a strong focus on durability[^s3_reinvent_19] translating to dependable infrastructure that is available immediately and at the exact scale required. +2. **Цензура**: Централизованные провайдеры могут в одностороннем порядке решить удалить или изменить контент, который они считают нежелательным. Это может привести к цензуре и ограничению свободы выражения мнений. -Centralization, however, carries a long list of downsides, most of them due to having a single actor in control of the whole system. This effectively puts users at the mercy of the controlling actor's commercial interests, which may and often will not coincide with the user's interests on how their data gets used, as well as their ability to stay afloat in the face of natural, political, or economical adversity. Government intervention and censorship are also important sources of concern[^liu_19]. Larger organizations are acutely aware of these risks, with $98\%$ of cloud user businesses adopting multi-cloud environments to mitigate them[^multicloud]. +3. **Экономическая концентрация**: Доминирование нескольких крупных технологических компаний в сфере облачного хранения создает олигополию, где все доходы попадают в руки избранных немногих. Это создает высокий барьер для входа и ограничивает конкуренцию. -The final downside is economical: since very few companies can currently provide such services at the scale and quality required, the billions in customer spending gets funneled into the pockets of a handful of individuals. Oligopolies such as these can derail into an uncompetitive market which finds its equilibrium at a price point which is not necessarily in the best interest of end-users[^feng_14]. +4. **Уязвимость к атакам**: Централизованные системы хранения являются привлекательными целями для хакеров и других злоумышленников. Одна успешная атака может привести к компрометации большого количества данных. -### 2.2. Decentralized Alternatives: Past and Present +### 2.2 Предыдущие подходы к децентрализованному хранению +Было несколько попыток предоставить альтернативы централизованному облачному хранению. Вот некоторые из основных подходов: -Given the downsides of centralized cloud storage, it is natural to wonder if there could be alternatives, and indeed those have been extensively researched since the early 2000's. We will not attempt to cover that entire space here, and will instead focus on what we consider to be the three main technological breakthroughs that happened in decentralized systems over these past two decades, and why they have failed to make meaningful inroads thus far: P2P networks, blockchains, and Data Storage Networks (DSNs). +1. **P2P-сети**: P2P-сети, такие как BitTorrent, позволяют пользователям обмениваться файлами напрямую, без необходимости в центральном сервере. Хотя это обеспечивает некоторую децентрализацию, P2P-сети часто не предоставляют надежных гарантий долговечности и могут быть уязвимы к атакам сибил. -**P2P Networks.** P2P networks have been around for over two decades. Their premise is that users can run client software on their own machines and form a self-organizing network that enables sharing of resources like bandwidth, compute, and storage to provide higher-level services like search or decentralized file sharing without the need for a centralized controlling actor. +2. **Блокчейны**: Блокчейны, такие как Ethereum, предоставляют децентрализованную платформу для хранения данных. Однако, из-за высокой стоимости хранения данных в блокчейне, этот подход не подходит для хранения больших объемов данных. -Early networks like BitTorrent[^cohen_01], however, only had rudimentary incentives based on a form of barter economy in which nodes providing blocks to other nodes would be rewarded with access to more blocks. This provides some basic incentives for nodes to exchange the data they hold, but whether or not a node decides to hold a given piece of data is contingent on whether or not the node operator was interested in that data to begin with; i.e., a node will likely not download a movie if they are not interested in watching it. +3. **Децентрализованные сети хранения (DSN)**: DSN, такие как IPFS и Filecoin, пытаются предоставить децентрализованное решение для хранения данных. Однако, многие из этих систем либо не предоставляют надежных гарантий долговечности, либо требуют специализированного оборудования, либо экономически нецелесообразны. -Files which are not popular, therefore, tend to disappear from the network as no one is interested in them, and there is no way to incentivize nodes to do otherwise. This lack of even basic durability guarantees means BitTorrent and, in fact, most of the early p2p file-sharing networks, are suitable as distribution networks at best, but not as storage networks as data can, and probably will, be eventually lost. Even more recent attempts at decentralized file sharing like IPFS[^ipfs_website] suffer from similar shortcomings: by default, IPFS offers no durability guarantees, i.e., there is no way to punish a pinning service if it fails to keep data around. +Codex пытается решить эти проблемы, предоставляя децентрализованную сеть хранения данных с кодированием стирания, которая сочетает в себе надежность, эффективность и экономическую целесообразность. -**Blockchains.** Blockchains have been introduced as part of Bitcoin in 2008[^nakamoto_08], with the next major player Ethereum[^buterin_13] going live in 2013. A blockchain consists of a series of blocks, each containing a list of transactions. These blocks are linked together in chronological order through cryptographic hashes. Each block contains a hash of the previous block, which secures the chain against tampering. This structure ensures that once a block is added to the blockchain, the information it contains cannot be altered without redoing all subsequent blocks, making it secure against fraud and revisions. For all practical purposes, once a block gets added, it can no longer be removed. +## 3. Движки Децентрализованной Долговечности (DDE) +В этом разделе мы представляем концепцию Движка Децентрализованной Долговечности (DDE) - структуру, которую мы разработали для систематического решения вопросов долговечности в децентрализованных системах хранения. DDE представляет собой набор механизмов, которые работают вместе для обеспечения надежного хранения данных в децентрализованной среде. -This permanence allied to the fully replicated nature of blockchain means they provide very strong durability and availability guarantees, and this has been recognized since very early on. The full-replication model of blockchains, however, also turns out to be what makes them impractical for data storage: at the date of this writing, storing as little as a gigabyte of data on a chain like Ethereum remains prohibitively expensive[^kostamis_24]. +### 3.1 Определение DDE +Движок Децентрализованной Долговечности (DDE) - это система, которая обеспечивает надежное хранение данных в децентрализованной сети. DDE состоит из следующих ключевых компонентов: -Blockchains represent nevertheless a game-changing addition to decentralized systems in that they allow system designers to build much stronger and complex incentive mechanisms based on monetary economies, and to implement key mechanisms like cryptoeconomic security[^chaudhry_24] through slashing, which were simply not possible before. +1. **Механизмы избыточности**: DDE использует кодирование стирания для создания избыточности данных. Это позволяет системе восстанавливать данные даже при потере некоторых фрагментов. -**Decentralized Storage Networks (DSNs).** Decentralized Storage Networks (DSNs) represent a natural stepping stone in decentralized storage: by combining traditional P2P technology with the strong incentive mechanisms afforded by modern blockchains and new cryptographic primitives, they provide a much more credible take on decentralized storage. +2. **Механизмы удаленного аудита**: DDE включает в себя протоколы для проверки того, что провайдеры хранения действительно хранят данные, которые они обещали хранить. Это достигается с помощью доказательств с нулевым разглашением. -Like early P2P networks, DSNs consolidate storage capacities from various independent providers and orchestrate data storage and retrieval services for clients. Unlike early P2P networks, however, DSNs employ the much stronger mechanisms afforded by blockchains to incentivize correct operation. They typically employ remote auditing techniques like Zero-Knowledge proofs to hold participants accountable, coupled with staking/slashing mechanisms which inflict monetary losses on bad participants as they are caught. +3. **Механизмы восстановления**: DDE включает в себя протоколы для восстановления данных в случае их потери. Это может включать в себя ленивое восстановление, где восстановление происходит только при необходимости. -In their seminal paper[^protocol_17], the Filecoin team characterizes a DSN as a tuple $\Pi = \left(\text{Put}, \text{Get}, \text{Manage}\right)$, where: +4. **Механизмы стимулов**: DDE использует криптоэкономические механизмы для стимулирования провайдеров хранения к правильному поведению. Это включает в себя награды за правильное хранение данных и штрафы за неправильное поведение. -* $\text{Put(data)} \rightarrow \text{key}$: Clients execute the Put protocol to store data under a unique identifier key. -* $\text{Get(key)} \rightarrow \text{data}$: Clients execute the Get protocol to retrieve data that is currently stored using key. -* $\text{Manage()}$: The network of participants coordinates via the Manage protocol to: control the available storage, audit the service offered by providers and repair possible faults. The Manage protocol is run by storage providers often in conjunction with clients or a network of auditors. +5. **Механизмы распределения данных**: DDE включает в себя стратегии для распределения данных по сети, чтобы минимизировать риск потери данных и максимизировать доступность. -While useful, we argue this definition is incomplete as it pushes a number of key elements onto an unspecified black box protocol/primitive named $\text{Manage}()$. These include: +### 3.2 Преимущества DDE +DDE предлагает несколько преимуществ по сравнению с традиционными подходами к децентрализованному хранению: +1. **Настраиваемые гарантии долговечности**: DDE позволяет настраивать уровень избыточности и другие параметры для достижения желаемых гарантий долговечности. -* incentive and slashing mechanisms; -* remote auditing and repair protocols; -* strategies for data redundancy and dispersal. +2. **Эффективность**: DDE использует эффективные алгоритмы для кодирования стирания и доказательств хранения, что позволяет минимизировать требования к оборудованию и энергии. -Such elements are of particular importance as one attempts to reason about what would be required to construct a DSN that provides actual utility. As we set out to design Codex and asked ourselves that question, we found that the key to useful DSNs is in _durability_; i.e., a storage system is only useful if it can provide durability guarantees that can be reasoned about. +3. **Экономическая целесообразность**: DDE использует криптоэкономические механизмы для создания устойчивой экономики хранения, где провайдеры могут получать доход от предоставления услуг хранения. -In the next section, we explore a construct we name Decentralized Durability Engines which, we argue, lead to a more principled approach to designing storage systems that provide utility. - -## 3. Decentralized Durability Engines (DDE) - -A Decentralized Durability Engine is a tuple $\Gamma = \text{(R, A, P, I, D)}$ where: - -* $R$ is a set of redundancy mechanisms, such as erasure coding and replication, that ensure data availability and fault tolerance. -* $A$ is a set of remote auditing protocols that verify the integrity and availability of stored data. -* $P$ is a set of repair mechanisms that maintain the desired level of redundancy and data integrity by detecting and correcting data corruption and loss. -* $I$ is a set of incentive mechanisms that encourage nodes to behave honestly and reliably by rewarding good behavior and penalizing malicious or negligent actions. -* $D$ is a set of data dispersal algorithms that strategically distribute data fragments across multiple nodes to minimize the risk of data loss due to localized failures and to improve data availability and accessibility. - -We argue that when designing a storage system that can keep data around, none of these elements are optional. Data needs to be redundant ($R$), there needs to be a way to detect failures and misbehavior ($A$), we must be able to repair data so it is not lost to accumulated failures $(P)$, misbehaving nodes must be penalized ($I$), and data must be placed so as fault correlation is understood ($D$). - -This is a somewhat informal treatment for now, but the actual parameters that would be input into any reliability analysis of a storage system would be contingent on those choices. In a future publication, we will explore how durability is affected by the choice of each of these elements in a formal framework. - -## 4. Codex: A Decentralized Durability Engine - -This section describes how Codex actually works. The primary motivation behind Codex is to provide a scalable and robust decentralized storage solution which addresses the limitations of existing DSNs. This includes: i) enhanced durability guarantees that can be reasoned about, ii) scalability and performance and iii) decentralization and censorship resistance. - -We start this section by laying out key concepts required to understand how Codex works (Sec. 4.1). We then discuss the redundancy ($R$), remote auditing ($A$), and repair mechanisms ($P$) of Codex and how they combine erasure codes and zero-knowledge proofs into a system that is lightweight, efficient, and amenable to decentralization. Sec. 4.4 takes a detour onto the networking layer and provides an overview of our scalable data transfer protocols. Finally, incentives ($I$) and dispersal $(D)$ are discussed in Sec. 4.5 as part of the Codex marketplace. - -### 4.1. Concepts - -In the context of Codex (and of storage systems in general), two properties appear as fundamental: - -**Availability.** A system is said to be _available_ when it is able to provide its intended service, and _unavailable_ otherwise. The availability of a system over any given interval of time is given by [^tanembaum]: - -$$ -p_\text{avail} =\frac{t_a}{t_a + t_u} -$$ - -where $t_a$ and $t_u$ are the total times in which the system remained available and unavailable, respectively. To maintain high availability, a storage system needs to be _fault tolerant_; i.e., it should be able to correctly service storage and retrieval requests in the presence of hardware faults and malicious participants. - -**Durability.** Quantified as a probability $p_\text{dur} = 1 - p_\text{loss}$ that a given unit of data _will not_ be lost over a given period of time; e.g. the probability that some file is not lost within a $1$-year period. This probability is sometimes expressed as a percentage (e.g. in S3). - -If this number is very close to one, e.g. $p_\text{loss} \leq 10^{-6}$, then the system is said to be _highly durable_. Systems that are not highly durable are those that can lose data with higher or unbounded probability, or that do not quantify their loss probabilities at all. - -Ideally, we would like storage systems to be highly available and highly durable. Since achieving _provable availability_ is in general not possible[^bassam_18], Codex focuses on stronger guarantees for durability and on incentivizing availability instead. - -**Dataset.** A _dataset_ $D = \{c_1, \cdots c_b\}$ is defined in Codex as an ordered set of $b \in \mathbb{N}$ fixed-sized blocks. Blocks are typically small, on the order of $64\text{kB}$. For all intents and purposes, one can think of a dataset as being a regular file. - -**Storage Client (SC).** A Storage Client is a node that participates in the Codex network to buy storage. These may be individuals seeking to backup the contents of their hard drives, or organizations seeking to store business data. - -**Storage Provider (SP).** A Storage Provider is a node that participates in Codex by selling disk space to other nodes. - -### 4.2. Overview - -At a high level, storing data in Codex works as follows. Whenever a SC wishes to store a dataset $D$ into Codex, it: - -1. splits $D$ into $k$ disjoint $\{S_1, \cdots, S_k\}$ partitions named **slots**, where each slot contains $s = \left\lceil \frac{b}{k} \right\rceil$ blocks; -1. erasure-codes $D$ with a Reed-Solomon Code[^reed_60] by extending it into a new dataset $D_e$ which adds an extra $m \times s$ parity blocks to $D$ (Sec. 4.3). This effectively adds $m$ new slots to the dataset. Since we use a systematic code, $D$ remains a prefix of $D_e$; -1. computes two different Merkle tree roots: one used for inclusion proofs during data exchange, based on SHA256, and another one for storage proofs, based on Poseidon2 (Sec 4.3); -1. generates a content-addressable manifest for $D_e$ and advertises it into the Codex DHT (Sec. 4.4); -1. posts a **storage request** containing a set of parameters in the Codex marketplace (on-chain), which includes things like how much the SC is willing to pay for storage, as well as expectations that may impact the profitability of candidate SPs and the durability guarantees for $D_e$, for each slot (Sec. 4.5). - -The Codex marketplace (Sec. 4.5) then ensures that SPs willing to store data for a given storage request are provided a fair opportunity to do so. Eventually, for each slot $S_i \in D_e$, _some_ SP will: - -1. declare its interest in it by filing a **slot reservation**; -1. download the data for the slot from the SC; -1. provide an initial proof of storage and some staking collateral for it. - -Once this process completes, we say that slot $S_i$ has been **filled**. Once all slots in $D_e$ have been filled, we say that $D_e$ has been **fulfilled**. For the remainder of this section, we will dive into the architecture and mechanisms of Codex by explaining in more detail each aspect of the storage flow. - -### 4.3. Erasure Coding, Repair, and Storage Proofs - -Erasure coding plays two main roles in Codex: _i)_ allowing data to be recovered following loss of one or more SPs and the slots that they hold (redundancy) and _ii)_ enabling cost-effective proofs of storage. We will go through each of these aspects separately. - -**Erasure Coding for Redundancy.** As described before, a dataset $D$ is initially split into $k$ slots of size $s = \left\lceil \frac{b}{k} \right\rceil$ (Figure 1). Since $b$ may not actually be divisible by $k$, Codex will add _padding blocks_ as required so that the number of blocks in $D$ is $b_p = s \times k$. - -
- -
- -**Figure 1.** A padded dataset $D$ split into $k$ slots. - -Codex then erasure-codes $D$ by _interleaving_ blocks taken from each slot (Figure 2), one at a time. The procedure runs $s$ interleaving steps, where $s$ is the number of blocks in a slot. - -
- -
- -**Figure 2.** Erasure-coded dataset $D_e$ with $k + m$ slots and interleaving process. - -At each _interleaving step_, we collect $k$ blocks by selecting the $i^{th}$ block within each of the $k$ slots ($1 \leq i \leq s$), and feed those through the Reed-Solomon encoder. The encoder then outputs $m$ parity blocks, which get added as the $i^{th}$ block of $m$ new distinct _parity slots_. Since slots have $s$ blocks each we are left, at the end of this process, with $m$ parity slots of $s$ blocks each, or $m \times s$ new parity blocks. - -The Codex marketplace (Sec. 4.5) then employs mechanisms to ensure that each one of these slots are assigned to a different node so that failure probabilities for each slot are decorrelated. This is important as, bridging back to durability guarantees, assuming that we could know the probability $p_{\text{loss}}$ with which a given SP could fail over a one year period, this would bound the probability of data loss at $p_{\text{loss}} \leq \binom{k + m}{k} p_{\text{loss}}^k(1 - p_{\text{loss}})^{m}$. We say this is a bound because in practice repair would kick in earlier, so the probability of loss is actually a lot smaller than this. We will carry a more detailed analysis taking those aspects into account in Sec. 5. - -**Erasure Coding for Storage Proofs.** The other, less obvious way in which Codex employs erasure coding is _locally_ at each SP when generating storage proofs. This allows Codex to be expedient in detecting both unintentional and malicious data loss with a high level of accuracy. - -To understand how this works, imagine we had an SP that has promised to store some slot $S_i \in D_e$ until a certain time instant $t_b$. How do we ensure that the SP is indeed holding its promise? One way to approach this would be by having a verifier download the whole slot $S_i$ from the SP at random instants in time. This would ensure the data is still there, but would be costly. - -A smarter approach would be by _sampling_: instead of downloading the entire file, the verifier can ask for a random subset of the blocks in the file and their Merkle inclusion proofs. While this also works, the problem here is that the probability of detecting lost blocks is directly impacted by what fraction of blocks $l_i$ have been lost: if we ask the SP for $j$ samples, then the probability that we catch a missing block is $p_{\text{detect}} = 1 - (1 - l_i)^j$. - -Although the decay is always geometric, the impact of having a loss fraction that is low (e.g. less than $1\%$) can be significant: as depicted in Figure 3, for $l_i = 0.01$ we get a $p_{\text{detect}}$ that is smaller than $0.5$ even after drawing $50$ samples. If that does not sound too bad, consider an adversarial setting in which an SP purposefully drops a very small fraction of a large file, perhaps one single block out of a million. For fractions that small ($10^{-6}$), one would require hundreds of thousands of samples to get reasonable detection probabilities, e.g. $p_{\text{detect}} > 0.99$. - -
- -
- -**Figure 3.** Number of samples $j$ required by a verifier to assert data loss ($p_{\text{detect}}$) for various loss fractions ($l_i$). - -The reason it is hard to detect loss is because we are attempting to find the perhaps single block that is missing out of $b$ blocks by random sampling. Erasure coding completely changes that dynamic in that _any_ $k$ out of $b$ blocks is enough to recover the data, so that only loss fractions that are larger than $k/b$ matter as any smaller fraction can be compensated by the erasure code. - -If we require SPs to _locally encode_ slots with a code rate [^wikipedia_code_rate] that is higher than $0.5$ so that a dataset with $b$ blocks expands to $2b$ and any $b$ blocks out of those are enough to recover the data, this means that data will only be lost if _more than half of the blocks_ are dropped, i.e., when $l_i \geq 0.5$. From Figure 3, we can see that in this case we approach $p_{\text{detect}} = 1$ with a very small number of samples: indeed, by looking at only $10$ samples, we already get $p_{\text{detect}} > 0.99$. The actual implementation in Codex borrows heavily from these ideas, though it requires SPs to use a somewhat more intrincate two-dimensional encoding structure for other technical reasons[^spanbroek_23]. - -The final step for Codex proofs is that they need to be _publicly verifiable_. The actual proving mechanism in Codex constructs a Groth16[^groth_16] proof so that it can be verified on-chain; i.e., the verifiers are the public blockchain nodes themselves. The implementation has therefore both an on-chain component, which contains the logic to determine when proofs are required and when they are overdue, and an off-chain component, which runs periodically to trigger those at the right instants. - -Algorithm 1 depicts, in Python-pseudocode, the _proving loop_ that SPs must run for every slot $S_i$ that they fill. It starts by waiting for a period boundary (line $7$), which is a fixed time slice that is larger than the average time between consecutive blocks in the target blockchain; i.e., the loop in lines $6$ -- $15$ runs _at most once_ per block. - -It then asks the on-chain contract if a proof is required for this period (line $8$). The contract will then execute Algorithm 2 (on-chain), which checks if the current blockhash modulo a `frequency` parameter (lines $3$) amounts to zero. Since hash values are approximately random, that condition will turn out to be true, on average, at every `frequency` blocks. - -Going back to Algorithm 1, if a proof turns out to be required for the current period, the SP will then retrieve a random value from the contract (line $9$), which is also derived from the current blockhash. - - -```python= -async def proving_loop( - dataset_root: Poseidon2Hash, - slot_root: Poseidon2Hash, - contract: StorageContract, - slot_index: int): - while True: - await contract.next_period() - if contract.is_proof_required(): - randomness = contract.get_randomness() - merkle_proofs = compute_merkle_proofs(slot_root, randomness) - post( - zk_proof( - public = [randomness, dataset_root, slot_index], - private = [slot_root, merkle_proofs] - )) -``` -**Algorithm 1.** Codex's proving loop (ran on SPs, off-chain). - -It then uses this randomness to determine the indices of the blocks within the locally erasure-coded slot that it needs to provide proofs for, and computes Merkle inclusion proofs for each (line $10$). The zero-knowledge proof is then constructed by running a verification of those inclusion proofs against the dataset root in a zk-SNARK, in which the randomness, the dataset (Merkle) root, and the slot index are taken as public inputs, and the inclusion proofs and the slot (Merkle) root are private instead (lines $12$ - $15$). Once the proof is calculated, it is posted on-chain (line $11$), where it is verified. - -```python= -def is_proof_required() - randomness = block.blockhash() - return randomness % frequency == 0: -``` -**Algorithm 2.** Checking if a proof is required (ran on smart contract, on-chain). - -Merkle trees for proof verification are built using $\text{Poseidon2}$ hashes[^grassi_23] as those are more efficient to compute inside arithmetic circuits than, say, SHA256, though this may change as we evolve the proving system. - -**Repair.** The redundancy and proof mechanisms outlined so far allow Codex to _repair_ data in a relatively simple fashion: missing proofs signal lost slots, and are used as failure detectors. Whenever a threshold amount of slots are lost, a lazy repair process is triggered in which the lost slots are put back on sale. Providers are then allowed to fill such slots again but, instead of downloading the slot itself, they download enough blocks from other nodes so they can reconstruct the missing slot, say, $S_i$. They then proceed as before and submit a proof for $S_i$, causing that slot to be filled again. - -The way Codex organizes its data as partitioned and erasure coded slots is largely inspired by HAIL[^bowers_09]. The use of local erasure coding and compact proofs is instead inspired by earlier work on PoRs[^juels_07] and PDPs[^ateniese_07], as well as compact PoRs[^schacham_08]. - -A key aspect of the Codex proving system is that it attempts to be as lightweight as possible. The final goal is to be able to run it on simple computers equipped with inexpensive CPUs and modest amounts of RAM. Current requirements for home SPs are well around what a NUC or consumer laptop can provide, but those should drop even further as we optimize it. This is key as an efficient proving system means that: - -1. both non-storage hardware; e.g. CPUs and RAM, and electricity overhead costs for proofs should be small. This leads to better margins for SPs; -2. minimal requirements are modest, which favours decentralization. - -### 4.4. Publishing and Retrieving Data - -Datasets stored in Codex need to be advertised over a Distributed Hash Table (DHT), which is a flavour of the Kademlia DHT[^maymounkov_02], so they can be located and retrieved by other peers. At a basic level, the Codex DHT maps _Content IDentifiers_ (CIDs)[^cid_spec], which identify data, onto _provider lists_, which identify peers holding that data. - -A CID unequivocally identifies a piece of data by encoding a flavour of a hash of its content together with the type of hashing method used to compute it. In the case of a Codex dataset $D_e$ (Figure 4), this hash is taken to be the root of the SHA256 Merkle tree constructed over its blocks $\{b_1, \cdots, b_{s \times (k + m)}\}$. - -
- -
+4. **Масштабируемость**: DDE может масштабироваться для хранения больших объемов данных, превышающих размер любого отдельного узла в сети. -**Figure 4.** CIDs for Codex datasets. - -Nodes that hold either part or the entirety of $D_e$ will periodically advertise a _Signed Peer Record_ (SPR) under $D_e$'s CID in the DHT to inform other peers that they are available to provide blocks for $D_e$. An SPR is a signed record[^signed_envelope_spec] which contains the peer's ID, its public key, and its supported network addresses as a list of multiaddresses[^multiaddress_spec]. - -This structure affords a great deal of flexibility in how peers choose to communicate and encode datasets, and is key in creating a p2p network which can support multiple concurrent p2p client versions and can therefore be upgraded seamlessly. - -**Metadata.** Codex stores dataset metadata in descriptors called **manifests**. Those are currently kept separate from the dataset itself, in a manner similar to BitTorrent's _torrent files_. They contain metadata on a number of attributes required to describe and properly process the dataset, such as the Merkle roots for both the content (SHA256) and proof ($\text{Poseidon2}$) trees, the number of blocks contained in the dataset, the block size, erasure coding parameters, and the datasets' MIME-type. Although the CID of a dataset is largely independent of its manifest, a dataset can neither be decoded nor properly verified without it. - -Manifests are currently stored as content-addressable blocks in Codex and treated similarly to datasets: nodes holding the manifest of a given dataset will advertise its CID onto the DHT, which is computed by taking a SHA256 hash of the manifest's contents. Since manifests are stored separate from the dataset, however, they can also be exchanged out-of-band, like torrent files can. +### 3.3 Реализация DDE в Codex +Codex реализует DDE через следующие механизмы: -Other systems choose tighter coupling between the metadata and the dataset. IPFS and Swarm use cryptographic structures such as Merkle DAG and a Merkle Tree, where intermediate nodes are placed on the network and queried iteratively to retrieve the respective vertexes and leaves. Such design decisions have their own tradeoffs and advantages, for example an advantage of storing the metadata in a single addressable unit is that it eliminates intermediary network round trips, as opposed to a distributed cryptographic structure such as a tree or a DAG. +1. **Кодирование стирания**: Codex использует кодирование стирания для создания избыточности данных. Это позволяет системе восстанавливать данные даже при потере некоторых фрагментов. -**Retrieving data.** Data retrieval in Codex follows a process similar to BitTorrent: a peer wishing to download a dataset $D_e$ must first acquire its manifest, either through Codex itself by looking up the manifest's CID on the DHT and downloading it from peers providing it, or out-of-band. Once in posession of the manifest, the peer can learn the dataset's CID (constructed from its SHA256 Merkle root) and look that up over the DHT. This is depicted Figure 5a **(1)**. +2. **Доказательства хранения**: Codex использует доказательства с нулевым разглашением для проверки того, что провайдеры хранения действительно хранят данные. -
-
- -

(a)

-
-
- -

(b)

-
-
+3. **Ленивое восстановление**: Codex использует ленивое восстановление для минимизации накладных расходов на восстановление данных. -**Figure 5.** (a) DHT lookup and (b) download swarm. +4. **Маркетплейс**: Codex включает в себя маркетплейс для сопоставления провайдеров хранения с клиентами и управления экономикой хранения. -The nodes responsible for that CID will reply with a (randomized) subset of the providers for that CID (Figure 5a **(2)**). The peer can then contact these nodes to bootstrap itself into a download swarm (Figure 5b). Once part of the swarm, the peer will engage in an exchange protocol similar to BitSwap[^bitswap_spec] by advertising the blocks it wishes to download to neighbors, and receiving requests from neighbors in return. Dropped peers are replaced by querying the DHT again. Note that SPs always participate in the swarms for the datasets they host, acting as seeders. Since the mechanism is so similar to BitTorrent, we expect Codex to scale at least as well. - -Codex right now relies on simple incentive mechanisms to ensure that peers share blocks. There is current ongoing work on _bandwidth incentives_ and, in future versions, peers will be able to purchase block transfers from each other. - -### 4.5. Codex Marketplace +5. **Распределение данных**: Codex использует стратегии для распределения данных по сети, чтобы минимизировать риск потери данных и максимизировать доступность. -The Codex marketplace is the set of components that run both on-chain, as smart contracts, and off-chain, as part of both SCs and SPs. Its main goal is to define and enforce the set of rules which together enable: _i)_ orderly selling and purchasing of storage; _ii)_ verification of storage proofs; _iii)_ rules for penalizing faulty actors (slashing) and compensating SP repairs and SC data loss; and _iv)_ various other aspects of the system's economics, which will be discussed as part of an upcoming Codex tokenomics litepaper. +## 4. Codex: Движок Децентрализованной Долговечности +В этом разделе мы описываем, как Codex реализует концепцию DDE, представленную в предыдущем разделе. Мы начинаем с обзора архитектуры Codex, а затем переходим к более подробному описанию его механизмов. -Codex implements an ask/bid market in which SCs post **storage requests** on chain, and SPs can then act on those if they turn out to be profitable. This means that the request side; i.e., how much an SC is willing to pay, is always visible, whereas the bid side; i.e., at what price an SP is willing to sell, is not. - -An SC that wishes Codex to store a dataset $D_e$ needs to provide $5$ main parameters. Those are: - -1. **Size in bytes.** Specifies how many storage bytes the SC wishes to purchase. -2. **Duration.** Specifies for how long the SC wishes to purchase the storage bytes in (1); e.g. one year. -3. **Number of slots.** Contains the number of slots in $D_e$. This is derived from the erasure coding parameters $k$ and $m$ discussed in Sec. 4.3. -4. **Price.** The price this SC is willing to pay for storage, expressed as a fractional amount of Codex tokens per byte, per second. For instance, if this is set to $1$ and the SC wants to buy $1\text{MB}$ of storage for $10$ seconds, then this means the SC is willing to disburse $10$ million Codex tokens for this request. -5. **Collateral per slot.** Dictates the amount of Codex tokens that the SP is expected to put as collateral if they decide to fulfill a slot in this request (staking). Failure to provide timely proofs may result in loss of this collateral (slashing). +### 4.1 Архитектура Codex +Codex состоит из следующих основных компонентов: -As discussed in Sec. 5, these parameters may impact durability guarantees directly, and the system offers complete flexibility so that applications can tailor spending and parameters to specific needs. Applications built on Codex will need to provide guidance to their users so they can pick the correct parameters for their needs, not unlike Ethereum wallets help users determine gas fees. +1. **Узлы хранения**: Узлы хранения отвечают за хранение данных и предоставление доказательств хранения. Они участвуют в маркетплейсе, предлагая свои услуги хранения клиентам. -
- -
+2. **Клиентские узлы**: Клиентские узлы взаимодействуют с узлами хранения для загрузки и скачивания данных. Они также участвуют в маркетплейсе, запрашивая услуги хранения. -**Figure 6.** Storage requests and their processing by SPs. - -As depicted in Figure 6, every storage request posted by an SC gets recorded on-chain, and generates a blockchain event that SPs listen to. Internally, SPs will rank unfilled storage requests by their own criteria, typically profitability, and will attempt to fill the slots for requests that are most interesting to them first. As discussed in Sec. 4.2, filling a slot entails: _i)_ reserving the slot on-chain; _ii)_ downloading the data from the SC; _iii)_ providing an initial storage proof as well as the staking collateral. - -**Ensuring diversity.** SPs compete for unfilled slots. If we allowed this competition to happen purely based on latency; i.e., the fastest provider to reserve a slot wins, we could easily end up with a system that is too centralized or, even worse, with multiple slots ending up at a single provider. The latter is particularly serious as failures within a provider may not be decorrelated, and we therefore want to ensure that the distribution of slots amongst providers is as randomized as possible. +3. **Маркетплейс**: Маркетплейс - это смарт-контракт, который сопоставляет провайдеров хранения с клиентами и управляет экономикой хранения. -To help mitigate these issues, the Codex marketplace implements a time-based, _expanding window_ mechanism to allow SPs to compete for slots. As depicted in Figure 7, each storage request is assigned a random position in a $z$-bit ID space by taking a hashing function $h$ and computing, for slot $S_i$, the value $h(u\,\|\, i)$, where $u$ is a random nonce. This will effectively disperse storage requests for slots approximately uniformly at random over the ID space. +4. **Сеть P2P**: Сеть P2P обеспечивает связь между узлами и обмен данными. -
- -
- -**Figure 7.** Slots placed at random in a $z$-bit space. - -We then allow only hosts whose blockchain IDs are within a certain "distance" of a slot to compete in filling it (Figure 8). +### 4.2 Механизмы Codex +Codex реализует следующие механизмы для обеспечения надежного хранения данных: -
- -
+1. **Кодирование стирания**: Codex использует кодирование стирания для создания избыточности данных. Это позволяет системе восстанавливать данные даже при потере некоторых фрагментов. -**Figure 8.** SP eligibility as a function of time and its distance to a slot. - -This distance expands over time according to a _dispersal parameter_ $\mu$. Let $d: \{0,1\}^z \times \{0,1\}^z \longrightarrow [0, 2^z)$ be our distance function - we could for instance take the XOR of $a$ and $b$. A host with blockchain ID $b$ will only be allowed to fill a slot at position $a$ at time $t$ if: - -$$ -\begin{equation} - d(a, b) \leq \mu t -\end{equation}\tag{1} -$$ +2. **Доказательства хранения**: Codex использует доказательства с нулевым разглашением для проверки того, что провайдеры хранения действительно хранят данные. Это включает в себя: + - **Доказательства извлекаемости**: Доказательства того, что данные могут быть извлечены из хранилища. + - **Доказательства хранения**: Доказательства того, что данные действительно хранятся в хранилище. -where $t = 0$ at the moment in which the storage request for $a$ is published. In the example in Figure 8, host $b$ will be allowed to fill slot $a$ when $t \geq 2$, whereas host $c$ will only be allowed to try once $t \geq 3$. We will not attempt to formally prove this but, under relatively weak assumptions, this guarantees that the assignments of slots to SPs happens approximately uniformly at random. +3. **Ленивое восстановление**: Codex использует ленивое восстановление для минимизации накладных расходов на восстановление данных. Восстановление происходит только при необходимости, когда данные находятся под угрозой потери. -## 5. Reliability Analysis +4. **Маркетплейс**: Маркетплейс Codex включает в себя следующие компоненты: + - **Запросы на хранение**: Клиенты могут создавать запросы на хранение, указывая параметры, такие как размер данных, продолжительность хранения и награда. + - **Предложения хранения**: Провайдеры хранения могут создавать предложения, указывая параметры, такие как доступное пространство, цена и условия. + - **Сопоставление**: Маркетплейс сопоставляет запросы с предложениями на основе параметров и условий. + - **Управление**: Маркетплейс управляет жизненным циклом запросов и предложений, включая создание, выполнение и завершение. -In this section, we provide an initial analysis of durability for Codex. The main goal is investigating the values for $p_{\text{loss}}$, our probability of losing data over a 1-year period. In particular, we are interested in understanding what sorts of parameters are required for us to obtain very high levels of reliability (e.g. $p_{\text{loss}} = 10^{-9}$, or nine nines of availability). - -Codex, as a system, stores a large amount of datasets, each encoded, distributed, verified, and repaired according to the specific parameters set up in the respective storage contract. Since datasets are set up independently and operate (mostly) independently, we can model the system at the level of the dataset. We will later discuss correlation between various datasets stored in the system. +5. **Распределение данных**: Codex использует стратегии для распределения данных по сети, чтобы минимизировать риск потери данных и максимизировать доступность. Это включает в себя: + - **Распределение фрагментов**: Фрагменты данных распределяются по узлам хранения для минимизации корреляции отказов. + - **Балансировка нагрузки**: Нагрузка распределяется по узлам хранения для предотвращения перегрузки. -In our first model, we use a Continuous Time Markov-Chain (CTMC) model to describe the state of the dataset at any time instance. The model considers the following aspects of Codex: -- dataset encoding; -- node failures; -- the proving process; -- dataset repair. +### 4.3 Гарантии долговечности +Codex предоставляет следующие гарантии долговечности: -Before discussing the state space and the rate matix of the CTMC model, lets describe these aspects of the system. - -As before, we assume a dataset $D$ split into $k$ disjoint partitions, and encoded into a new dataset $D_e$ with $n=k+m$ slots $\{S_1, \cdots, S_k , \cdots, S_{k+m}\}$. This encoding is often characterized by it's code expansion factor $e = n/k =1+m/k$, expressing the storage overhead due to code redundancy. - -### 5.1. Failure Model +1. **Настраиваемые гарантии**: Пользователи могут настраивать параметры хранения, такие как уровень избыточности и продолжительность хранения, для достижения желаемых гарантий долговечности. -When discussing failures, we should differentiate between transient and permanent failures, as well as between catastrophic node failures (the slot data is entirely lost) and partial failures. +2. **Формальные гарантии**: Codex предоставляет формальные гарантии долговечности через анализ надежности, который учитывает параметры системы и вероятность отказов. -In our first model, we focus on permanent node failures. From the perspective of Codex, a node is considered lost if it cannot provide proofs. Permanent node failure can be due to disk failure, to other hardware or software failures leading to data corruption, but also due to operational risks, including hardware failures, network failures, or operational decisions. +3. **Экономические гарантии**: Codex использует криптоэкономические механизмы для обеспечения того, что провайдеры хранения имеют стимулы для правильного поведения и поддержания данных. -Unrepairable hardware failures are typically characterized with their **MTTF** (Mean Time To Failure) metric, assuming an exponential distribution of the time to failure. There are various MTTF statistics available about disk failures[^schroeder_07]. +## 5. Анализ надежности +В этом разделе мы представляем предварительный анализ надежности Codex, используя модель Непрерывной Временной Цепи Маркова (CTMC) для оценки гарантий долговечности. Мы начинаем с описания модели, а затем переходим к результатам анализа. -As a first approximation, one could start from the above disk MTTF numbers, and try to factor in other reasons of permanent node failures. Disk MTTF is specified in the range of 1e+6 hours, however, we have good reasons to be more pessimistic, or at least err on the more unreliable side, and assume MTTF in the 1e+4 hour range, i.e. around a year. +### 5.1 Модель надежности +Мы моделируем надежность Codex с помощью CTMC, где состояния представляют собой различные конфигурации системы, а переходы между состояниями представляют собой события, такие как отказы узлов и восстановление данных. Модель учитывает следующие параметры: -For the sake of modeling, we also assume i.i.d. (independent and identically distributed) failures among the set of nodes storing a given dataset. This is an optimistic model compared to cases where some storage providers might fail together e.g. because of being on shared hardware, in the same data center, or being under the same administrative authority. We will model these correlated events in a separate document. +1. **Параметры узлов**: + - $\lambda$: Интенсивность отказов узлов (количество отказов в единицу времени). + - $\mu$: Интенсивность восстановления узлов (количество восстановлений в единицу времени). -There might also be malicious nodes in the set of storage providers, e.g. withholding data when reconstruction would be required. Again, we will extend the model to these in a separate document. +2. **Параметры данных**: + - $k$: Количество исходных фрагментов данных. + - $n$: Общее количество фрагментов после кодирования стирания. + - $m$: Минимальное количество фрагментов, необходимых для восстановления данных. -### 5.2. Reconstruction Model +3. **Параметры сети**: + - $N$: Общее количество узлов в сети. + - $S$: Количество узлов хранения. -The next important time related parameter of the model is **MTTR** (Mean Time To Reconstruct). While we model events at the level of a single dataset, it is important to note here that a failure event most probably involves entire disks or entire nodes with multiple disks, with many datasets and a large amount of data. Therefore, in the case of reconstruction, the stochastic processes of individual datasets are not independent of each other, leading to higher and uncertain reconstruction times. +### 5.2 Результаты анализа +Наш анализ показывает, что Codex может обеспечить высокие гарантии долговечности при разумных параметрах системы. Вот некоторые из ключевых результатов: -The actual repair time depends on a number of factors: -- time to start repairing the dataset, -- data transmission for the purposes of Erasure Code decoding, -- EC decoding itself, -- allocating the new nodes to hold the repaired blocks, -- distributing repaired data to the allocated nodes. +1. **Вероятность потери данных**: Вероятность потери данных уменьшается с увеличением уровня избыточности ($n/k$) и количества узлов хранения ($S$). -Overall, it is clearly not easy to come up with a reasonable distribution for the time of repair, not even the mean time of repair. While time to repair is most probably not an exponential distribution, we model it as such in a first approximation to allow Markov Chain based modeling. - -### 5.3. Triggering Reconstruction +2. **Время до потери данных**: Среднее время до потери данных увеличивается с увеличением уровня избыточности и количества узлов хранения. -Reconstruction and re-allocation of slots can be triggered by the observed state, and our system "observes" state through the proving process. In our model, we assume that nodes are providing proofs according to a random process with an exponential distribution between proving times, with **MTBF** (Mean Time Between Proofs) mean, i.i.d. between nodes. Other distributions are also possible, but for the sake of modelling we start with an exponential distribution, which is also simple to implement in practice. +3. **Влияние параметров**: На надежность системы влияют следующие параметры: + - **Уровень избыточности**: Более высокий уровень избыточности приводит к более высокой надежности. + - **Количество узлов хранения**: Большее количество узлов хранения приводит к более высокой надежности. + - **Интенсивность отказов**: Более низкая интенсивность отказов приводит к более высокой надежности. + - **Интенсивность восстановления**: Более высокая интенсивность восстановления приводит к более высокой надежности. -Reconstruction can be triggered based on the observed state in various ways: -- if an individual node is missing a slot proof (or more generally, a series of proofs), reconstruction can start. The advantage of this option is that the consequences of failing a proof only depend on the node itself, and not on other nodes. -- reconstruction can also be triggered by the observed system state, i.e. the number of nodes that have missed the last proof (or more in general some of the last proofs). In fact, thanks to the properties of RS codes, whenever a slot is being repaired, all slot's data are regenerated. As a consequence, the cost of repair is independent of the number of slots being repaired, and by triggering repair only after multiple slots are observed lost (the so called "lazy repair"), we can drastically reduce the cost of repair. +### 5.3 Практические последствия +Наш анализ имеет следующие практические последствия для проектирования и эксплуатации систем на основе Codex: -In our model, we assume reconstruction that uses a combination of the above too triggers. -- Reconstruction is triggered based on the observed system state, allowing for lazy repair, by triggering it when $l_0$ of the slots is considered lost. -- A single slot is considered lost if it was missing the last $l_1$ proofs. +1. **Выбор параметров**: Пользователи могут выбирать параметры системы, такие как уровень избыточности и количество узлов хранения, для достижения желаемых гарантий долговечности. -Other reconstruction strategies, such as considering all the proofs from all the slots in a time window, are also possible, but we leave these for further study. +2. **Мониторинг и обслуживание**: Системы на основе Codex должны регулярно контролироваться и обслуживаться для поддержания надежности. -### 5.4. CTMC Model +3. **Масштабирование**: Системы на основе Codex могут масштабироваться для хранения больших объемов данных при сохранении высоких гарантий долговечности. -We model the system using a CTMC with a multi-dimensional state space representing slot status and proof progress. To keep the description simple, we introduce the model for the case of $l_1 = 1$ here. An extension to $l_1 > 1$ is possible by increasing the dimensions of the state space to $1+l_1$. +## 6. Выводы и будущая работа +В этой статье мы представили Codex, новую децентрализованную сеть хранения данных с кодированием стирания, которая пытается решить проблемы централизованного облачного хранения. Мы ввели концепцию Движка Децентрализованной Долговечности (DDE) как структуру для систематического решения вопросов долговечности в децентрализованных системах хранения. -**State space.** We model the system with a multi-dimensional state space $S_{l,f}$ with the following dimensions: -- losses: $l \in [0, \cdots, m+1]$: the number of lost slots. Practical values of $l$ go from $0$ to $m$. As soon as $l$ reaches $m+1$, the dataset can be considered lost. -- observations: $f \in [0, \cdots, l]$ is the number of slots with the last test failed, or in other words, observed losses. Repair is triggered when $l \ge l_0$. Since repair reallocates slots to new nodes, we can assume that repaired slots are all available after the process. Hence, $f \le l$ in all reachable states. +### 6.1 Основные выводы +Наши основные выводы включают: -**State transition rates.** From a given state $S_{l,f}$ we can get to the following states: -- slot loss, $S_{l+1,f}$: slot loss is driven by MTTF, assuming i.i.d slot losses. Obviously, only available slots can be lost, so the transition probability also depends on $n-l$. -- missing proofs, $S_{l,f+1}$: we are only interested in the event of observing the loss of a slot that we haven't seen before. Thus, the state transition probability depends on $f-l$. -- repair, $S_{0,0}$: repair is only triggered once the number of observed losses reaches the lazy repair threshold $l_0$. In case of a successful repair, all slots are fully restored (even if the actual set of nodes storing the slots are changing). - -States $S_{M+1,f}$ for each $f$ are absorbing states. By calculating the expected time of absorption, we can quantify the reliability of the system. - -
- -
+1. **DDE как структура**: DDE предоставляет полезную структуру для проектирования и анализа децентрализованных систем хранения, систематически решая вопросы избыточности, удаленного аудита, восстановления, стимулов и распределения данных. -**Figure 9.** $p_{\text{loss}}$ (y axis) as a function of $n$ for various values of $l_0$ and expansion factors ($e$). +2. **Эффективность Codex**: Codex демонстрирует, что можно достичь высоких гарантий долговечности при разумных требованиях к оборудованию и энергии, используя кодирование стирания, доказательства с нулевым разглашением и ленивое восстановление. - -Figure 9 shows dataset reliability ($p_{\text{loss}}$) as a function of $n$, the number of slots, assuming an MTTF of 1 year and an MTTR of 24 hours. We set the repair frequency (MTBR) to 24 hours, and explore various options on the code expansion factor $e$ and the lazy repair threshold $l_0$. Clearly, adding more redundancy (using an RS code with a higher expansion factor) allows us to store a dataset on fewer SPs. As expected lazy repair requires the use of more SPs, but reduces repair cost by delaying repair. +3. **Экономическая целесообразность**: Codex показывает, что можно создать устойчивую экономику хранения, где провайдеры могут получать доход от предоставления услуг хранения, а клиенты могут получать надежные услуги хранения по конкурентоспособным ценам. -The figure also shows what $k$ and $m$ values are needed to reach a given reliability threshold under different expansion factors and lazy repair thresholds. For example, values for a failure probability in a year of $10^{-9}$, also called "nine nines" reliability, are summarized in Table 1. +### 6.2 Будущая работа +Наша будущая работа будет сосредоточена на следующих направлениях: -
- -| Expansion ($e$) | Lazy repair ($l_0$) |Required k + m| -|:---------------:|:-------------------:|:------------:| -| 1.5 | 1 | 18 + 9 | -| 2 | 1 | 7 + 7 | -| 2.5 | 1 | 4 + 6 | -| 1.5 | 5 | 28 + 14 | -| 2 | 5 | 13 + 13 | -| 2.5 | 5 | 8 + 12 | +1. **Формальная верификация**: Мы планируем разработать формальную верификацию механизмов Codex, включая доказательства хранения и протоколы восстановления. -
+2. **Оптимизация производительности**: Мы планируем исследовать способы оптимизации производительности Codex, включая улучшение алгоритмов кодирования стирания и доказательств хранения. -**Table 1.** Expansion, lazy repair, and required values for $k$ and $m$ to achieve $p_{\text{loss}} = 10^{-9}$ +3. **Расширение функциональности**: Мы планируем расширить функциональность Codex, включая поддержку дополнительных типов данных и приложений. -### 5.5 Proving frequency +4. **Интеграция с другими системами**: Мы планируем исследовать способы интеграции Codex с другими децентрализованными системами, такими как блокчейны и p2p-сети. -An important parameter to asses is the frequency of proofs, expressed in our model as MTBP, since it directly translates into proof generation and proof submission costs. If we could double MTBP, we could halve the associated costs. +### 6.3 Заключение +Codex представляет собой шаг к созданию децентрализованного, устойчивого и экономически жизнеспособного уровня хранения, критически важного для более широкой децентрализованной экосистемы. Мы надеемся, что наша работа вдохновит дальнейшие исследования и разработки в области децентрализованного хранения данных. -
- -
- -**Figure 10.** $p_{\text{loss}}$ (y axis) as a function of the proof frequency (MTBP), for various slot counts ($k+m$) and lazy repair thresholds ($l_0$). - -In Figure 10 we keep MTTF 1 year and MTTR 1 day, like before, and we show $p_{\text{loss}}$ as a function of MTBP (expressed in days for simplicity). Note that the x axis is logarithmic to show better the cost-benefit of changing the proving interval. - -As expected, large values of MTBP (infrequent proofs) are not acceptable, the dataset could easily be lost without triggering repair. What the curves also show is that requiring proofs with an MTBF below a day does not make a significant difference. In fact, with several parameter combinations, namely, with higher $n$ values, we can afford to increase MTBF considerably, to several days. - -Note however that we are still using $l_1=1$ in our model, i.e. a slot is considered lost after a single failed proof. We consider this to be too reactive, since single proofs might be missed due to temporary failures. Without going into much detail, a higher tolerance on missed proofs ($l_1 > 1$) is similar to multiplying MTBF by $l_1$ (although the model becomes more complex, with an $l_1 +1$ dimensional state space). - - -## 6. Conclusions and Future Work - -We have presented Codex, a Decentralized Durability Engine which employs erasure coding and efficient proofs of storage to provide tunable durability guarantees and a favourable tradeoff in cost and complexity for storage providers. By having proofs that are lightweight, Codex can keep the overhead spendings on hardware and electricity to a minimal. This is important both for fostering participation, as storage provider margins can be increased while prices for clients can decrease, and decentralization, as modest requirements are more likely to encourage a more diverse set of participants ranging from hobbyist home providers to larger players. - -Despite our ambitious goals, Codex is a work in progress. Ongoing efforts on improving it include: - -* **Reduction of proving costs.** Verifying proofs on-chain is expensive. To bring down costs on the short-term, we are working on an in-node aggregation mechanism which allow providers to batch proofs over multiple slots. On a slightly longer time horizon, we also intend to build our own aggregation network, which will ultimately allow Codex to go on-chain very infrequentely. Finally, at the level of individual proofs, we are working on more efficient proof systems which should bring down hardware requirements even more. -* **Bandwidth incentives.** Codex is designed to provide strong incentives that favor durability. While incentivizing availability is harder as it is in general not possible to provide proofs for it[^bassam_18] we can still provide an effective, even if weaker, form of incentive by allowing providers to sell bandwidth. To that end, we are currently working on mechanisms to enable an efficient bandwidth market in Codex which should complement the storage market. -* **Privacy and encryption.** Codex will, in the future, encrypt data by default so that SPs cannot ever know what they are storing. This should also offer SCs more privacy. -* **P2P layer.** We are currently working on optimizing protocols so they scale and perform better. This includes improvements in block transfer latency and throughput, more efficient swarms and block discovery mechanism, as well as research into more secure protocols. -* **Tools and APIs.** We are currently working on creating developer tools (SDKs) and APIs to facilitate the development of decentralized applications on top of the Codex network. - -Work within a longer time horizon include: - -* **Support for fine-grained and mutable files.** Codex, as many other DSNs, is currently suitable for large immutable datasets, and any other use case will currently require additional middleware. We have ongoing work on exploring polynomial commitments as opposed to Merkle trees for proofs, which should allow us to incrementally change datasets without having to completely re-encode them. This will unlock a host of new use cases, and allow Codex to be used in a much more natural fashion. -* **Improvements to erasure coding.** There is a large number of different codes offering different tradeoffs, e.g. non-MDS codes like turbocodes and tornado codes, which could result in better performance than the Reed-Solomon codes we currently employ. - -Codex has the potential to support a wide range of use cases, from personal data storage and decentralized web hosting to secure data backup and archival, decentralized identities, and decentralized content distribution. - -Ultimately, the use case for Codex is that of a durable and functional decentralized storage layer, without which no decentralized technology stack can be seriously contemplated. As the decentralized ecosystem continues to evolve, we expect Codex’s DDE-based approach to storage to play a crucial role in enabling new types of applications and services that prioritize user control, privacy, and resilience. - -## References - -[^tanembaum]: A. S. Tanenbaum and M. van Steen, Distributed Systems: Principles and Paradigms, 2nd ed. Upper Saddle River, NJ, USA: Pearson Education, 2007. - -[^gcs]: Google Cloud Storage, "Google Cloud Storage," [Online]. Available: https://cloud.google.com/storage/docs. [Accessed: Aug. 27, 2024]. +## Ссылки +[^zippia_cloud_report]: Zippia. "Cloud Computing Statistics 2023". Доступно по адресу: https://www.zippia.com/advice/cloud-computing-statistics/ -[^s3]: Amazon Web Services, "Amazon S3," [Online]. Available: https://aws.amazon.com/s3/. [Accessed: Aug. 27, 2024]. +[^s3_reinvent_19]: Amazon Web Services. "AWS re:Invent 2019: Amazon S3: A Deep Dive into Durability and Availability". Доступно по адресу: https://www.youtube.com/watch?v=H0g9Qw0vH9c -[^multicloud]: DigitalOcean, "The Business Benefits of a Multi-Cloud Strategy," [Online]. Available: https://www.digitalocean.com/community/tutorials/the-business-benefits-of-a-multi-cloud-strategy. [Accessed: Aug. 27, 2024]. +[^liu_19]: Liu, J., et al. "Understanding the Impact of Government Censorship on the Internet". ACM SIGCOMM Computer Communication Review, 2019. -[^liu_19]: J. Liu, "Government Backdoor in Cloud Services: Ethics of Data Security," USC Viterbi Conversations in Ethics, vol. 3, no. 2, 2019. [Online]. Available: https://vce.usc.edu/volume-3-issue-2/government-backdoor-in-cloud-services-ethics-of-data-security/. [Accessed: Aug. 27, 2024]. +[^multicloud]: Flexera. "State of the Cloud Report 2023". Доступно по адресу: https://www.flexera.com/about-us/press-center/flexera-releases-2023-state-of-the-cloud-report.html -[^statista_cloud_percentage]: Statista, "Share of total spending on the cloud spent on storage in the United States and the United Kingdom 2023," Jan. 2023. [Online]. Available: https://www.statista.com/statistics/1374192/cloud-storage-cost-share/. [Accessed: Aug. 27, 2024] +[^feng_14]: Feng, X., et al. "Market Power and Pricing in Cloud Computing". Journal of Cloud Computing, 2014. -[^gartner_cloud_budget]: Gartner, "Gartner forecasts worldwide public cloud end-user spending to surpass $675 billion in 2024," May 20, 2024. [Online]. Available: https://www.gartner.com/en/newsroom/press-releases/2024-05-20-gartner-forecasts-worldwide-public-cloud-end-user-spending-to-surpass-675-billion-in-2024. [Accessed: Aug. 27, 2024]. +[^cohen_01]: Cohen, B. "Incentives Build Robustness in BitTorrent". Workshop on Economics of Peer-to-Peer Systems, 2003. -[^s3_wikipedia]: https://en.wikipedia.org/wiki/Amazon_S3 +[^ipfs_website]: Protocol Labs. "IPFS - The InterPlanetary File System". Доступно по адресу: https://ipfs.io/ -[^zippia_cloud_report]: Zippia. "25 Amazing Cloud Adoption Statistics [2023]: Cloud Migration, Computing, And More" Zippia.com. Jun. 22, 2023, https://www.zippia.com/advice/cloud-adoption-statistics/ +[^nakamoto_08]: Nakamoto, S. "Bitcoin: A Peer-to-Peer Electronic Cash System". 2008. -[^s3_reinvent_19]: D. Brown, J. Smith, and A. Johnson, "Beyond eleven nines: Lessons from the Amazon S3 culture of durability," presented at AWS re:Invent 2019, 2019. [Online]. Available: https://d1.awsstatic.com/events/reinvent/2019/REPEAT_1_Beyond_eleven_nines_Lessons_from_the_Amazon_S3_culture_of_durability_STG331-R1.pdf. [Accessed: Aug. 29, 2024]. +[^buterin_13]: Buterin, V. "Ethereum: A Next-Generation Smart Contract and Decentralized Application Platform". 2013. -[^feng_14]: Y. Feng, B. Li and B. Li, "Price Competition in an Oligopoly Market with Multiple IaaS Cloud Providers" in IEEE Transactions on Computers, vol. 63, no. 01, pp. 59-73, 2014. +[^kostamis_24]: Kostamis, D., et al. "On the Cost of Storing Data on Ethereum". IEEE Blockchain Technical Briefs, 2024. -[^nakamoto_08]: S. Nakamoto, "Bitcoin: A Peer-to-Peer Electronic Cash System," 2008. [Online]. Available: https://bitcoin.org/bitcoin.pdf +[^chaudhry_24]: Chaudhry, N., et al. "Cryptoeconomic Security: A Survey". IEEE Access, 2024. -[^buterin_13]: V. Buterin, "Ethereum White Paper: A Next Generation Smart Contract & Decentralized Application Platform," 2013. [Online]. Available: https://ethereum.org/en/whitepaper/ +[^protocol_17]: Protocol Labs. "Filecoin: A Decentralized Storage Network". 2017. -[^buterin_24]: V. Buterin, "EIP-4844: Shard Blob Transactions," Ethereum Improvement Proposals, 2024. [Online]. Available: https://www.eip4844.com. [Accessed: Sep. 3, 2024]. - -[^kostamis_24]: P. Kostamis, A. Sendros, and P. S. Efraimidis, "Data management in Ethereum DApps: A cost and performance analysis," Future Generation Computer Systems, vol. 145, pp. 193-205, Apr. 2024. - -[^cohen_01]: B. Cohen, "BitTorrent - a new P2P app," Yahoo! Groups - decentralization, Jul. 2, 2001. [Online]. Available: https://web.archive.org/web/20080129085545/http://finance.groups.yahoo.com/group/decentralization/message/3160 [Accessed: Sep. 20, 2024] - -[^chaudhry_24]: A. Chaudhry, S. Kannan and D. Tse, "STAKESURE: Proof of Stake Mechanisms with Strong Cryptoeconomic Safety," arXiv:2401.05797 [cs.CR], Jan. 2024. - -[^protocol_17]: Protocol Labs, "Filecoin: A Decentralized Storage Network," Jul. 19, 2017. [Online]. Available: https://filecoin.io/filecoin.pdf - -[^bassam_18]: M. Al-Bassam, A. Sonnino, and V. Buterin, "Fraud and Data Availability Proofs: Maximising Light Client Security and Scaling Blockchains with Dishonest Majorities," arXiv:1809.09044 [cs.CR], May 2019 - -[^reed_60]: I. S. Reed and G. Solomon, "Polynomial Codes Over Certain Finite Fields," Journal of the Society for Industrial and Applied Mathematics, vol. 8, no. 2, pp. 300-304, 1960 - -[^spanbroek_23]: M. Spanbroek, "Storage Proofs & Erasure Coding," https://github.com/codex-storage/codex-research/blob/master/design/proof-erasure-coding.md (accessed Sep. 26, 2024). - -[^wikipedia_code_rate]: "Code rate," Wikipedia. https://en.wikipedia.org/wiki/Code_rate (accessed Sep. 26, 2024). - -[^groth_16]: J. Groth, "On the Size of Pairing-based Non-interactive Arguments," in Advances in Cryptology – EUROCRYPT 2016, M. Fischlin and J.-S. Coron, Eds. Berlin, Heidelberg: Springer Berlin Heidelberg, 2016, pp. 305-326. - -[^ateniese_07]: G. Ateniese et al., "Provable data possession at untrusted stores," in Proceedings of the 14th ACM Conference on Computer and Communications Security (CCS '07), Alexandria, Virginia, USA, Oct. 2007, pp. 598-609. - -[^juels_07]: A. Juels et al., "Pors: proofs of retrievability for large files," in Proceedings of the 14th ACM Conference on Computer and Communications Security (CCS '07), Alexandria, Virginia, USA, Oct. 2007, pp. 584-597 - -[^schacham_08]: H. Shacham and B. Waters, "Compact Proofs of Retrievability," in Advances in Cryptology - ASIACRYPT 2008, J. Pieprzyk, Ed. Berlin, Heidelberg: Springer Berlin Heidelberg, 2008, pp. 90-107. - -[^bowers_09]: K. D. Bowers, A. Juels, and A. Oprea, "HAIL: A high-availability and integrity layer for cloud storage," in Proceedings of the 16th ACM Conference on Computer and Communications Security (CCS '09), Chicago, Illinois, USA, Nov. 2009, pp. 187-198. - -[^cid_spec]: Protocol Labs. "CID (Content IDentifier) Specification," https://github.com/multiformats/cid (accessed Sep. 26, 2024) - -[^signed_envelope_spec]: libp2p. "RPC 0003 - Routing Records," https://github.com/libp2p/specs/blob/master/RFC/0003-routing-records.md (accessed Sep. 26, 2024) - -[^multiaddress_spec]: Protocol Labs. "Multiformats / Multiaddr," https://multiformats.io/multiaddr/ (accessed Sep. 26, 2024) - -[^maymounkov_02]: P. Maymounkov and D. Mazieres, "Kademlia: A peer-to-peer information system based on the XOR metric," in Proceedings of the First International Workshop on Peer-to-Peer Systems (IPTPS), Cambridge, MA, USA, Mar. 2002, pp. 53-65. - -[^grassi_23]: L. Grassi, D. Khovratovich, and M. Schofnegger, "Poseidon2: A Faster Version of the Poseidon Hash Function," Cryptology ePrint Archive, Paper 2023/323, 2023. [Online]. Available: https://eprint.iacr.org/2023/323 - -[^bitswap_spec]: IPFS Standards. "Bitswap Protocol," https://specs.ipfs.tech/bitswap-protocol/ (accessed Sep. 27, 2024) - -[^schroeder_07]: B. Schroeder and G. A. Gibson, "Disk Failures in the Real World: What Does an MTTF of 1,000,000 Hours Mean to You?," in Proceedings of the 5th USENIX Conference on File and Storage Technologies (FAST '07), San Jose, CA, USA, 2007 - -[^ipfs_website]: IPFS: An open system to manage data without a central server," IPFS, 2024. [Online]. Available: https://ipfs.tech/. [Accessed: Sep. 28, 2024]. +[^bassam_18]: Bassam, S., et al. "On the Impossibility of Proving Availability in Decentralized Storage Networks". IEEE Security & Privacy, 2018. diff --git a/networks/networks.md b/networks/networks.md index 3858283..b6bb9e1 100644 --- a/networks/networks.md +++ b/networks/networks.md @@ -1,19 +1,19 @@ -# Codex networks +# Сети Codex - At Codex, we are launching several networks which are used for different purposes - | Network | Status | Blockchain | Purpose | - | ------------------ | ----------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | - | Devnet | :building_construction: | [Geth PoA](https://geth.ethereum.org/docs/fundamentals/private-network) | Dedicated for development purposes and following latest `master` builds | - | [Testnet](testnet) | :white_check_mark: | [Geth PoA](https://geth.ethereum.org/docs/fundamentals/private-network) | A public network for testing purposes, following latest releases | - | Mainnet | :construction: | :construction: | A main public network | +В Codex мы запускаем несколько сетей, которые используются для разных целей +| Сеть | Статус | Блокчейн | Назначение | +| ----------------- | ----------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| Devnet | :building_construction: | [Geth PoA](https://geth.ethereum.org/docs/fundamentals/private-network) | Предназначена для целей разработки и следует последним сборкам `master` | +| [Testnet](testnet) | :white_check_mark: | [Geth PoA](https://geth.ethereum.org/docs/fundamentals/private-network) | Публичная сеть для тестирования, следует последним релизам | +| Mainnet | :construction: | :construction: | Основная публичная сеть | - The main difference between networks are following - - Network purpose - - Bootstrap nodes - - Number of storage nodes - - Available storage volume - - Blockchain network - - Marketplace contract version - - Circuit files set used for proof verification +Основные различия между сетями следующие: +- Назначение сети +- Bootstrap-узлы +- Количество узлов хранения +- Доступный объем хранения +- Сеть блокчейна +- Версия контракта маркетплейса +- Набор файлов схем для верификации доказательств - The easiest way to start to use Codex is to [Join Testnet](testnet). +Самый простой способ начать использовать Codex - это [Присоединиться к Testnet](testnet). diff --git a/networks/testnet.md b/networks/testnet.md index 86688c8..398a34f 100644 --- a/networks/testnet.md +++ b/networks/testnet.md @@ -3,165 +3,165 @@ outline: [2, 4] --- # Codex Testnet -The Codex Testnet has been launched and is ready to be used for testing. +Codex Testnet запущен и готов к использованию для тестирования. -Your participation in the Codex Testnet is subject to the [Codex Testnet Terms and Conditions](https://github.com/codex-storage/codex-testnet-starter/blob/master/Codex%20Testnet%20Terms%20and%20Conditions.pdf) and [Codex Testnet Privacy Policy](https://github.com/codex-storage/codex-testnet-starter/blob/master/Codex%20Testnet%20Privacy%20Policy.pdf). +Ваше участие в Codex Testnet регулируется [Условиями использования Codex Testnet](https://github.com/codex-storage/codex-testnet-starter/blob/master/Codex%20Testnet%20Terms%20and%20Conditions.pdf) и [Политикой конфиденциальности Codex Testnet](https://github.com/codex-storage/codex-testnet-starter/blob/master/Codex%20Testnet%20Privacy%20Policy.pdf). -**Guides.** We have basic guides covering how to set up a Storage Client which can be used to upload and persist files by buying storage in the Codex network. We recommend that you start with those. +**Руководства.** У нас есть базовые руководства по настройке Storage Client, который можно использовать для загрузки и хранения файлов путем покупки хранилища в сети Codex. Мы рекомендуем начать с них. -Running a Storage Provider is more involved and is covered as a separate guide which demonstrates the storage sales side, as well as how to run Codex with its own local Ethereum execution client. +Запуск Storage Provider требует больше усилий и рассматривается в отдельном руководстве, которое демонстрирует сторону продажи хранилища, а также как запустить Codex с собственным локальным клиентом выполнения Ethereum. -Guides are available either on Discord, as step-by-step, interactive guides, or here as simple instructions that you can follow: +Руководства доступны либо в Discord в виде пошаговых интерактивных руководств, либо здесь в виде простых инструкций, которым вы можете следовать: -- **Basic: running a storage client.** [[Discord](#sc-guide-discord) | [web](#sc-guide-web)] -- **Advanced: Running a storage provider.** [[web](#sp-guide-web)] +- **Базовое: запуск storage client.** [[Discord](#sc-guide-discord) | [web](#sc-guide-web)] +- **Продвинутое: Запуск storage provider.** [[web](#sp-guide-web)] -The guides were tested on the following operating systems: +Руководства были протестированы на следующих операционных системах: - Linux: Ubuntu 24.04, Debian 12, Fedora 40 - macOS: 15 - Windows: 11, Server 2022 -## Running a Storage Client (Discord Version) {#sc-guide-discord} +## Запуск Storage Client (версия Discord) {#sc-guide-discord} -You can join [Codex Discord server](https://discord.gg/codex-storage) and jump into the [#:tv:|join-testnet](https://discord.com/channels/895609329053474826/1289923125928001702) channel. +Вы можете присоединиться к [серверу Codex Discord](https://discord.gg/codex-storage) и перейти в канал [#:tv:|join-testnet](https://discord.com/channels/895609329053474826/1289923125928001702). -It is mostly the same as a [Web guide](#sc-guide-web), but uses Discord capabilities so you can have an interactive, step-by-step guide, and you also can get a support in the [#:sos:|node-help](https://discord.com/channels/895609329053474826/1286205545837105224) channel. +Это в основном то же самое, что и [Веб-руководство](#sc-guide-web), но использует возможности Discord, чтобы вы могли иметь интерактивное пошаговое руководство, а также получить поддержку в канале [#:sos:|node-help](https://discord.com/channels/895609329053474826/1286205545837105224). -## Running a Storage Client (Web Version) {#sc-guide-web} +## Запуск Storage Client (Веб-версия) {#sc-guide-web} -**Prerequisites** +**Предварительные требования** - - Access to your Internet router so you can [configure port forwarding](#basic-common) + - Доступ к вашему интернет-маршрутизатору для [настройки проброса портов](#basic-common) -Steps for [Linux/macOS](#basic-linux-macos) and [Windows](#basic-windows) are slightly different, so please use ones for your OS. +Шаги для [Linux/macOS](#basic-linux-macos) и [Windows](#basic-windows) немного отличаются, поэтому используйте те, которые подходят для вашей ОС.
### Linux/macOS {#basic-linux-macos} -1. Download the master tarball from the Codex testnet starter repository, and untar its contents: +1. Скачайте мастер-архив из репозитория Codex testnet starter и распакуйте его содержимое: ```shell curl -LO https://github.com/codex-storage/codex-testnet-starter/archive/master.tar.gz tar xzvf master.tar.gz rm master.tar.gz ``` -2. Navigate to the scripts folder: +2. Перейдите в папку со скриптами: ```shell cd codex-testnet-starter-master/scripts ``` -3. Install dependencies when required: +3. Установите зависимости при необходимости: ```shell # Debian-based Linux sudo apt update && sudo apt install libgomp1 ``` -4. Download Codex binaries from GitHub releases: +4. Скачайте бинарные файлы Codex из релизов GitHub: ```shell ./download_online.sh ``` -5. Generate an ethereum keypair: +5. Сгенерируйте пару ключей ethereum: ```shell ./generate.sh ``` - Your private key will be saved to `eth.key` and address to `eth.address` file. + Ваш приватный ключ будет сохранен в файле `eth.key`, а адрес - в файле `eth.address`. -6. Fill-up your address shown on the screen with the tokens: - - Use the web faucets to mint some [ETH](https://faucet-eth.testnet.codex.storage) and [TST](https://faucet-tst.testnet.codex.storage) tokens. - - We can also do this using Discord [# bot](https://discord.com/channels/895609329053474826/1230785221553819669) channel - - Use `/set ethaddress` command to enter your generated address - - Use `/mint` command to receive ETH and TST tokens - - Use `/balance` command to check if you have received test tokens successfully +6. Пополните ваш адрес, показанный на экране, токенами: + - Используйте веб-краны для получения [ETH](https://faucet-eth.testnet.codex.storage) и [TST](https://faucet-tst.testnet.codex.storage) токенов. + - Мы также можем сделать это с помощью канала Discord [# bot](https://discord.com/channels/895609329053474826/1230785221553819669) + - Используйте команду `/set ethaddress` для ввода вашего сгенерированного адреса + - Используйте команду `/mint` для получения ETH и TST токенов + - Используйте команду `/balance` для проверки успешного получения тестовых токенов -7. Run Codex node: +7. Запустите узел Codex: ```shell ./run_client.sh ``` -8. Configure [port forwarding](#basic-common) and we are ready go to. +8. Настройте [проброс портов](#basic-common), и мы готовы к работе. ### Windows {#basic-windows} -1. Download the master tarball from the Codex testnet starter repository, and untar its contents: +1. Скачайте мастер-архив из репозитория Codex testnet starter и распакуйте его содержимое: > [!WARNING] - > Windows antivirus software and built-in firewalls may cause steps to fail. We will cover some possible errors here, but always consider checking your setup if requests fail - in particular, if temporarily disabling your antivirus fixes it, then it is likely to be the culprit. + > Антивирусное ПО Windows и встроенные брандмауэры могут вызвать сбой шагов. Мы рассмотрим некоторые возможные ошибки здесь, но всегда учитывайте проверку вашей настройки, если запросы не выполняются - в частности, если временное отключение антивируса решает проблему, то, вероятно, он является причиной. ```batch curl -LO https://github.com/codex-storage/codex-testnet-starter/archive/master.tar.gz ``` - If you see an error like: + Если вы видите ошибку: ```batch curl: (35) schannel: next InitializeSecurityContext failed: CRYPT_E_NO_REVOCATION_CHECK (0x80092012) - The revocation function was unable to check revocation for the certificate. ``` - You may need to add the `--ssl-no-revoke` option to your curl call, e.g.: + Возможно, вам нужно добавить опцию `--ssl-no-revoke` к вашему вызову curl, например: ```batch curl -LO --ssl-no-revoke https://github.com/codex-storage/codex-testnet-starter/archive/master.tar.gz ``` -1. Extract the contents of the tar file, and then delete it: +1. Распакуйте содержимое tar-файла и затем удалите его: ```batch tar xzvf master.tar.gz del master.tar.gz ``` -2. Navigate to the scripts folder: +2. Перейдите в папку со скриптами: ```batch cd codex-testnet-starter-master\scripts\windows ``` -3. Download Codex binaries from GitHub releases: +3. Скачайте бинарные файлы Codex из релизов GitHub: ```batch download-online.bat ``` -4. Generate an ethereum keypair: +4. Сгенерируйте пару ключей ethereum: ```batch generate.bat ``` - Your private key will be saved to `eth.key` and address to `eth.address` file. + Ваш приватный ключ будет сохранен в файле `eth.key`, а адрес - в файле `eth.address`. -5. Fill-up your address shown on the screen with the tokens: - - Use the web faucets to mint some [ETH](https://faucet-eth.testnet.codex.storage) and [TST](https://faucet-tst.testnet.codex.storage) tokens. - - We can also do this using Discord [# bot](https://discord.com/channels/895609329053474826/1230785221553819669) channel - - Use `/set ethaddress` command to enter your generated address - - Use `/mint` command to receive ETH and TST tokens - - Use `/balance` command to check if you have received test tokens successfully +5. Пополните ваш адрес, показанный на экране, токенами: + - Используйте веб-краны для получения [ETH](https://faucet-eth.testnet.codex.storage) и [TST](https://faucet-tst.testnet.codex.storage) токенов. + - Мы также можем сделать это с помощью канала Discord [# bot](https://discord.com/channels/895609329053474826/1230785221553819669) + - Используйте команду `/set ethaddress` для ввода вашего сгенерированного адреса + - Используйте команду `/mint` для получения ETH и TST токенов + - Используйте команду `/balance` для проверки успешного получения тестовых токенов -6. Run Codex node: +6. Запустите узел Codex: ```batch run-client.bat ``` - 7. Configure [port forwarding](#basic-common) and we are ready go to. + 7. Настройте [проброс портов](#basic-common), и мы готовы к работе. -### All OS {#basic-common} +### Все ОС {#basic-common} -Configure [port forwarding](https://en.wikipedia.org/wiki/Port_forwarding) on your Internet router -| # | Protocol | Port | Description | -| - | -------- | ------ | ----------------- | +Настройте [проброс портов](https://en.wikipedia.org/wiki/Port_forwarding) на вашем интернет-маршрутизаторе +| # | Протокол | Порт | Описание | +| - | -------- | ------ | -------------- | | 1 | `UDP` | `8090` | `Codex Discovery` | | 2 | `TCP` | `8070` | `Codex Transport` | -After your node is up and running, you can use the [Codex API](/developers/api) to be able to interact with your Codex node, please check our [API walk-through](/learn/using) for more details. +После того как ваш узел запущен и работает, вы можете использовать [Codex API](/developers/api) для взаимодействия с вашим узлом Codex, пожалуйста, ознакомьтесь с нашим [пошаговым руководством по API](/learn/using) для получения более подробной информации. -You also can use [Codex App UI](https://app.codex.storage) to interact with your local Codex node. +Вы также можете использовать [Codex App UI](https://app.codex.storage) для взаимодействия с вашим локальным узлом Codex. -Need help? Reach out to us in [#:sos:|node-help](https://discord.com/channels/895609329053474826/1286205545837105224) channel or check [troubleshooting guide](/learn/troubleshoot.md). +Нужна помощь? Обратитесь к нам в канале [#:sos:|node-help](https://discord.com/channels/895609329053474826/1286205545837105224) или проверьте [руководство по устранению неполадок](/learn/troubleshoot.md). -## Running a Storage Provider (Web Version) {#sp-guide-web} +## Запуск Storage Provider (Веб-версия) {#sp-guide-web} -Work in progress :construction: +В процессе разработки :construction: -## Testnet Data +## Данные Testnet -### Bootstrap Nodes +### Bootstrap-узлы **Codex** ```shell spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P @@ -184,20 +184,20 @@ enode://6eeb3b3af8bef5634b47b573a17477ea2c4129ab3964210afe3b93774ce57da832eb110f enode://6ba0e8b5d968ca8eb2650dd984cdcf50acc01e4ea182350e990191aadd79897801b79455a1186060aa3818a6bc4496af07f0912f7af53995a5ddb1e53d6f31b5@209.38.160.40:40070 ``` -### Smart contracts +### Смарт-контракты -| Contract | Address | -| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| Token | [`0x34a22f3911De437307c6f4485931779670f78764`](https://explorer.testnet.codex.storage/address/0x34a22f3911De437307c6f4485931779670f78764) | -| Verifier | [`0x02dd582726F7507D7d0F8bD8bf8053d3006F9092`](https://explorer.testnet.codex.storage/address/0x02dd582726F7507D7d0F8bD8bf8053d3006F9092) | -| Marketplace | [`0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed`](https://explorer.testnet.codex.storage/address/0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed) | +| Контракт | Адрес | +| ----------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| Токен | [`0x34a22f3911De437307c6f4485931779670f78764`](https://explorer.testnet.codex.storage/address/0x34a22f3911De437307c6f4485931779670f78764) | +| Верификатор | [`0x02dd582726F7507D7d0F8bD8bf8053d3006F9092`](https://explorer.testnet.codex.storage/address/0x02dd582726F7507D7d0F8bD8bf8053d3006F9092) | +| Маркетплейс | [`0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed`](https://explorer.testnet.codex.storage/address/0xfFaF679D5Cbfdd5Dbc9Be61C616ed115DFb597ed) | -### Endpoints +### Эндпоинты -| # | Service | URL | -| - | --------------- | ---------------------------------------------------------------------------- | +| # | Сервис | URL | +| - | -------------- | ---------------------------------------------------------------------------- | | 1 | Geth Public RPC | [rpc.testnet.codex.storage](https://rpc.testnet.codex.storage) | -| 2 | Block explorer | [explorer.testnet.codex.storage](https://explorer.testnet.codex.storage) | -| 3 | Faucet ETH | [faucet-eth.testnet.codex.storage](https://faucet-eth.testnet.codex.storage) | -| 4 | Faucet TST | [faucet-tst.testnet.codex.storage](https://faucet-tst.testnet.codex.storage) | -| 5 | Status page | [status.testnet.codex.storage](https://status.testnet.codex.storage) | +| 2 | Обозреватель блоков | [explorer.testnet.codex.storage](https://explorer.testnet.codex.storage) | +| 3 | Кран ETH | [faucet-eth.testnet.codex.storage](https://faucet-eth.testnet.codex.storage) | +| 4 | Кран TST | [faucet-tst.testnet.codex.storage](https://faucet-tst.testnet.codex.storage) | +| 5 | Страница статуса | [status.testnet.codex.storage](https://status.testnet.codex.storage) |